-2
String s="";
while ((strLine = br.readLine()) != null)   {
    s=s.concat(strLine);

When I used this code I get the string I expect from the file .. But if I used

String s = null;

What I get is null as the result of the s string. Can anyone explain me the reason for this?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Vbabey
  • 113
  • 1
  • 2
  • 10

1 Answers1

9

Firstly, I suspect that's not your code - or it would throw a NullPointerException. I suspect you've actually got:

s = s + strLine;

After that, it's very simple - concatenating any string with a null String reference will give you null:

String x = null;
String y = x + "a";
System.out.println(y); // nulla

From section 15.18.1 of the JLS (string concatenation):

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

Then from section 5.1.11:

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Note that your code is extremely inefficient at the moment - you should be using a StringBuilder.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194