The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Java
Variables and types
What is a variable, and what does a type decide?
Why it exists — If you write the values used in a calculation directly as numbers every time, then when the same value is used in several places, there are several places to fix, and a value that changes while the program runs, such as an age that goes up by one, cannot be carried on. A variable stores a value under a name and lets you read and change it again by that name. Java has you decide a type for each variable, so the compiler catches the mistake of using the wrong kind of value before you run the program.
Where it's used today — You see variables everywhere in Java code. The name a user typed, the number of items and the total in a shopping cart, and i, which counts which pass of a loop you are on, are all handled as variables. A value that must not change after you decide it is declared with final so that it cannot be assigned again.
A variable is a name given to a storage location where a value is stored. A variable of a primitive type such as int stores the value itself, and a variable of a reference type such as String stores a reference that points to an object, not the object. The single line int age = 20; has three parts. int is the type, which means that this variable holds only integers. age is the name. 20 is the value to store first. This line is called a declaration. When the compiler reads a declaration, it remembers that "age is an int variable," and before the program runs it checks that the lines after it fit what it remembered. In this lab you remove the type int, change the value that is stored, and store no value at all. Each time, the same code is compiled and run, so you can see what the compiler reports and what is printed.
Checked against real execution · Six combinations were compiled with javax.tools on JDK 21, run, and checked against the results
Concepts in this lab
- Variable
- A variable is a name for a storage location where a value is stored. A variable of a primitive type such as int stores the value itself, and a variable of a reference type such as String stores a reference that points to an object, not the object. Every variable has a type that is already fixed at compile time, and the type decides what kind of value the variable can hold. For example, a variable declared as int age; can hold only integers, and int is a 32-bit integer from -2147483648 to 2147483647. A value is stored in a variable with =, and age = age + 1; means "store the value calculated on the right in the variable on the left." The stored value can change, but the name and the type of the variable do not change. Trying to store a value that does not fit the type is a compile-time error.
- Declaration and initialization
- Why it exists — If you could use a name right away without declaring it, a line with a misspelled name would be treated as creating one more new variable, and the mistake would not show. Java makes you declare the name and type first before use, so that the compiler finds such typos before running.
- Where it's used today — When you keep a value that changes as it is calculated, such as a total or a count, inside a method, the form that gives the first value right at the declaration, as in int count = 0;, is commonly used. If the value differs for each branch of an if statement, you only declare first and decide the value in each branch.
- A declaration is the line that creates a variable inside a method. It is called a local variable declaration, and it gives a type, a name, and optionally a first value after = (the initialization). int age; only declares, and int age = 20; declares and initializes at the same time. If you use a name that was not declared, the compiler cannot find the name and reports an error. A local variable, unlike a field, does not automatically get a default value such as 0, so a value must be stored in it before it is read, or else it is a compile-time error. A name written on the left of =, where a value is stored, does not count as reading.
- Type
- Why it exists — If the kind of a value is not decided, mistakes such as multiplying text or calling a method that does not exist show up only when the program is run and reaches that line. Java's types find such mistakes before running, at compile time.
- Where it's used today — You write it when declaring variables, parameters, and the values a method returns. An editor such as IntelliJ looks at the type and shows the list of methods that can be called on that value.
- A type is a name that decides what kind of value a variable can point to or hold. The types of Java are divided into primitive types and reference types, and the reference types are class types, interface types, type variables, and array types. A name can be used as a type only when there is a class or interface declaration for it. List (an interface) and ArrayList (a class) that Java provides are types declared in that way. On every line that puts a value in a variable, the compiler checks that the type of the value is the same as the type of the variable or a subtype of it, and it also looks up the methods you can call through the variable in the type of the variable. So through a variable of type List you cannot call trimToSize, which only ArrayList has, even if the actual object is an ArrayList.
- Primitive types and reference types
- These are the two kinds into which the types of Java are divided. There are eight primitive types, byte, short, int, long, float, double, char, and boolean, and a variable of one of them holds the value itself. Reference types are all the other types, such as classes, interfaces, and arrays, and a variable of one of them holds a reference to an object, not the object itself. So assigning a variable of a primitive type copies the value, and the two variables do not affect each other, but assigning a variable of a reference type copies the reference, and the two variables come to refer to the same object. A variable of a reference type can hold null, which means that it refers to no object, and a variable of a primitive type cannot hold null.
Try these
- Default settings — The variable is declared with the name age and the type int, and 20 is stored in it. Compiling succeeds and 21 is printed.
- Remove the type int — The compiler does not know what age is, so it reports an error that the name is not declared.
- Store "twenty" — You get a compile error saying that text cannot be stored in an int variable.
- Store no value — The variable is created, but the code reads it before a value is stored, which is a compile error.
Running with the default settings
- The compiler reads main from the top. First it reads the line int age = 20;. This line has three parts. int is the type, which means that only integers are stored. age is the name. 20 is the value to store. The compiler remembers that "the name age is a variable of type int."
- The compiler checks the value to store. 20 is an integer, so it can be stored in the int variable age, which holds only integers.
- The compiler checks the line age = age + 1;. The age + 1 on the right reads the value stored in age. age is declared as an int and a value was stored in it on the previous line, so it can be read. The result of adding 1 to an int is also an integer, so it may be stored in age again.
- The compiler checks the line System.out.println(age);. age is an int variable and has a value stored in it, so it can be read and printed.
- Compiling succeeds, and the Main class file to run is created. Whether age is an int, whether the stored value fits, and whether age can be read were all checked now, while compiling, and not when the program runs.
- You run it with java Main. main starts, and the line int age = 20; runs. An int slot with the name tag age is created, and 20 is stored in that slot.
- The line age = age + 1; runs. First it calculates the age + 1 on the right. Adding 1 to the 20 in the age slot gives 21. This value is stored in the same age slot. The slot stays the same, and only the value inside changes from 20 to 21. Here = does not mean "equals." It means "store the result on the right in the slot on the left."
- System.out.println(age); runs. It reads the value in the age slot and prints 21 on the screen.
Result of this run
- A variable is a name given to a storage location where a value is stored. int age = 20; has three parts: the type int (which means only integers are stored), the name age, and the value to store, 20. At this line the compiler remembered that "age is an int variable," and it checked that the lines after it fit what it remembered before the program ran.
- When run, 20 was stored in the age slot, age = age + 1; changed the value in the same slot to 21, and 21 was printed. The name and the slot of a variable stay the same, and only the value inside can change.
Code
public class Main {
public static void main(String[] args) {
// Declaration: create a variable age of type int and store 20 in it
int age = 20;
age = age + 1;
System.out.println(age);
}
}
Assumptions of this model
The compiler and the runtime environment are JDK 21.0.12.1 (javac 21). All six combinations were compiled with javax.tools from the same source as the code on the screen (identical line by line). The ones that compiled successfully were loaded with a new class loader and Main.main was run, and the results were checked against the captured standard output. What was checked is whether compiling succeeded, the diagnostic code of the first error (compiler.err.cant.resolve.location, prob.found.req, and var.might.not.have.been.initialized, which are shown on the screen as the three error descriptions), the number of errors and the lines they occurred on, whether the Main class file was created, and the output when run. The documentation was checked by opening the Java Language Specification (Java SE 21) directly. That every variable and expression has a type known at compile time follows the beginning of chapter 4; that a variable is a storage location with a compile-time type follows section 4.12; that a variable of a primitive type holds only values of that type follows section 4.12.1; that int is a 32-bit signed integer follows sections 4.2 and 4.2.1; that a local variable declaration consists of a type (or var), a name, and an optional initializer follows section 14.4; that a variable declared without an initializer must be assigned before it is read, or else it is a compile-time error, follows sections 14.4.2 and 4.12.5 and the beginning of chapter 16. That a local variable, unlike a field, does not automatically get a default value is also in section 4.12.5. That only reading a value counts as access, and the name on the left of = does not, is in the beginning of chapter 16. The kinds of errors, the number of errors, and the lines they occur on are not set by the specification but were observed with this javac. When there are several errors javac reports all of them, but the table shows only the first. In every combination that failed to compile, the Main class file was not created, which is why the screen says it cannot run. In the combination with neither the type int nor a value, the declaration line was left out entirely. A line with only age; and no type is not a statement allowed by the grammar (section 14.8: the only expressions that can be used as statements are assignments, increments and decrements, method invocations, and object creations), and when this form was compiled once separately, javac gave a syntax error saying not a statement (it was not included in the check of the combinations). This lab covers only a local variable and a single int. It does not cover other primitive types, variables of reference types, var, naming and scope of variables, or constants (final). How values are copied for variables of primitive and reference types is covered in "In-depth lab: Variables and types".
Next lab: Methods