Variables & Data Types
Unlike Python or JavaScript, Java variables need an explicit type when
declared: int age = 21;.
Example: declaring several typed variables
public class Main {
public static void main(String[] args) {
String name = "Ada";
int age = 21;
System.out.println(name + " is " + age + " years old.");
}
}
Ada is 21 years old.
Common types: int (whole numbers), double
(decimals), boolean (true/false), and String
(text — capitalised, since it's technically a class, not a primitive
type like the others). Try assigning a number to name
instead of text, and Java refuses to even compile the program — this
compile-time type checking is exactly what "statically-typed" means in
practice, not just a definition to memorize.
public class Main {
public static void main(String[] args) {
String name = "Ada";
int age = 21;
System.out.println(name + " is " + age + " years old.");
}
}
Ada is 21 years old.