The blog of Jafar Aliyev

Archive

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

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

Wrapper objects

Static and instance initilization blocks

Overloading

Java access and nonaccess modifiers
Look at this cheat sheet for Java access and nonaccess modifiers

Implicit typecasting

Protected details

Interface methods are always public

Static methods can not be overriden
Here I explain, why static methods can not be overriden

Implicit typecasting

Java Tips

Variable hiding

Postfix operators

Tricky Polymorphism

Pattern Matching

Default values

© 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.