2

This program

public class OddBehavior {
    public static void main(String[] args){
        String[] words = new String[3];
        words[0] += "ify";
        System.out.println(words[0]);
    }
}

has the following output:

Image

I initialized an array of 3 Strings, which I thought would be null. But by adding the string "ify" to the end of words[0], the words[0] got the value "nullify", i.e. it already contained the String "null" (the String, not the value null!)

Chris Middleton
  • 5,654
  • 5
  • 31
  • 68
  • @ChrisMiddleton Read this [answer](http://stackoverflow.com/questions/4260723/concatenating-null-strings-in-java/4260803#4260803). – Steve P. Aug 04 '13 at 03:18
  • There's no one good answer. If the Java gods had declared "a `null` value string shall print as empty-string", then someone right about now would be posting to SO asking if it wouldn't have been better to print "null" instead. It's simply a decision that was made, no better or worse than another decision. – Richard Sitze Aug 04 '13 at 16:18

1 Answers1

3

The code words[0] += "ify" is equivalent to words[0] = words[0] + "ify". When Strings are concatenated with the + operator, Java internally uses a StringBuilder to put them together. When null is appended to a StringBuilder, it uses the literal "null" instead. That is why this happens.

Martin Wickham
  • 442
  • 4
  • 9