A static variable belongs to the class, not to any one object: there is exactly one copy, shared by every object, so a change made by one object is seen by all of them. A static method is called on the class, as in Member.getCount(), and runs with no current object, so it cannot use instance variables, instance methods or this directly. A static counter that each constructor adds 1 to is the classic way to count the objects created.
Quick check
Every Tank object has its own level. What kind of variable is level?Show answerHide answer
An instance variable: each object gets its own copy.
You call Math.sqrt(16.0) without creating a Math object. What does that tell you about sqrt?Show answerHide answer
It is a static method: it belongs to the
Mathclass, so you call it on the class name.Two objects share one static variable, and one of them adds 1 to it. What value does the other object see?Show answerHide answer
The new value. There is only one copy of the variable.
Know these already? Jump to the practice questions
What you'll be able to do
- Explain how a static variable differs from an instance variable.
- Determine a static counter's value after a series of constructor calls.
- Explain why a static method cannot use instance variables or
this. - Identify which variables and methods each kind of method can use.
- Determine the output of code that mixes static and instance members.
Key terms
Static variable
A variable declared with static in a class: one copy exists for the whole class, shared by every object. Also called a class variable.
- In plain English
- A noticeboard every object reads and writes.
- Don't write
- "Each object has its own static variable."
Static method
A method declared with static: it belongs to the class, is called with the class name and has no current object.
- In plain English
- A method you can run without making an object first.
- Don't write
- "A static method can use
this."
What does static mean for a variable?
An instance variable has one copy per object. A static variable has one copy per class.
public class Member
{
private static int count = 0;
private String name;
private int id;
public Member(String n)
{
count++;
name = n;
id = count;
}
public String getTag()
{
return name + "#" + id;
}
public static int getCount()
{
return count;
}
}
Every Member has its own name and id, but they all share count. The initializer = 0 runs once, when the class is first set up, not once per object. Each constructor call then adds 1 to the same count and copies the new value into that object's own id, so the members get ids 1, 2, 3 in order of creation.
Key idea
Instance variables describe one object; a static variable describes the class as a whole.
Check yourself
Show answerHide answer
One count and three ids, one in each object.
How do static methods work?
A static method is called on the class name: Member.getCount(), just as you call Math.abs(-4). The Math methods on the Java Quick Reference are all static, which is why you never create a Math object.
Because a static method is not called on an object, it has no current object. So inside a static method:
thiscannot be used: there is no object for it to mean.- An instance variable such as
namecannot be used on its own: Java could not tell whosename. - An instance method such as
getTag()cannot be called on its own, for the same reason.
A static method can still use instance members through an object reference it is given, such as a parameter Member m and the call m.getTag().
Check yourself
Show answerHide answer
name is an instance variable, and a static method has no current object to take it from.
Which members can each kind of method use?
| Inside … | Static variables and methods | Instance variables and methods | this |
|---|---|---|---|
| an instance method or constructor | yes | yes | yes |
| a static method | yes | only through an object reference | no |
Instance methods are allowed everything: they run on an object, and the class's static members are always there. In Member, the constructor uses count (static) and id (instance) side by side.
When you trace code that mixes the two, keep one column for each static variable and one column per object for each instance variable. A change to a static column shows up for every object at once.
Java also lets you call a static method through an object, as in a.getCount(), but the class name makes it clear the member is shared.
Check yourself
Show answerHide answer
Yes. Instance methods can use static variables and static methods directly.
Worked example 1: Trace an object counter
Question: Using the Member class, what is printed?
Member a = new Member("Ada");
Member b = new Member("Ben");
Member c = new Member("Cy");
System.out.println(b.getTag() + " " + Member.getCount());
What tells you the method
A static variable changed by every constructor call, so trace one shared column and one column per object.
Step 1: Trace each constructor call.
Statement count(shared)a.idb.idc.idstart 0 new Member("Ada")1 1 new Member("Ben")2 1 2 new Member("Cy")3 1 2 3 Whycount++runs beforeid = count, so each object stores the count just after it was added.Step 2: Evaluate the print.
b.getTag()is "Ben#2", andMember.getCount()is 3.Whyb'sidwas fixed whenbwas made;countkept growing.
Check it
The last object's id always equals count, and c.id is 3, matching.
Answer
Ben#2 3
Worked example 2: Design a shared setting
Question: Every Product must use the same tax rate, and changing it must affect every product at once. Decide which members are static, then state what this prints.
public class Product
{
private static double taxRate = 0.25;
private double price;
public Product(double p)
{
price = p;
}
public double finalPrice()
{
return price + price * taxRate;
}
public static void setTaxRate(double r)
{
taxRate = r;
}
}
Product x = new Product(20.0);
Product y = new Product(50.0);
System.out.println(x.finalPrice());
Product.setTaxRate(0.5);
System.out.println(x.finalPrice() + " " + y.finalPrice());
What tells you the method
A design decision: ask of each member whether it belongs to one object or to the class.
Step 1: Sort the data.
Each product has its own price, so
priceis an instance variable. One rate is shared, sotaxRateis static.WhyStatic means one copy for the whole class, which is exactly "the same rate for everyone".
Step 2: Sort the methods.
finalPriceneeds one product'sprice, so it is an instance method.setTaxRatetouches onlytaxRate, so it can be static and be called asProduct.setTaxRate(0.5).WhyA method that needs no particular object fits being static.
Step 3: Trace.
At rate 0.25,
xgives 20.0 + 5.0 = 25.0. After the rate becomes 0.5,xgives 20.0 + 10.0 = 30.0 andygives 50.0 + 25.0 = 75.0.WhyBoth objects read the one
taxRate, so the single call changed both results.
Check it
At rate 0.5 each final price should be 1.5 times the price: 1.5 × 20 = 30 and 1.5 × 50 = 75.
Answer
25.0 then 30.0 75.0 on the next line.
Worked example 3: Spot the illegal static method
Question: Which method, added to the Member class, causes a compile-time error?
- A)
public String info() { return name + " of " + count; } - B)
public static void reset() { count = 0; } - C)
public static String tagOf(Member m) { return m.getTag(); } - D)
public static String firstName() { return name; }
What tells you the method
Static and instance members are mixed, so check each method against the table of what it may use.
Step 1: Classify each method.
A is an instance method; B, C and D are static.
WhyThe rules depend on whether the method has a current object.
Step 2: Check each body.
A, an instance method, may use
nameandcount. B uses only the staticcount. C reaches an instance method through the referencem. D uses the instance variablenamewith no object.WhyOnly D asks a static method for an instance variable with no object to take it from.
Check it
Changing D's header to drop static makes it an instance method, and it then compiles.
Answer
D
Your turn
Question: What is printed?
public class Light
{
private static int onCount = 0;
private boolean on;
public void switchOn()
{
if (!on)
{
on = true;
onCount++;
}
}
public void switchOff()
{
if (on)
{
on = false;
onCount--;
}
}
public static int getOnCount()
{
return onCount;
}
}
Light p = new Light();
Light q = new Light();
p.switchOn();
q.switchOn();
p.switchOn();
q.switchOff();
System.out.println(Light.getOnCount());
Step 1: Trace the first two calls.
Both lights start with
onasfalse, its default.p.switchOn()makesonCount1 andq.switchOn()makes it 2.Step 2: Your go: trace
p.switchOn()andq.switchOff().
Show the full solutionHide the solution
Step 2. p is already on, so the if is false and onCount stays 2. q.switchOff() finds q on, turns it off and makes onCount 1.
Answer: 1
Traps
Trap
Each object gets its own fresh copy of a static variable.
It seems right because each constructor call uses it. But there is one copy for the whole class, and every object reads and changes that same copy.
After new Member("A"); new Member("B");, what does Member.getCount() return?
Trap
The = 0 in private static int count = 0; resets the counter for every new object.
It seems right because instance variable initializers do run per object. But a static initializer runs once, when the class is set up, so the counter keeps its value between objects.
Does creating a fourth Member set count back to 0 before adding 1?
No: count goes from 3 to 4.
What's examined
On the AP® Computer Science A exam (Unit 3: Class Creation), multiple-choice questions ask you to trace code where a static variable changes as objects are created or methods run, or to spot a static method that misuses an instance variable. In the class design free-response question, deciding whether a variable is shared or per-object is part of writing the class.
Practice questions
- Recall Which statement about a static variable is true?
- A) Each object gets its own copy, set by the constructor.
- B) There is one copy, shared by every object of the class.
- C) Only static methods can use it.
- D) Its value cannot change after it is declared.
Show answer
Answer: B. A static variable belongs to the class, so there is exactly one copy.
Why the others are wrong:
- A describes an instance variable.
- C is wrong: instance methods and constructors can use static variables too.
- D confuses
staticwith a constant;count++changes a static variable.
- Recall Name the keyword that a static method cannot use because it has no current object.
Show answer
Answer: this
Marking points:
thismeans the current object, and a static method is not called on an object.
- Apply What is printed?
public class Seat
{
private static int next = 100;
private int number;
public Seat()
{
number = next;
next = next + 5;
}
public int getNumber()
{
return number;
}
public static int getNext()
{
return next;
}
}
Seat s1 = new Seat();
Seat s2 = new Seat();
Seat s3 = new Seat();
String line = s1.getNumber() + " " + s3.getNumber();
System.out.println(line + " " + Seat.getNext());
Show answer
Answer: 100 110 115
Marking points:
- Each seat takes the current
next, thennextgoes up by 5: seats 100, 105 and 110. - After three objects,
nextis 115.
- Exam-style The compiler reports an error on exactly one line of this class. Give that line's number.
1: public class Score
2: {
3: private static int best = 0;
4: private int points;
5:
6: public Score(int p)
7: {
8: points = p;
9: if (points > best)
10: {
11: best = points;
12: }
13: }
14:
15: public static int getBest()
16: {
17: return best;
18: }
19:
20: public static int getPoints()
21: {
22: return points;
23: }
24: }
Show answer
Answer: Line 22.
Marking points:
getPointsis static, so it has no current object and cannot use the instance variablepoints.- Lines 9 and 11 are fine: a constructor may use both static and instance variables.
- Exam-style What is printed?
public class Account
{
private static double rate = 0.5;
private double balance;
public Account(double b)
{
balance = b;
}
public void addInterest()
{
balance = balance + balance * rate;
}
public static void setRate(double r)
{
rate = r;
}
public double getBalance()
{
return balance;
}
}
Account a = new Account(100.0);
Account b = new Account(100.0);
a.addInterest();
Account.setRate(0.25);
b.addInterest();
a.addInterest();
System.out.println(a.getBalance() + " " + b.getBalance());
- A)
225.0 125.0 - B)
156.25 125.0 - C)
187.5 125.0 - D)
234.375 234.375
Show answer
Answer: C. a grows to 150.0 at rate 0.5, then to 187.5 at 0.25; b grows once at 0.25 to 125.0.
Why the others are wrong:
- A treats
rateas ifakept its own copy of 0.5. - B applies the new rate to
a's first call, which ran beforesetRate. - D treats
balanceas shared, as if it were static.
The Member class is for questions 6 and 7.
public class Member
{
private static int count = 0;
private String name;
private int id;
public Member(String n)
{
count++;
name = n;
id = count;
}
public String getTag()
{
return name + "#" + id;
}
public static int getCount()
{
return count;
}
}
- Apply What value does
Member.getCount()return after this code runs in a new program?
Member a = new Member("Ana");
Member b = a;
Member c = new Member("Bo");
b = new Member("Cal");
Show answer
Answer: 3
Marking points:
- The constructor, and so
count++, runs once pernew: three times. b = a;copies a reference and runs no constructor.
- Exam-style Which statement compiles when written in the
mainmethod of a different class?
- A)
int n = Member.getCount(); - B)
String t = Member.getTag(); - C)
int n = Member.count; - D)
int n = this.getCount();
Show answer
Answer: A. getCount is a public static method, so it is called on the class name.
Why the others are wrong:
- B calls an instance method on the class name; it needs an object.
- C reads
countfrom outside the class, but it isprivate. - D uses
thisinmain, which is static, so there is no current object.
- Exam-style What is printed?
public class Club
{
private static int total = 0;
private int visits;
public void visit()
{
visits++;
total++;
}
public int getVisits()
{
return visits;
}
public static int getTotal()
{
return total;
}
public static void doubleVisit(Club c)
{
c.visit();
c.visit();
}
}
Club x = new Club();
Club y = new Club();
x.visit();
Club.doubleVisit(y);
y.visit();
String line = x.getVisits() + " " + y.getVisits();
System.out.println(line + " " + Club.getTotal());
Show answer
Answer: 1 3 4
Marking points:
doubleVisitreachesythrough its parameter, soygets two visits, then one more.- Every visit also adds 1 to the shared
total: 1 + 2 + 1 = 4.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- A static variable has one copy for the whole class; instance variables have one per object.
- A static initializer runs once, so a static counter keeps growing as objects are made.
- Call a static method on the class name; it has no current object.
- A static method cannot use
thisor instance members except through an object reference. - Instance methods and constructors may use static members freely.