Check to see if Strings are shared in Java
Description
The following code shows how to check to see if Strings are shared.
Example
/*www . j ava2s .co m*/
public class Main {
public static void main(String[] argv) {
String one = "A String from java2s.com";
String two = "A String from java2s.com";
String three = new String(one);
compare(one, two);
compare(two, three);
}
public static void compare(String one, String two) {
System.out.println("Comparing...");
if (one == two) {
System.out.println("Strings are shared: " +
one.hashCode() + ", " + two.hashCode());
} else if (one.equals(two)) {
System.out.println("At least the strings are equal: " +
one.hashCode() + ", " + two.hashCode());
System.out.println((Object)one);
System.out.println(two);
} else System.out.println("This is rather distressing, sir.");
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »