This is a question that I got in an interview.
I\'ve two strings defined as
String s1=\"Java\";
String s2=\"Java\";
My question i
Adding to others: new keyword always forces to create a new object. If you declare like below:
String s1 = "some";
String s2 = "some";
Then using String Pooling mechanism, both references s1 and s2 will refer to the same String object with the value "some".
The process of combining identical strings is called "interning", and has been done for many years by lots of language compilers, but not always. The answer to the question, especially as expanded by @GennadyVanin--Novosibirsk, depends on the language and the compiler implementation. For Java, all constant strings are interned, as required by the Java Language Specification. But that's only constant string expressions, and only when they're compiled at the same time. If you have two Java strings sufficiently separated in time and space (e.g., compiled into separate JAR files), they will not be the same object. Similarly, dynamically created Java strings (e.g., the output of various toString()
methods) won't be interned unless the method specifically requests it via String.intern()
. And yes, all uses of an interned string will share the same memory locations - that's a big part of why strings are interned in the first place.
As to other languages, that's a bigger question, but with all the information in these answers, I'm sure you can research it on the web. Suffice it to say that there is no universal agreement on how this ought to be done.
Example.
First example
String s1 = "FirstString";
String s2 = "FirstString";
if(s1 == s2) {
//This condition matched true because java don't make separate object for these two string. Both strings point to same reference.
}
Second example
String s1= "FirstString";
String s2 = new String("FirstString");
if(s1.equals(s2)) {
//This condition true because same content.
}
if(s1 == s2) {
//This condition will be false because in this java allocate separate reference for both of them
}
Conclusion: Java check whether string exist or not. If we create the object of second string using new and have different content then its creates object and assign different reference and In case of If we don't create the object using new and have same content then its assign the same reference as first string contain.