1

Below is my code, wondering why null is printed instead of Hello World!!!

public class MyClass {

    static String s1 = getMyValue();
    static String s2 = "Hello World!!!";

    private static String getMyValue() {
        return s2;
    }

    public static void main(String args[]) {
        System.out.print(s1);  //outputs: null
    }
}
3
  • Try to place s2 initialization before s1 . Commented Apr 28, 2016 at 15:25
  • 3
    Initialized by order of declaration. So s1 gets assigned to getMyValue() which returns null since s2 hasn't been assigned yet. Commented Apr 28, 2016 at 15:28
  • I haven't touched Java in a long time but don't you need to reference inner function using this.getMyValue() seemed like a common usage in C#, PHP and as far as I recall Java. May be something has changed. Anyone can shed some light onto this? Actually, class properties to be assigned using another method would usually be performed within a constructor. Commented Apr 28, 2016 at 15:58

1 Answer 1

1

Run this in a debugger and you wil see that s1=getMyValue() is executed BEFORE s2 is set to "Hello World!!!"..

Sign up to request clarification or add additional context in comments.

2 Comments

Right, however why doesn't it give error on return s2, since it didn't find s2 and s2 is defined after s1.
@MaheshSapkal The compiler won't parse every single possible path to figure out who called getMyValue and if it's defined before whatever value is used within the method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.