String in Java is not a primitive type, such as integer, boolean etc.
Every string is an object.
We can compare strings using method equals() or the identity operator ==.
Let's separate between the two types of comparing here.
Every string is an object.
We can compare strings using method equals() or the identity operator ==.
Let's separate between the two types of comparing here.
- While using equals() the comparison is done by characters.
String name1 = "Hello, world!";
String name2 = "Hello, world!";
if (name1.equals(name2))
System.out.println("The names are the same.");
// Output "The names are the same."
That means string "Hello, world!" is equal to the second "Hello, world!", because these strings have the same characters. - While using == the pointers to strings are compared.
if (name1 == name2)
When we write this code:
System.out.println("The names are the same.");
else
System.out.println("Oh, no!"); // Output "Oh, no!"
String name1 = "Hello, world!";
we have this picture in the main memory:
The variable name1 holds the address of object in the memory (in our example the address is 42).
name1 is a pointer to the location in memory where the object is held.
Let's create strings as different objects.String name1 = new String("Hello, world!");
Now we don't care about string characters, we care about objects.
String name2 = new String("Hello, world!");
We have this picture in the main memory:
When we made that comparison we didn't care about characters.
We checked whether both pointers name1 and name2 refer to the same string.
We see from the picture, that the answer is no.
Let's make the code to answer yes :)
String name1 = new String("Hello, world!");
The picture in the main memory now:
String name2 = name1;
if (name1 == name2)
System.out.println("The names are the same."); // Output "The names are the same."
else
System.out.println("Oh, no!");