I came across following code :
public class TradingSystem {
private static String category = "electronic trading system";
public static void main(String[] args) {
TradingSystem system = null;
System.out.println(system.category);
}
Output : electronic trading system
I was surprised to not find a NullPointerException !
Q1. Why didn't it throw the NullPointerException
?
Q2. Or while compile time, due to category's declaration having static
made it to replace the system(i.e object reference) with TradingSystem
and as such essentially TradingSystem.category
was called?
Java allows accessing class variables (i.e. static
ones) using the instance syntax. In other words, the compiler lets you write system.category
, but it resolves it to TradingSystem.category
, which is independent of the instance on which it is accessed.
That is why you do not get NullPointerException
. However, this syntax is not readable and confusing. That is why you should get a warning and a suggestion to use TradingSystem.category
instead of system.category
.
Your code is not different from following code conceptually.
public class TradingSystem {
private static String category = "electronic trading system";
public static void main(String[] args) {
System.out.println(TradingSystem.category);
}
}
Even though you seem to be using system object reference, you are actually using static value. Java allows use instances when you use static,but you should prefer above syntax so that it is clear that you are using static ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With