[Solved]Why output of this two code is different?

//code 1 class Program{ static String str; public static void main(String[] args){ System.out.println(str+"hello"); } } //Output nullhello //code 2 class Program{ public static void main(String[] args){ String str; System.out.println(str+"hello"); } } //Output Error(variable str might not have been initialized)

8/25/2019 11:50:45 AM


2 Answers

New Answer


@Amir01 static member and non static member variables are initialized to the default values of their type. A non-static local variable must be initialized before it's first use. In program 1 str is a static class member, since it is not initialized explicitly it is initialized to null. In second case str is an uninitialized string object, hence compiler gives you an error.


because method variables do not have default values and class variables have default values