Variables

In Java, variables are explicitly declared and used by the compiler to e.g. check type-correctness of function calls.

public class Variables {
    public static void main(String[] args) {
        // Declaring a single variable
        String a = "initial";
        System.out.println(a);

        // Declaring multiple variables at once
        int b = 1, c = 2;
        System.out.println(b + " " + c);

        // Java will infer the type of initialized variables if using 'var' (Java 10+)
        var d = true;
        System.out.println(d);

        // Variables declared without a corresponding initialization are "default-valued". For example, the default value for an int is 0.
        int e;
        // Java requires the variable to be initialized before use, hence we initialize `e` implicitly
        e = 0;
        System.out.println(e);

        // The shorthand := syntax in Go does not exist in Java, but we declare and initialize variables in one line as seen earlier
        String f = "apple";
        System.out.println(f);
    }
}

To run the program, compile the code into a .class file and then use java to execute it.

$ javac Variables.java
$ java Variables
initial
1 2
true
0
apple

Now that we can run and build basic Java programs, let’s learn more about the language.

Next example: Constants.