Variables and assignment

A variable provides the programmer with a named storage area whose contents can be manipulated.

Some programming languages, including Java, are strongly typed languages, which means that it is necessary to declare what kind of data will be associated with the variable before it can be used.

For example

int myInt;

tells Java that the variable myInt will contain data of type int (the int data type is used for integers - that is positive and negative whole numbers). Once a variable has been declared its type is fixed.

Once a variable has been declared, a value can be assigned to it using the assignment operator (=) providing the value being assigned is compatible with the declaration type. For example, in this case we can write:

myInt = 3;

If the type of the value being assigned is not compatible with the declaration type, Java will give an error message.

The value associated with the variable can be changed at any time by using the assignment operator, which then overwrites the original value with the new value. For example, after the following statement has been executed, the variable myInt holds the int value 5.

myInt = 5;

The declaration and initialisation of a variable can also be achieved in a single line of code:

int myInt = 3;

which is equivalent to:

int myInt;

myInt = 3;

To access the value associated with a variable, the variable name is used. So, after executing this Java code:

int myInt = 3;

int yourInt = 5;

int result = myInt + yourInt;

The variable result will contain 8.

In programming, scope refers to the lifetime and accessibility of a variable. The scope of a variable in a Java program depends on where it is declared. Java defines several kinds of variable, but the two types that you will encounter most often are instance variables and local variables. Instance variables are declared in a class but outside of the constructors and methods of a class, and their scope is the whole class, meaning they are accessible anywhere within the class. A local variable is declared within a constructor or method and its scope is confined to the constructor or method.

Comparing Java with Python

Java is more strongly typed than Python. In Python it is not necessary to declare a variable before using it, but in Java if you attempt to use a previously undeclared variable a "symbol not found" error will be reported.

Once a variable has been declared in Java, it can only hold data that is compatible with the declared type. In Python, however, the type of data that can be assigned to a variable can change throughout the program.

Test your understanding

  1. Write the declaration of a Java variable isChild of type boolean.
  2. Write a single Java statement to declare the variable myModule to be of type String and assign the value "M250" to it.