Variable declaration and initialization

Now let’s talk about variables. There are two steps of variable creation – declaration and initialization.

Declaration

Declaration is a process of defining variable type and name. It’s like we are “reserving” a place, where the variable value would be stored.

public class VariableCreation {

    public static void main(String... args) {
        int a;
    }

}

Here we declare a variable of type int with name “a”.

Also we can declare as many variables of same type as we need using comma(please, notice that it is a bad practice, because it lowers code readability):

public class VariableCreation {

    public static void main(String... args) {
        int b, c, d;
    }

}

Initialization

Initialization is a process of assigning a value to declared variable.

public class VariableCreation {

    public static void main(String... args) {
        int x;
        x = 5;
        System.out.println(x);
    }

}

Now we’ve assigned a value “5” to variable “x” and than print value of x using System.out.println method (it should print “5”, try it yourself).

Declaration and initialization process can be done in one statement (and that is a recommended way to create variables):

public class VariableCreation {

    public static void main(String... args) {
        int y = 5;
        System.out.println(y);
    }

}

This is also possible for multiple variables (but still bad practice):

public class VariableCreation {

    public static void main(String... args) {
        int r, s, t = 5;
        System.out.println(t);
    }

}

Source code can be found here.

Scroll to Top