DEV Community

Alan
Alan

Posted on

Java By Example: Variables

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

class Variables {
  public static void main(String[] args) {

    //You can declares 1 or more variables.
    String a = "initial";
    System.out.println(a);

    // You can declare multiple variables at once.
    Integer b = 1, c = 2;
    System.out.println(b + " " + c);

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

    // Variables declared without a corresponding initialization are not able to be called, calling will be resulting in error.
    // Integer e;
    // System.out.println(e);
  }
}
Enter fullscreen mode Exit fullscreen mode
javac Variables.java
java Variables
# initial
# 1 2
# true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)