java - String initialization issue -


why got the local variable arctype may not have been initialized error?

1st case :

string arctype;  if (//somecondition) {  arctype += "test";     // here show error  system.out.println(arctype); } 

but below working fine.

2nd case :

 string arctype = null;  if (//somecondition) {  arctype += "test";     // it's working fine  system.out.println(arctype); }  output of above program : nulltest 

if initialize string space space concatenate test. using trim space remove don't want use trim.

my question :

  1. why got the local variable arctype may not have been initialized error in first case?

  2. in 2nd case when initialize string null why got output nulltest?

i want output test.

1- member & class variables initialized default. local variables aren't.

2- tostring() called implicitly if object passed isn't null. if is, literal "null" printed instead. so, in order "test" output, need initialize string empty one.

from docs: objects#tostring()

returns result of calling tostring non-null argument , "null" null argument.


Comments