==
operator compares numbers and that object references refer to the same object.
public class Main{ public static void main(String[] argv){ StringBuilder one = new StringBuilder(); StringBuilder two = new StringBuilder(); StringBuilder three = one.append("a"); System.out.println(one == two); // false System.out.println(one == three); // true } }
one == two
is false since they are pointing to different object instance.
one == three
is true since one.append("a")
return one
as the result.
The code above generates the following result.
In the following example x == y returns true because the JVM reuses String literals:
Strings are immutable and literals are pooled.
The JVM created only one literal in memory. x and y both point to the same location in memory.
public class Main{ public static void main(String[] argv){ String x = "Hello World"; String y = "Hello World"; System.out.println(x == y); // true } }
The code above generates the following result.
The following code shows how the trim()
method would create new String object.
In the code we don't have two of the same String literal.
Although x and z have the same string value,
z
is computed at runtime.
Since the value returned from trim() isn't the same at compile-time, a new String object is created.
public class Main{ public static void main(String[] argv){ String x = "Hello World"; String z = " Hello World".trim(); System.out.println(x == z); // false } }
The code above generates the following result.
We can create a new String without using the pooled value by using new
operator:
public class Main{ public static void main(String[] argv){ String x = new String("Hello World"); String y = "Hello World"; System.out.println(x == y); // false } }
The code above generates the following result.
The equals() method does the comparison for the content of two string values.
public class Main{ public static void main(String[] argv){ String x = "Hello World"; String z = " Hello World".trim(); System.out.println(x.equals(z)); // true } }
The code above generates the following result.
In the following code, the first two statements check object reference equality.
The t1.equals(t2)
prints false since Main does not implement equals().
public class Main { String name; /* w ww. j a v a 2s. co m*/ public static void main(String[] args) { Main t1 = new Main(); Main t2 = new Main(); Main t3 = t1; System.out.println(t1 == t1); // true System.out.println(t1 == t2); // false System.out.println(t1.equals(t2)); // false } }
The code above generates the following result.