-3

In my opinion calling getCity() method will return null, so null.name makes no sense, but it works. Both print statements are printed.

package javaapplication1;
public class JavaApplication1 {

    static String name = "New york";

    static JavaApplication1 getCity(){
        System.out.println("Getting city");
        return null;
    }

    public static void main(String[] args) {
        System.out.println( getCity().name );
    }
}

Working example: https://ideone.com/rTJup5

Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
AlexeyYar
  • 19
  • 2
  • 2
    what do you mean by "but it work" ? – AdrianS Apr 10 '18 at 11:47
  • It works as the name is static that does not need any object to call. – Amit Bera Apr 10 '18 at 11:50
  • It is neither a good nor a bad question. It is a tricky code that as we read it fast may be misleading. Morale : compiler warnings are designed to be handled. – davidxxx Apr 10 '18 at 11:57
  • According to java language specification a class variable can be accessible by with null reference also.
    We can access the static variable through class name as well as object reference. - In evaluation of `getCity().name` first `getCity()` is evaluated and result is discarded.
    – Pavan Apr 10 '18 at 12:04

2 Answers2

4

Your code is working as static String name = "New york"; is static.

Remove the static from it it will throw a NullPointerException. Static members do not need an object to call as a static member are class level members. Below code will also work.

JavaApplication1 application = null;
System.out.println(application.name);

Your getCity().name is same as JavaApplication1.nameIn your case compiler will give you a warning like below

The static field JavaApplication1.name should be accessed in a non-static way

kutschkem
  • 7,826
  • 3
  • 21
  • 56
Amit Bera
  • 7,075
  • 1
  • 19
  • 42
1

It works only because you call a static member of the object.

In your case, name is not related to an instance of JavaApplication1, it is only related to JavaApplication1 class. When you call getCity().name in reality you call JavaApplication.name.

If you remove the static modifier before String name = "New york" you will get a java.lang.NullPointerException.

Have fun!

Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27