Q1. If it would have been some primitive data type I would understand, but what does this signify for a class type ?
In this case, "TestString"
is a string literal. A string literal also serves as a reference to an instance of String
. This is per the language specification, §3.10.5. So, in your particular case "TestString"
is a reference to an instance of String
, and you are assigning that same reference to your variable s
.
Now, there are some rather special things about String
s that are referred to by literals. Two string literals with the same value (logically, as strings) always refer to the same instance of String
. This is due to the "interning" of string literals.
However, when you say
String s = new String("TestString");
it is still the case that "TestString"
refers to an instance of String
, in fact to an instance in the string intern pool, but it is not the case that s
refers to this same string. Instead, s
is initialized to have its value equal to "TestString"
, but it is in fact a new reference. That is:
String s = new String("TestString");
String t = "TestString";
System.out.println(s == t);
This will print false
.
Q2. Is this kind of initialization allowed for user created classes as well ?
No.