static: shared by the whole class
A normal field belongs to each object. A static field belongs to the class itself, so there is only one, shared by all objects:
class Player {
static int count = 0;
String name;
Player(String name) {
this.name = name;
count++;
}
}
public class Main {
public static void main(String[] args) {
new Player("Asha");
new Player("Ravi");
new Player("Meera");
System.out.println("Players created: " + Player.count);
}
}Output
Players created: 3
Think of it like this: Each student has their own name (normal field), but the whole class shares one classroom clock (static field).
A static method also belongs to the class, so you call it without making an object – like Math.sqrt(). That's why main is static: Java can start it before any object exists.
Printing an object
Printing an object gives an odd code like Point@1b6d3586. Give your class a toString() method and Java uses it whenever the object is printed or joined to text:
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public class Main {
public static void main(String[] args) {
Point p = new Point(3, 7);
System.out.println(p);
System.out.println("The point is " + p);
}
}Output
(3, 7) The point is (3, 7)
@Override tells Java “I'm replacing a method that already exists”. You'll learn why in the next module.
null: no object
A variable of a class type can hold null, meaning “no object here”. Using it crashes:
public class Main {
public static void main(String[] args) {
String name = null;
System.out.println(name.length());
}
}Output (Java stops with an error)
Exception in thread "main" java.lang.NullPointerException
Common mistake:
NullPointerExceptionis the most common Java crash. Make sure an object was created withnew(or isn'tnull) before you use it.