I am new in java.
In java, String
is a class
.But
we do not have to use new
keyword to create an object of class String<
The Java language specification allows for representation of a string as a literal. You can consider it a shortcut initialization for a String that has one important side-effect that is different from regular initialization via new
String literals are all interned, which means that they are constant values stored by the Java runtime and can be shared across multiple classes. For example:
class MainClass (
public String test = "hello";
}
class OtherClass {
public String another = "hello";
public OtherClass() {
MainClass main = new MainClass();
System.out.println(main.test == another);
}
}
Would print out "true" since, both String instances actually point to the same object. This would not be the case if you initialize the strings via the new keyword.