Navigator


Archive

201139
201230
201312
20151
201633
201755
201865
201955
20234
20242

Creation date:

String equality

Try to predict the result of the following code.

  String s = "test";
  System.out.println(s.equals("test"));
  System.out.println(s == "test");
  System.out.println(s == new String("test"));

I think the result of s.equals("test") is obvious. Yes, it's true (I mean result). But the result of s == "test" is also true. Because all String objects are immutable, before creation of new String Java looks at pool and tries to find the creating string. If it founds, it sets reference of found string to variable. Java does it to save memory. That's why the equality s == "test" is true. The equality check s == new String("test") returns false because in this case we force Java to create a new instance of String object.

Author: Jafar N.Aliyev (Jsoft)

Read also

Static methods can not be overriden

Here I explain, why static methods can not be overriden

Use instanceof carefully

Usage of 'instanceof' method in some situations will give you a compilation error

Java access and nonaccess modifiers

Look at this cheat sheet for Java access and nonaccess modifiers

© Copyright

All articles in this site are written by Jafar N.Aliyev. Reproducing of any article must be followed by the author name and link to the site of origin(this site). This site also keeps the same rules relative to the articles of other authors.