Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException or will print the static variable's content [duplicate]

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?

like image 884
KNU Avatar asked Nov 26 '14 11:11

KNU


2 Answers

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.

like image 172
Sergey Kalinichenko Avatar answered Oct 10 '22 06:10

Sergey Kalinichenko


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.

like image 45
Atilla Ozgur Avatar answered Oct 10 '22 07:10

Atilla Ozgur