I\'ve readed from the .txt file this:
When you concatenate a null
reference with a string, it is converted to "null"
string, and then concatenation is performed.
This is specified in JLS - Section 5.1.11:
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
Now, when you declare an instance or static reference field, without initializing to any value, it will be initialized to default value - null
, as in your declaration:
private static String str; // This is `null`.
Then for the first iteration of the loop:
str += sCurrentLine;
is equivalent to:
str = null + sCurrentLine; // Hence the result.
As for your str.indexOf()
query, I don't know where you are testing the index, because it should return the index of null
that is 0
, provided, you used that method after the loop, as shown in the below snippet:
String str = null;
String str2 = str + "someString";
System.out.println("Index of null in : " + str2 + " : " + str2.indexOf("null"));
This will output to you:
Index of null in : nullsomeString : 0
Also, while performing string concatenation inside such a loop, which you can't control, when it ends, and even in general, you should use StringBuilder
instance, to avoid creating intermediate string instances:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(sCurrentLine);