3

Why I got The local variable arcType may not have been initialized error?

1st Case :

String arcType;

if (//somecondition) {
 arcType += "Test";     // Here it show the 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 the above program : nullTest

If I initialize my String with space then space concatenate with Test. Using trim space will remove but I don't want to use trim.

My question are :

  1. Why I got The local variable arcType may not have been initialized error in first case?

  2. In 2nd case when I initialize my string with null then why I got output nullTest?

I want output only Test.

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
  • 1
    local variables don't have a default value – bNd Jan 29 '16 at 09:52
  • 1
    Initialize your String properly, `String arcType = "";` Also, strings are immutable. Every time you do a change to any String, it creates the new String. You should be using StringBuilder. – user2004685 Jan 29 '16 at 09:53

4 Answers4

4

1- Only member & class variables are initialized by default. Local variables aren't.

2- toString() is only called implicitly if the object passed isn't null. If it is, the literal "null" is printed instead. So, in order to get "Test" as output, you need to initialize your string to an empty one.

From the docs: Objects#toString()

returns the result of calling toString for a non-null argument and "null" for a null argument.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
1

Then you should init with empty:

String arcType = "";

Inside methods, all declared variable must be initialized before using it.

Null is also a value, so when you reference the String to null and concate it, it will use the null + the concate value.

Lucas
  • 129
  • 9
0
  1. Yiu are getting the error excatly like it says- the variable may not be initialized (if the condition is false- it wont)

  2. The += operator is a syntactic sugar for s = s + "test". Since initially s is null, youll get `null + "test"

You should initialize s to empty string`

Nir Levy
  • 12,750
  • 3
  • 21
  • 38
0

Firstly, before operating on any variable you have initialise it even though you are initialising it with null is fine. But it should be initialised.

Secondly, if we read the java doc we would find that when the string is intialised with null and if we call join or + operator on it, it will considered to be having a null value to it. "Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

For example, String message = String.join("-", "Java", "is", "cool"); // message returned is: "Java-is-cool" Note that if an element is null, then "null" is added."

Incase you dont want the null to be appended then initialise the string with empty value like String arcType="";