Skip to content

Instantly share code, notes, and snippets.

@rewinfrey
Created February 1, 2018 07:25
Show Gist options
  • Save rewinfrey/25855961273f760dfc1fb3ce26e2665b to your computer and use it in GitHub Desktop.
Save rewinfrey/25855961273f760dfc1fb3ce26e2665b to your computer and use it in GitHub Desktop.
Difference in instantiation semantics in Java for String.
class Playground {
public static void main(String[ ] args) {
String[] ex1 = new String[] { new String("a"), "b" };
String[] ex2 = new String[] { new String("a"), "b" };
evaluateReferenceEquality(ex1, ex2);
evaluateValueEquality(ex1, ex2);
}
public static void evaluateReferenceEquality(String[] a, String[] b) {
System.out.println("Reference equality");
for(int i = 0; i < a.length; i++) {
System.out.println(a[i] == b[i]);
}
}
public static void evaluateValueEquality(String[] a, String[] b) {
System.out.println("Value equality");
for(int i = 0; i < a.length; i++) {
System.out.println(a[i].equals(b[i]));
}
}
}
/* Output:
Reference equality
false
true
Value equality
true
true
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment