Title here
Summary here
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 in some cases
var d = true;
System.out.println(d);
// Variables declared without a corresponding
// initialization are given default values. For example,
// the default value for an int is 0.
int e;
System.out.println(e);
// In Java, we don't have a direct equivalent to Go's := syntax.
// Instead, we use the var keyword (introduced in Java 10)
// for local variable type inference.
var f = "apple";
System.out.println(f);
}
}
When you run this program, you’ll see:
initial
1 2
true
0
apple
In Java:
String
, int
, boolean
, etc., to declare variables with specific types.var
keyword (introduced in Java 10) can be used for local variable type inference, which is similar to Go’s type inference.:=
syntax. We either declare the type explicitly or use var
for type inference.System.out.println()
for console output, which is analogous to Go’s fmt.Println()
.Remember that in Java, all code must be inside a class, and the entry point of the program is the main
method in a public class.