Created
February 1, 2018 07:25
-
-
Save rewinfrey/25855961273f760dfc1fb3ce26e2665b to your computer and use it in GitHub Desktop.
Difference in instantiation semantics in Java for String.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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