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
    }
}
msapkal
  • 8,268
  • 2
  • 31
  • 48
  • Try to place s2 initialization before s1 . – Arnaud Apr 28 '16 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. – Tunaki Apr 28 '16 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. – dchayka Apr 28 '16 at 15:58

1 Answers1

1

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

FredK
  • 4,094
  • 1
  • 9
  • 11
  • Right, however why doesn't it give error on return s2, since it didn't find s2 and s2 is defined after s1. – msapkal Apr 28 '16 at 15:28
  • 1
    @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. – Sotirios Delimanolis Apr 28 '16 at 15:38