Having never worked with Java much before, I was teaching myself generics syntax. I was testing out the simple generic function with some strings, and noticed something a little strange:
public class Main {
public static <T> boolean areSameReference(T lhs, T rhs) {
return lhs == rhs;
}
public static void main(String[] args) {
String s = new String("test1");
String t = s;
String u = new String("test1");
System.out.println(areSameReference(s, t)); //true
System.out.println(areSameReference(s, u)); //false
String v = "test2";
String w = "test2";
System.out.println(areSameReference(v, w)); //true
}
}
How come [s] and [u] are different references, but [v] and [w] are the same reference? I would have thought that with or without "new" the string literal would have caused them to be the same or different consistently in both cases.
Am I missing something else going on here?