In java, i am trying to understand the difference between static and non-static objects and variables like this.
Code with static object:
package abc;
public class StaticUsage {
public static StaticUsage propfile;
public static void main(String[] args) {
checkifPropertiesFileisnull();
checkifPropertiesFileisnull();
checkifPropertiesFileisnotnull();
/*stu.checkifPropertiesFileisnull();*/
}
private static void checkifPropertiesFileisnotnull() {
if(propfile==null) {
System.out.println("Propfile is " + propfile);
propfile = new StaticUsage();
}
else {
System.out.println("Propfile value is " + propfile);
}
}
private static void checkifPropertiesFileisnull() {
if(propfile==null) {
System.out.println("Propfile is " + propfile);
propfile = new StaticUsage();
}
else {
System.out.println("Propfile value is " + propfile);
}
}
}
Code with non-static object:
package abc;
public class StaticUsage {
public StaticUsage propfile;
public static void main(String[] args) {
StaticUsage stu = new StaticUsage();
stu.checkifPropertiesFileisnull();
stu.checkifPropertiesFileisnull();
stu.checkifPropertiesFileisnotnull();
/*stu.checkifPropertiesFileisnull();*/
}
private void checkifPropertiesFileisnotnull() {
if(propfile==null) {
System.out.println("Propfile is " + propfile);
propfile = new StaticUsage();
}
else {
System.out.println("Propfile value is " + propfile);
}
}
private void checkifPropertiesFileisnull() {
if(propfile==null) {
System.out.println("Propfile is " + propfile);
propfile = new StaticUsage();
}
else {
System.out.println("Propfile value is " + propfile);
}
}
}
However, in both cases i am getting output as the below:
Propfile is null Propfile value is abc.StaticUsage@15db9742 Propfile value is abc.StaticUsage@15db9742
I have heard that for static objects, it is shared throughout the instance of the class. So, i am getting the value for the first time as null, and the rest not null. But, then why for non-static objects, i am getting the same value? The value for the first method call should go to heap according to me, and then at the time of calling the second method, it should be again showing as null.
Can anyone please clear me the confusion?