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 Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger