Comparing two String objects using == or != compares object identity, which may not be intended. The same sequence of characters can be represented by two distinct String objects.

To see if two String objects represent the same sequence of characters, you should usually compare the objects by using their equals methods.

With the following definition, headerStyle is compared to the empty string using ==. This comparison can yield false even if headerStyle is the empty string, because it compares the identity of the two string objects rather than their contents. For example, if headerStyle was initialized by an XML parser or a JSON parser, then it might have been created with code like String.valueOf(buf,start,len). Such code will produce a new string object every time it is called.

With the following definition, headerStyle is tested using the equals method. This version will reliably detect whenever headerStyle is the empty string.

  • Java API Specification: String.equals(), String.intern().
  • Java Language Specification: 15.21.3 Reference Equality Operators == and !=, 3.10.5 String Literals , 15.28 Constant Expressions.