Variables and constants
A variable is a named box that holds one value of one type. In Java the type is fixed when you declare the variable and can never change: an int box only ever holds whole numbers. You write the type, the name, and optionally an initial value: int age = 30;. Assigning later uses just the name: age = 31;.
public class Main {
public static void main(String[] args) {
int age = 30; // declare and initialise
String name = "Asha"; // String is a class, not a primitive
double height; // declare now...
height = 1.68; // ...assign later
age = age + 1; // reassign: the type stays int
final double TAX_RATE = 0.18; // final = cannot be reassigned
var city = "Pune"; // var: the compiler infers String
var count = 3; // inferred int
System.out.println(name + " is " + age + ", " + height + " m");
System.out.println("Tax rate: " + TAX_RATE);
System.out.println(city + " x" + count);
}
}Asha is 31, 1.68 m
Tax rate: 0.18
Pune x3Try count = "three"; after the var line. It will not compile: var still gives count a fixed type (int), it just saves you typing it.
var (Java 10+) only works for local variables that are initialised on the same line. The compiler reads the right-hand side, decides the type once, and it never changes. Use it when the type is obvious from the right side (var list = new ArrayList<String>()); write the type out when it is not.variable might not have been initialized
public class Main {
public static void main(String[] args) {
int total;
System.out.println(total);
}
}Main.java:4: error: variable total might not have been initialized
System.out.println(total);
^
1 errorLocal variables in Java have no default value. The compiler proves every local is assigned before it is read, and refuses to compile if any path could read an empty box. (Fields and array elements do get defaults — 0, false, null — but locals never do.)
Give the variable a value before you read it.
int total = 0;
System.out.println(total);cannot assign a value to final variable
public class Main {
public static void main(String[] args) {
final int MAX_USERS = 100;
MAX_USERS = 200;
System.out.println(MAX_USERS);
}
}Main.java:4: error: cannot assign a value to final variable MAX_USERS
MAX_USERS = 200;
^
1 errorfinal means "assigned exactly once". The compiler rejects the second assignment — that is the whole point of marking it final.
Remove final if the value really must change, or use a new variable for the new value.
final int MAX_USERS = 100;
int allowedToday = MAX_USERS * 2;