A Variable is a box that contains a specific value. The variable’s type denotes the kind of value it can store. For example, a variable of type “int” is a variable that can contain whole numbers (integers). Similarly, a variable of type “double” is a variable that can store decimals (floating point numbers).

Figure 1 – Variables

In figure 1, each box has a specific name and holds a particular value. One could ask “what is inside box3?”. Obviously, the answer would be the value -1.2. In programming, variables are used to store and read values when necessary.

Declaring Variables

Declaring a variable stands for creating a variable. To declare a variable two components are necessary: the type and the identifier (name of the variable). For example, double box3; where double is the type and box3 is the name.

public class Main{
    public static void main(String[] args) {
        double box3;
    }
}

If you want to declare a variable that holds a character such as box2 in Figure 1, you would write char box2;

public class Main{
    public static void main(String[] args) {
        char box2;
    }
}

Note that you cannot declare a variable with the same identifier more than once.

Identifiers

An identifier is a unique name that is used to refer to a variable. In other words, it is the variable name. Now that we know how to declare a variable, we need to know what is a valid name for our variable.

  • A variable name can consist of Captial letters (A-Z), lowercase letters (a-z), digits (0-9), underscores (_), and dollar sign ($)
  • A variable name’s first character cannot be a digit (1average is not a valid name)
  • A variable name cannot contain any blank spaces (average speed is not a valid variable name)
  • A variable name cannot be similar to a reserved Java keyword (table 1)
abstract continue fornewswitch
assertpackage synchronizeddefaultgoto
booleandoifprivatethis
breakelseimportpublicthrow
byteenumimplements protected throws
casedoubleinstanceof returntransient
catchextends intshorttry
charfinalinterfacestaticvoid
classfinallylongstrictfp volatile
constfloatnativesuperwhile
Table 1 – List of reserved keywords in java

Note that a variable name in java

  • Is case sensitive (averageSpeed is a different variable than AverageSpeed)
  • Has no limit to its length

By convention, the variable name should

  • Have a meaning (For example, averageSpeed is a better name than x)
  • Have a length of between 4 and 15 characters
  • Use naming conventions such camel-case in which each first letter of a word is capitalized at the exception of the first word. (example: averageSpeed, yearlyEmployeeSalary). Read more about naming conventions here.

Some examples of valid and invalid names are provided in Table 2.

Valid Invalid
employeeSalary1employeeSalary (starts with a number)
$employeeSalaryemployee Salary (contains space)
_EmployeeSalaryemployee#salary (contains #)
employee_salary_123eployeesalary? (contains ?)
EMPLOYEESALARYabstract (reserved java keyword)
Table 2 – Example of valid and invalid variable names in java

Initialising Variables

Now that we successfully declared our double variable box3, we would probably want to store data in it. Initializing a variable is placing/assigning a value in a declared variable for the first time. This is done by using the assignment (=) sign. For instance, box3 = 1.2;

public class Main{
    public static void main(String[] args) {
        double box3;
        box3 = 1.2;
    }
}

Note that, if you do not initialize a variable, it will hold the value of 0 by default for double types in java. This statement does not hold for different programming languages.

Printing Variables

One of the numerous tasks we could do with a variable is to display it on the screen. To achieve this, we would place the variable name inside System.out.println(). The following code does not output “box3” but it outputs the value that is inside box3, hence, it will print “1.2”.

public class Main{
    public static void main(String[] args) {
        double box3;
        box3 = 1.2;
        System.out.println(box3);
    }
}

We can take it further by mixing messages with variables in our print statement.

public class Main{
    public static void main(String[] args) {
        double box3;
        box3 = 1.2;
        System.out.println("The value stored in box3 is: " + box3);
    }
}

In the example above, when we write the name of the variable “box3” in the print statement, we are “using” this variable.

You may overwrite the value (change the value) of the variable at any given time. When using the variable, the latest value before the statement that uses it will apply. In the example below, the first print statement will display “At this point, box 3 = 1.2” and the second one will display “At this point, box3 = 4.5”.

public class Main{
    public static void main(String[] args) {
        double box3;
        box3 = 1.2;
        System.out.println("At this point, box3 = " + box3);
        box3 = 4.5;
        System.out.println("At this point, box3 = " + box3);
    }
}

Data Types

Data types refer to the nature of the value that is stored in a variable. There are two categories of data types: primitive data types and non-primitive data types (more on this later). There are 8 primitive data types in java.

Data TypeSizeDescription
byte1 byteStores whole numbers from -128 to 127
short2 bytesStores whole numbers from -32,768 to 32,767
int4 bytesStores whole numbers from -2,147,483,648 to 2,147,483,647
long8 bytesStores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float4 bytesStores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double8 bytesStores fractional numbers. Sufficient for storing 15 decimal digits
boolean1 bitStores true or false values
char2 bytesStores a single character/letter or ASCII values

Note that in Figure 1. box 4 contains “Hello” which has a String data type. The latter is a non-primitive data type which we will discuss more later.

Additional Tips

A variable can be declared and initialized in one line.

public class Main{
    public static void main(String[] args) {
        double box3 = 1.2;
        System.out.println("The value stored in box3 is: " + box3);
    }
}

Multiple variables of the same type can be declared on multiple lines or on the same line. All below code examples are valid.

public class Main{
    public static void main(String[] args) {
        double box3;
        box3 = 1.2;
        double x;
        x = - 3.5;
        System.out.println("The value stored in box3 is: " + box3);
    }
}
public class Main{
    public static void main(String[] args) {
        double box3, x;
        box3 = 1.2;
        x = - 3.5;
        System.out.println("The value stored in box3 is: " + box3);
    }
}
public class Main{
    public static void main(String[] args) {
        double box3 = 1.2, x = - 3.5;
        System.out.println("The value stored in box3 is: " + box3);
    }
}

Practice!

Practice variables & types by downloading this exercise sheet.

Check your solutions by downloading this solution sheet.

Other Lessons in Introduction to Programming in Java

No. Lesson Reading Time
1 Introduction to Java 5 mins
2 Setting up the environment in Java 5 mins
3 Java Hello World Program 5 mins
4 Java Output 5 mins
5 Java Escape Characters 5 mins
6 Variables & Types 5 mins
7 Arithmetic Operators in Java 5 mins

Related Subjects

or view all subjects
No realted subjects found.