Variables in Mercury
In Java, variables are explicitly declared and used by the compiler to check type-correctness of method calls.
public class Variables {
public static void main(String[] args) {
// String declares a variable
String a = "initial";
System.out.println(a);
// You can declare multiple variables at once
int b = 1, c = 2;
System.out.println(b + " " + c);
// Java will infer the type of initialized variables using var (Java 10+)
var d = true;
System.out.println(d);
// Variables declared without initialization are given default values
// For example, the default value for an int is 0
int e;
System.out.println(e);
// In Java, there's no direct equivalent to Go's := syntax
// But you can use var for type inference in local variables (Java 10+)
var f = "apple";
System.out.println(f);
}
}
To run the program, compile it and then use java
:
$ javac Variables.java
$ java Variables
initial
1 2
true
0
apple
In Java, variables are declared with their type (or var
for local variable type inference in Java 10+). Unlike Go, Java doesn’t have a shorthand :=
syntax for declaring and initializing variables.
Variables in Java are also explicitly declared, and the compiler uses this information to check for type correctness. When a variable is declared without initialization, it’s given a default value (e.g., 0 for int
, null
for objects).
Java’s var
keyword (introduced in Java 10) allows for local variable type inference, which is similar to Go’s type inference, but it’s only available for local variables with initializers.