NullPointerException or will print the static variable's content

java, nullpointerexception, static, static-members

Solution

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`.

Problem

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?

Original source

Related problems