Java Variables

A variable is a construct that allows us to give a name to a memory location. A variable has a data type and a value.

In Java the value of a variable can be a reference / pointer to a memory location where the value is stored, as is the case with reference types. Alternatively, the value can be stored directly as is the case with primitive types.

In this short tutorial we’ll look at variables in Java. We will explain the different types of variables and how they are declared.

There are three main types of variables in Java:

  • local variables
  • instance variables
  • static variables
  • method parameters

Before we begin it is important to mention that when we work with variables in Java, we don’t mutate the variable directly. Instead, we manipulate the memory location, to which a variable represents.

Moreover, Java is an imperative language, so by default, and the normal way to work with variables is to mutate their state. If we consider newer JVM languages such as: Kotlin, and Scala, these languages provide support for immutable variables out of the box. They also make the distinction between mutable and immutable variables.

We should also mention that we can create immutable variables in Java using the final keyword.

Declaring Variables

We can declare variables in Java by specifying a data type, followed by the variable name, followed by an optional value.

1
<DATE_TYPE> <VARIABLE_NAME> = <VALUE>;

For example we can declare a variable in Java of type int as follows:

1
int x = 1;

Moreover, we can declare a variable without a value:

1
int x;

However, we must assign the variable with a value before use. Otherwise, the code will not compile.

1
System.out.println(x);  //compile time error

Types Of Variables

As mentioned we can create different types of variables in Java. Let’s examine these now.

Local Variables

Local variables are defined within a block of code. This block could be a constructor, method, if, switch, loop etc. These variables normally have a scope which is the block in which the variable is declared.

For example, if we declare a local variable inside an if block, can we access it outside of the if block?

1
2
3
4
5
6
7
8
int x = 1;

if(x==1) {
     int y = 2;
     y++;
}

System.out.println(y);  // compile error y is not in scope

As we can see above, if we try to access the y variable outside the if block it results in a compile error.

Instance Variables

Instance variables are variables defined in a class outside of any method, constructor. block etc. Also instance variables are not static, therefore they cannot be accessed from static members of the class, unless of course they are accessed through an instance of the class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public final class Point {
    private  int x;
    private int y;

    public Point() {
    }

    public Point(final int x, final int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Point moveX(final int amount) {
        final int newX = x + amount;

        if (newX < 0) {
            throw new IllegalArgumentException("X cannot be less than zero, after move");
        }

        return new Point(newX, getY());
    }
}

For example in the above Point class the variables x, and y are instance variables. Instance variables are created when an object of a class is created and destroyed when an object ceases to exist.

Instance variables also are accessible, from any non static block: method, constructor etc inside of the class.

1
2
3
public int getX() {
    return x;
}

Above we can access the x instance variable from within the getX() instance method.

Moreover, as we can see in the above class, instance variables can also have access modifiers, such as public, private, protected, that control the visibility / access of the variable from outside of the class. If no access modifier is specified it will be assigned the default modifier, which is package access.

An instance variable also does not have to be initialized, and if not, it receives a default value depending on its type. In the case of an int data type, this is the value 0.

1
2
Point point = new Point();
System.out.println(point.getX()); // prints 0

Static Variables

Static variables are also known as class variables. These variables are similar to instance variables, with some subtle differences.

Static variables are defined with the static keyword, and just like instance variables they are defined within a class outside of any method, constructor, or block. Moreover, there can only be one copy of a static variable per class, so static variables are shared across all object instances of a class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static final class Point {

    public static final Point ORIGIN = new Point(0, 0);

    private int x;
    private int y;


    public Point() {
    }

    public Point(final int x, final int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Point moveX(final int amount) {
        final int newX = x + amount;
        if (newX < 0) {
            throw new IllegalArgumentException("X cannot be less than zero, after move");
        }
        return new Point(newX, getY());
    }
}

Above we update the point class with a static variable that exposes a Point that represents an origin. Static variables should also be accessed via the class.

1
Point.ORIGIN

We can still access static variables through an object instance of a class. However, this will result in a compiler warning, although the code will still compile.

1
2
Point point = new Point();
point.ORIGIN.getX();

Method Parameters

Variables can also act as method parameters. Method parameters are part of a methods signature.

1
2
3
4
5
6
public int add(int x, int y) {
    while (y-- > 0) {
        x = ++x;
    }
    return x;
}

In the above example the variables x, and y are method parameters. Method parameters are tied to the scope of the method.

Java Variable Naming Conventions

Let’s quickly review some of the rules and conventions related to naming variables.

Case Sensitive

Java variable names are case sensitive. For example the variables:

1
2
Point maySales;
Point MaySales;

are different variables.

Variable Naming Rules

Variable names can start with a _ character, $ character, or a letter.

1
2
3
4
5
6
int $varOne; //ok
int _varTwo; //ok
int varThree; //ok

int 3var // compile error
int *var //compile error

Moreover, after the first character of the variable name, the name can also contain digits.

1
2
3
4
5
int $var1; //ok
int _var2; //ok
int var3; //ok
int var4.0 // compile error
var var4-0 //compile error

Moreover, variable names cannot be Java reserved keywords.

1
2
3
4
5
int final1; //ok

int double; //compile error reserved error
int if;//compile error reserved error
String for;//compile error reserved error

Variable Naming Conventions

Java variables have a few naming conventions. These conventions help to improve understanding and readability. Firstly, if a variable name contains a single word it is written in lowercase.

1
Point origin = Point.ORIGIN;

However, if a variable name consists of multiple words we use camel case.

1
2
Point maySales = new Point(5,100);
Point mayStaffExpenses = new Point(5,-50);

Static variables that represent constants use uppercase characters and words are separated with an underscore (_).

1
2
3
public static final Point ORIGIN = new Point(0,0);

public static final Point X_INTERCEPT = new Point(1,0);

Local Variable Type Inference

Java 10 introduced a new mechanism in which the compiler can infer the type of the variable by looking at the variables value.

1
var myString = "My String";

Above the compiler reads the value My String and resolves it as a java.lang.String. The above is equivalent to:

1
String myString = "My String";

Conclusion

In this short tutorial we examined the different types of variables in Java.