r/javahelp • u/VanVleet-goes-for-22 Nooblet Brewer • Jun 15 '20
I’m having a concept issue with regards to Static / Instance fields
Hey all,
I’m studying for the OCA and came across a concept I’m having a bit of trouble grasping. The textbook is saying that if Class A1 has a public static int myInt = 4, I do not need to create a new instance of Class A1 to use myInt. This I understand. I also get that if it wasn’t a static, I would have to create a new instance of this Class A1 to use this int (if the class I’m in is static).
My issue came when the book said you could create a new object and attach the static method to it.
A1 tester = new A1();
System.out.println(tester.myInt)//should print 4
tester = null;
System.out.println(tester.myInt)//still prints 4The last line is confusing me. The book says java doesn’t actually use the object tester so it doesn’t matter whether it has a value or not?? Sorry if this isn’t clear, I just don’t understand how the last line can compile
1
Jun 15 '20
Shouldn't the last line, System.out.println(tester.myInt()) throw a null pointer exception?
2
u/VanVleet-goes-for-22 Nooblet Brewer Jun 15 '20
It doesn’t, it still shows 4
I thought it should too, try it out
0
2
u/garblz Jun 15 '20
See the Java Language Specification, section 15.12.4.1. Compute Target Reference:
When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null
So, that's discarded on account of being static, and replaced by class reference itself. It's a good idea to use it from the get go like this A1.myInt to avoid confusion. Having said that, a nice catch! It's fun interesting to poke at the internals.
4
u/[deleted] Jun 15 '20 edited Jun 15 '20
The reason why it doesn't throw a nullpointerexception is because static members aren't associated with objects to begin with.
All static members are initialized at the start of code execution. Even if you never created any object of Class A1. You will be able to access myInt.
The book uses an odd method to access static member which is discouraged as it can be confusing. (Probably for demonstration purposes)
The right way is this to use type expression which is
As you can see I am not using object at all and whenever java runs your last line. It automatically corrects your code and invoke the line I mentioned above. Since object not being used, you don't get NPE.
Hopefully I was able to explain it. If you find it confusing. Just ask.