Java Static Keyword
Table of Contents + โ
In the last lesson you learned about the Java import statement. Now for a word you have used all along without thinking: every main method starts with public static void main. Letโs finally find out what that static does.
๐ค The problem static solves
Each object gets its own copy of every field. Usually that is fine. But sometimes a normal field is wrong:
- You want the total count of
Counterobjects. That number belongs to the whole class, not to one object. - A normal field gives each object its own copy, so no copy knows the total.
- You want a value or helper without making an object. You never write
new Math()to getMath.PI.
The static keyword answers both. It says โthis member belongs to the class itself, not to any one object.โ
๐งฉ What static really means
Marking a member static makes it shared. There is only one of it, and it lives with the class.
- A normal (instance) member belongs to each object. Ten objects, ten copies.
- A static member belongs to the class. Ten objects, still one shared copy.
- You can use a static member with no object. You reach it through the class name.
- That is why
mainis static. At program start no object exists, andstaticlets Java callmainanyway.
The program below shows the smallest static member, read straight from the class name.
public class Main { static String appName = "FreeCodingSchool"; // belongs to the class
public static void main(String[] args) { System.out.println(Main.appName); // reached through the class name }}We never wrote new Main(). The field exists the moment the class loads, so we ask the class for it directly.
Output
FreeCodingSchool๐ ๏ธ The four uses of static
The static keyword shows up in four places. The next lessons cover each one:
- Static variables. A field shared by every object. One copy for the whole class. Use it for a total count or a shared setting.
- Static methods. A method called without an object. Helpers like
Math.maxandInteger.parseIntare static methods. - Static blocks. A block that runs once, when the class first loads. Use it to set up static variables that need more than a one-line value.
- Static nested classes. A class nested inside another and marked
static. It needs no outer object. Covered in a later module.
One word, one idea
All four uses share the same single idea. Static means โbelongs to the class, not to an object.โ If you remember that one sentence, every use of static makes sense.
๐ Accessing static members through the class name
Reach a static member through the class name, not an object. You have done this already. The snippet below uses two static members from Javaโs library. Neither line creates an object.
public class Main { public static void main(String[] args) { double pi = Math.PI; // static variable on the Math class int number = Integer.parseInt("42"); // static method on the Integer class
System.out.println(pi); System.out.println(number); }}Read both lines:
Math.PIis a static variable. You ask theMathclass for pi.Integer.parseInt("42")is a static method. You ask theIntegerclass to turn"42"into42.- The pattern is the same: ClassName dot member. No
new, no object.
Output
3.14159265358979342๐ข A shared counter: static vs instance
Put a static field and an instance field side by side. Below, count is static and id is an instance field. The constructor adds one to count and copies the new total into each objectโs own id.
public class Main { static int count = 0; // shared by ALL objects int id; // each object gets its own
Main() { count++; // bump the one shared total id = count; // store this object's personal number }
public static void main(String[] args) { Main a = new Main(); Main b = new Main(); Main c = new Main();
System.out.println("a.id = " + a.id); System.out.println("b.id = " + b.id); System.out.println("c.id = " + c.id); System.out.println("Total objects = " + Main.count); }}Walk through each new object:
- Making
aruns the constructor.countgoes 0 to 1,a.idbecomes 1. - Making
bruns it again.countgoes 1 to 2,b.idbecomes 2. - Making
cruns it once more.countgoes 2 to 3,c.idbecomes 3. - Each object keeps its own frozen
id. Butcountis one shared number that climbed each time.
Output
a.id = 1b.id = 2c.id = 3Total objects = 3The instance field id answers โwho am I.โ The static field count answers โhow many of us are there.โ
๐ Static vs instance summary
Here is the side-by-side view.
| Feature | Static member | Instance member |
|---|---|---|
| Belongs to | The class itself | Each individual object |
| How many copies | One, shared by all | One per object |
| Need an object? | No, use the class name | Yes, create one first |
| Reached by | ClassName.member | object.member |
| Good for | Shared totals, settings, helpers | Data unique to one object |
| Can use this? | No, there is no object | Yes, this points to the object |
The bottom row matters. A static method has no object behind it, so this has nothing to point at.
โ ๏ธ Common Mistakes
Reaching a static member through an object. Java allows object.staticField, but it is misleading. It looks like the field belongs to that object. Always use the class name.
// โ Misleading: looks like a belongs to count, but count is sharedMain a = new Main();System.out.println(a.count);
// โ
Clear: the class name shows count belongs to the classSystem.out.println(Main.count);Using this inside a static method. A static method runs with no object, so this does not exist there. Using it is a compile error.
// โ Wrong: there is no object, so this means nothing herestatic void show() { System.out.println(this.id); // compile error}
// โ
Correct: a static method works only with static data or its parametersstatic void show(int id) { System.out.println(id);}Calling an instance member from a static method directly. A static method has no object, so it cannot touch instance fields on its own. It would not know which object you mean. Hand it an object first.
// โ Wrong: id is an instance field; main does not know whose idpublic static void main(String[] args) { System.out.println(id); // compile error}
// โ
Correct: make an object, then read its instance fieldpublic static void main(String[] args) { Main a = new Main(); System.out.println(a.id);}Overusing static. Making everything static to skip objects is tempting. Resist it. Shared state across the whole program makes bugs hard to trace, and the code stops being object-oriented.
โ Best Practices
- Access static members through the class name. Write
Math.PI, not through an object. It shows the member is shared. - Use static only when the member belongs to the class. Shared totals, fixed constants, and stateless helpers fit. Per-object data does not.
- Keep static methods stateless. Take inputs as parameters and return a result. Do not lean on shared changing state.
- Use static final for constants. A value that never changes, like
static final double PI, cannot be reassigned by accident. - Do not make a class fully static just to dodge objects. If everything is turning static, step back. You may be avoiding the object design the problem needs.
๐งฉ What Youโve Learned
- โ
staticmeans a member belongs to the class itself, not to any single object. - โ A static member has one shared copy, and you can use it without creating an object.
- โ There are four uses: static variables, static methods, static blocks, and static nested classes.
- โ
You reach static members through the class name, like
Math.PIandInteger.parseInt. - โ A static counter is shared by all objects, while an instance field is unique to each object.
- โ
A static method has no object, so it cannot use
thisor touch instance members directly.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does the static keyword mean for a member?
Why: Static means the member belongs to the class, so there is one shared copy for all objects.
- 2
How do you correctly access the static value PI on the Math class?
Why: Static members are accessed through the class name, like Math.PI, with no object needed.
- 3
Why can a static method not use the keyword this?
Why: A static method has no associated object, so this would have nothing to refer to.
- 4
If count is a static field bumped in the constructor, what does it represent after making three objects?
Why: A static field is shared, so each constructor updates the same copy, giving the total count of 3.
๐ Whatโs Next?
You have the big picture of static. Now we zoom in on the first use in detail: fields that are shared across every object of a class. Letโs see how a single static variable behaves when many objects touch it.