Reputation: 117
I am new to Java and trying to learn by myself. I wrote the below code and I was wondering why the output is not as I expect. Below is the code I have written:
public class Roughwork {
public static int classVar = 25;
public void getValue(int a){
classVar = a;
System.out.println(classVar);
}
public static void main(String[] args) {
Roughwork test = new Roughwork();
System.out.println(classVar);
test.getValue(30);
System.out.println(classVar);
}
}
and the output of this program is:
25
30
30
I expected the output to be
25
30
25
What exactly is happening and What I have to do to get my expected output?
Upvotes: 1
Views: 135
Reputation: 16651
ClassVar is declared static.
public static int classVar = 25;
This means that it is not tied to an instance of Roughwork
. It is a global variable if you will. You can call this variable even from other classes in your application like this:
Roughwork.classVar
To get your expected behaviour, change your code to this:
public class Roughwork {
public int classVar = 25;
public void getValue(int a){
classVar = a;
System.out.println(classVar);
}
public static void main(String[] args) {
Roughwork test = new Roughwork();
System.out.println(test.classVar);
test.getValue(30);
Roughwork test2 = new Roughwork();
System.out.println(test2.classVar);
}
}
Upvotes: 3
Reputation: 407
A static variable is shared by all instances of the class. and in case of instance variable each instance of class have different copy.
Static variable memory allocate at compile time, They are loaded at load time and initialized at class initialization time and in case of instance variable everything is done at run time.
To make this example interesting: Create new instances of Roughwork, try to change the value and give it a try.
Roughwork test = new Roughwork();
Roughwork test2 = new Roughwork();
System.out.println(classVar);
test.getValue(30);
test2.getValue(25);
System.out.println(classVar);
Reference this thread for example to understand clearly:Class Variable & Instance Variable
Upvotes: 0
Reputation: 9488
It's because you change it to 30 and don't change it back to 25. (static
means it is the same for all instances of class)
System.out.println(classVar); //25
test.getValue(30); //30
System.out.println(classVar); //30 - you don't change variable back to 25
To fix it add classVar = 25
after test.getValue
or remove static
modifier on classVar
definition.
Upvotes: 0