0

My code below is compile error. The local available may not has been initialized

String str;
my_obj.setValue(str);

and fixed by this

String str = null;
my_obj.setValue(str);

So is null instance of anything? What is the difference between null and not initialized.

Why does it work for this way?

My Class

class MyClass {
    String str;
}

I have initialized obj not obj.str. but no such a compile error that ways...

MyClass obj = new MyClass();
my_obj.setValue(str);

I already read what all of you recommend before I post this questions. Maybe it duplicated, but I didn't get any idea form those.

Se Song
  • 1,613
  • 2
  • 19
  • 32
  • 1
    I think this question is a duplicate, but the answer to your question appears to be that the string `str` may literally have no value unless you initialize it somewhere. See [here](http://stackoverflow.com/questions/1560685/why-must-local-variables-including-primitives-always-be-initialized-in-java) and [here](http://stackoverflow.com/questions/10068219/in-java-why-do-certain-variables-need-initialization-at-first-and-others-only-n) for more information. – Tim Biegeleisen Nov 17 '15 at 06:36
  • maybe this will help you http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 – MaVRoSCy Nov 17 '15 at 06:44

1 Answers1

2

Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.

There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.

If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.

Local variables must be initialized before they are accessed. not initialized means, that you have not created object for that instance. Assigning a value will create a object to use it.

String str ;

Above code represents, that you have just declared it. But, can't use it until, it is assigned with some real value or null.

Reference to the question could be verified on this link

Community
  • 1
  • 1
Rohit Batta
  • 482
  • 4
  • 16