String.equals versus == [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?
public static void main(String...aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos = "Jorman 14988611";
StringTokenizer tokens = new StringTokenizer(strDatos, " ");
int nDatos = tokens.countTokens();
String[] datos = new String[nDatos];
int i = 0;
while (tokens.hasMoreTokens()) {
String str = tokens.nextToken();
datos[i] = str;
i++;
}
//System.out.println (usuario);
if ((datos[0] == usuario)) {
System.out.println("WORKING");
}
}

Use the string.equals(Object other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.
if (usuario.equals(datos[0])) {
...
}
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.

Meet Jorman
Jorman is a successful businessman and has 2 houses.
But others don't know that.
Is it the same Jorman?
When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:
Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.
That's how the operator == behaves. So it will say that datos[0]==usuario is false, because it only compares the addresses.
An Investigator to the Rescue
What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms.
Here's the source code of String's equals() method:
It compares the Strings character by character, in order to come to a conclusion that they are indeed equal.
That's how the String equals method behaves. So datos[0].equals(usuario) will return true, because it performs a logical comparison.

It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.
Only right way is using .equals() -> datos[0].equals(usuario). == says only if two objects are the same instance of object (ie. have same memory address)
Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language

The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).
Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented and it checks whether two strings have the same value or not.
Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1; // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2; // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.

equals() function is a method of Object class which should be overridden by programmer. String class overrides it to check if two strings are equal i.e. in content and not reference.
== operator checks if the references of both the objects are the same.
Consider the programs
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
Here the abc and xyz, both refer to same String "Awesome". Hence the expression (abc == xyz) is true.
String abc = "Hello World";
String xyz = "Hello World";
if(abc == xyz)
System.out.println("Refers to same string");
else
System.out.println("Refers to different strings");
if(abc.equals(xyz))
System.out.prinln("Contents of both strings are same");
else
System.out.prinln("Contents of strings are different");
Here abc and xyz are two different strings with the same content "Hello World". Hence here the expression (abc == xyz) is false where as (abc.equals(xyz)) is true.
Hope you understood the difference between == and <Object>.equals()
Thanks.

== tests for reference equality.
.equals() tests for value equality.
Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).
== is for testing whether two strings are the same Object.
// These two have the same value
new String("test").equals("test") ==> true
// ... but they are not the same object
new String("test") == "test" ==> false
// ... neither are these
new String("test") == new String("test") ==> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" ==> true
// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st" ==> true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false
It is important to note that == is much cheaper than equals() (a single pointer comparision instead of a loop), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement. However, these situations are rare.

Instead of
datos[0] == usuario
use
datos[0].equals(usuario)
== compares the reference of the variable where .equals() compares the values which is what you want.

Let's analyze the following Java, to understand the identity and equality of Strings:
public static void testEquality(){
String str1 = "Hello world.";
String str2 = "Hello world.";
if (str1 == str2)
System.out.print("str1 == str2\n");
else
System.out.print("str1 != str2\n");
if(str1.equals(str2))
System.out.print("str1 equals to str2\n");
else
System.out.print("str1 doesn't equal to str2\n");
String str3 = new String("Hello world.");
String str4 = new String("Hello world.");
if (str3 == str4)
System.out.print("str3 == str4\n");
else
System.out.print("str3 != str4\n");
if(str3.equals(str4))
System.out.print("str3 equals to str4\n");
else
System.out.print("str3 doesn't equal to str4\n");
}
When the first line of code String str1 = "Hello world." executes, a string \Hello world."
is created, and the variable str1 refers to it. Another string "Hello world." will not be created again when the next line of code executes because of optimization. The variable str2 also refers to the existing ""Hello world.".
The operator == checks identity of two objects (whether two variables refer to same object). Since str1 and str2 refer to same string in memory, they are identical to each other. The method equals checks equality of two objects (whether two objects have same content). Of course, the content of str1 and str2 are same.
When code String str3 = new String("Hello world.") executes, a new instance of string with content "Hello world." is created, and it is referred to by the variable str3. And then another instance of string with content "Hello world." is created again, and referred to by
str4. Since str3 and str4 refer to two different instances, they are not identical, but their
content are same.
Therefore, the output contains four lines:
Str1 == str2
Str1 equals str2
Str3! = str4
Str3 equals str4

You should use string equals to compare two strings for equality, not operator == which just compares the references.

It will also work if you call intern() on the string before inserting it into the array.
Interned strings are reference-equal (==) if and only if they are value-equal (equals().)
public static void main (String... aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos="Jorman 14988611";
StringTokenizer tokens=new StringTokenizer(strDatos, " ");
int nDatos=tokens.countTokens();
String[] datos=new String[nDatos];
int i=0;
while(tokens.hasMoreTokens()) {
String str=tokens.nextToken();
datos[i]= str.intern();
i++;
}
//System.out.println (usuario);
if(datos[0]==usuario) {
System.out.println ("WORKING");
}

Generally .equals is used for Object comparison, where you want to verify if two Objects have an identical value.
== for reference comparison (are the two Objects the same Object on the heap) & to check if the Object is null. It is also used to compare the values of primitive types.

== operator compares the reference of an object in Java. You can use string's equals method .
String s = "Test";
if(s.equals("Test"))
{
System.out.println("Equal");
}

If you are going to compare any assigned value of the string i.e. primitive string, both "==" and .equals will work, but for the new string object you should use only .equals, and here "==" will not work.
Example:
String a = "name";
String b = "name";
if(a == b) and (a.equals(b)) will return true.
But
String a = new String("a");
In this case if(a == b) will return false
So it's better to use the .equals operator...

The == operator is a simple comparison of values.
For object references the (values) are the (references). So x == y returns true if x and y reference the same object.

I know this is an old question but here's how I look at it (I find very useful):
Technical explanations
In Java, all variables are either primitive types or references.
(If you need to know what a reference is: "Object variables" are just pointers to objects. So with Object something = ..., something is really an address in memory (a number).)
== compares the exact values. So it compares if the primitive values are the same, or if the references (addresses) are the same. That's why == often doesn't work on Strings; Strings are objects, and doing == on two string variables just compares if the address is same in memory, as others have pointed out. .equals() calls the comparison method of objects, which will compare the actual objects pointed by the references. In the case of Strings, it compares each character to see if they're equal.
The interesting part:
So why does == sometimes return true for Strings? Note that Strings are immutable. In your code, if you do
String foo = "hi";
String bar = "hi";
Since strings are immutable (when you call .trim() or something, it produces a new string, not modifying the original object pointed to in memory), you don't really need two different String("hi") objects. If the compiler is smart, the bytecode will read to only generate one String("hi") object. So if you do
if (foo == bar) ...
right after, they're pointing to the same object, and will return true. But you rarely intend this. Instead, you're asking for user input, which is creating new strings at different parts of memory, etc. etc.
Note: If you do something like baz = new String(bar) the compiler may still figure out they're the same thing. But the main point is when the compiler sees literal strings, it can easily optimize same strings.
I don't know how it works in runtime, but I assume the JVM doesn't keep a list of "live strings" and check if a same string exists. (eg if you read a line of input twice, and the user enters the same input twice, it won't check if the second input string is the same as the first, and point them to the same memory). It'd save a bit of heap memory, but it's so negligible the overhead isn't worth it. Again, the point is it's easy for the compiler to optimize literal strings.
There you have it... a gritty explanation for == vs. .equals() and why it seems random.

#Melkhiah66 You can use equals method instead of '==' method to check the equality.
If you use intern() then it checks whether the object is in pool if present then returns
equal else unequal. equals method internally uses hashcode and gets you the required result.
public class Demo
{
public static void main(String[] args)
{
String str1 = "Jorman 14988611";
String str2 = new StringBuffer("Jorman").append(" 14988611").toString();
String str3 = str2.intern();
System.out.println("str1 == str2 " + (str1 == str2)); //gives false
System.out.println("str1 == str3 " + (str1 == str3)); //gives true
System.out.println("str1 equals str2 " + (str1.equals(str2))); //gives true
System.out.println("str1 equals str3 " + (str1.equals(str3))); //gives true
}
}

The .equals() will check if the two strings have the same value and return the boolean value where as the == operator checks to see if the two strings are the same object.

Someone said on a post higher up that == is used for int and for checking nulls.
It may also be used to check for Boolean operations and char types.
Be very careful though and double check that you are using a char and not a String.
for example
String strType = "a";
char charType = 'a';
for strings you would then check
This would be correct
if(strType.equals("a")
do something
but
if(charType.equals('a')
do something else
would be incorrect, you would need to do the following
if(charType == 'a')
do something else

a==b
Compares references, not values. The use of == with object references is generally limited to the following:
Comparing to see if a reference is null.
Comparing two enum values. This works because there is only one object for each enum constant.
You want to know if two references are to the same object
"a".equals("b")
Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.

Use Split rather than tokenizer,it will surely provide u exact output
for E.g:
string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}
After this I am sure you will get better results.....

Related

string.concat(string) function, why my code is giving false in the output

String s1="Hello";
s1=s1.concat("World");
String s2="HelloWorld";
System.out.println(s1);
System.out.println(s2);
System.out.println(s2==s1); //false
As after concatenating, the "HelloWorld" string is created in the string constant pool and we are making another string with the same word "HelloWorld" then it is already present in the string constant pool hence it returns the existed reference.
So, why my code is giving false in the output?
String s1="Hello";
String s2="HelloWorld";
s1=s1.concat("World");
System.out.println(s1);
System.out.println(s2);
System.out.println(s2==s1);//false
String s1="Hello";
s1=s1+"World";
String s2="HelloWorld";
System.out.println(s1);
System.out.println(s2);
System.out.println(s2==s1);//false
why false??
why they are pointing to different ref.
As the word is already present in the string constant pool. then if we forming a new string object with the same value then it should point to the already present object.
The strings have not an equal identity by default. A string from the string pool is only returned if the string is interned.
All String values or String concatenations whose results are solely from constant expressions are interned automatically. A constant expression is an expression whose value is known at compile time. That includes:
literals; and
final variables of primitive types or the String class.
Examples:
String a = "Hello" + "World"; // 'HelloWorld'
String b = "Hi" + 23 + "There"; // 'Hi23There'
final int i = 47 + 100;
String c = "Number" + i + '!'; // 'Number147!'
This is defined in the Java Language Specification, § 15.28.
Your use case does not fulfill these requirements, so your result is false. You can trigger string interning by calling Strings intern() method. If you had written s1 = s1.concat("World").intern(); instead, then the result would be true.
You need to use equals instead of == , so your code must look like System.out.println(s2.equals(s1))
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
You are creating two objects s1 and s2 . So when you do
s2==s1
you are comparing references of those 2 objects, which will always return false as both objects are seperate.
If comparing contents of a string , try implementing the .equals() method.
s2.equals(s1)
s1 and s2 are 2 different references pointing towards 2 different addresses. Therefore s1==s2 will return false always (since different addresses).
This is because the concat() method returns a new String object
public String concat(String str) {
if (str.isEmpty()) {
return this;
}
return StringConcatHelper.simpleConcat(this, str);
}
If you used the "+" operator instead this will result in your expected output:
String s1 = "Hello" + "World";
String s2 = "HelloWorld";
System.out.println(s1 == s2); // true
Hope this helps for your understanding,
but for real world usage always stick to .equals() when comparing String values:
System.out.println(s1.equals(s2));

Why == operator is not working here, but equals work in java

I have written the code to check whether the given string is palindrome or not. But here I didn't create any String object explicitly. When we don't create explicitly, "==" also should work to compare the strings. But here I am not getting correct output if I use ==. For the clarity in my question, I have given another code also below
Code 1:Here. "==" is not working.
class Palindrome
{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer();
sb1.append("anna");
String s1=sb1.toString();
StringBuffer sb2=new StringBuffer();
sb2=sb1.reverse();
String s2=sb2.toString();
if(s1.equals(s2))
{
System.out.println("The given String is a Palindrome");
}
else
System.out.println("Not a Palindrome");
}
}
Code 2: Here == works
class Stringdemo
{
public static void main(String[] args)
{
String str1="hello";
String str2="hello";
if(str1==str2)
{
System.out.println("both strings are same");
}
else
{
System.out.println("both strings are not Same");
}
}
}
Using StringBuilder/Buffer.toString() will create a new instance hence why equals() works, but == doesn't. In the case of using string literals, any string that is a string literal will be added to the constants pool of the class, and hence string1 and string2 will merely point to that same reference within the constant pool for "hello", ergo == says true because they are the same reference.
"==" compares object reference values where "equals()" compares object contents. "==" is only really useful for comparing primitives.
When you call "sb2.toString()" it creates a new object which has a new reference value.
sb2.toString(); creates a new String. == won't work here
it will however work if you use sb2.toString().intern() instead
== checks for object identity equality (i.e., same memory address).
.equals() checks for for equality of the value.
When you create a new string literal:
String str1="hello";
String str2="hello";
Java calls the String.intern() method to intern the new String, but will first check to see if that same String value already exists, and if it does it will return that (i.e., will not create a new instance). See the Javadoc comments on String.intern() for more details:
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
This is why the second example works, but the StringBuilder example does not since calling sb2.toString creates a new instance, bypassing intern().
To be safe, you are better off using .equals() for any non-primative objects.
== operator just checks the object's reference, while equals() compares the strings for its characters seperately.
Since String are immutable objects therefore it shares the reference of objects if it is created already in memory.
Therefore,
String str1 = "hello"; //and
String str2 = "hello"; //are equal
Because both str1 and str2 shares the same reference of "hello".

String compare strange bug

I have strange bug in my code. I have variable type and when I load that from class Settings ( implements persistable ) it has value "CPU 21" (type="CPU 21"), but when I try
if(type=="CPU 21") the condition is false. How is that possible ?
It's not a bug at all. It's the way that == works.
For reference types (such as string), "==" will always compare the references directly. If you have two references which refer to separate objects with equal content, then "==" will evaluate to false. Use equals for value equality.
Note that it's easy to fool yourself by using String literals, which are interned:
String x = "CPU 21";
String y = "CPU 21";
boolean b = (x == y);
Now b is true because the values of x and y - the references are actually the same. They're referreing to the same String object. Compare that with this:
String x = new String("CPU 21");
String y = new String("CPU 21");
boolean b1 = (x == y);
boolean b2 = x.equals(y);
Now b1 is false because x and y refer to distinct String objects, but b2 is true because String.equals(String) compares the contents of the strings in question (i.e. the character sequences represented by the strings).
You have to use .equals() to compare string content:
if (type.equals("CPU 21")) ...
This is because the == operator only compares two references to see whether they are pointing to the same object or not. Since your string type is not the same object as the literal "CPU 21", the comparison is false. The .equals() method actually checks the strings themselves.
You may also find that people often write this the other way around:
if ("CPU 21".equals(type)) ...
This means the same thing, but will not throw an exception if type happens to be null.
What is difference between equals() and == ?
Explanation : 1
They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the '==' operator is expected to check the actual object instances are same or not.
For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.
s1 = new String("abc");
s2 = new String("abc");
Now, if you use the "equals()" method to check for their equivalence as
if(s1.equals(s2))
System.out.println("s1.equals(s2) is TRUE");
else
System.out.println("s1.equals(s2) is FALSE");
You will get the output as TRUE as the 'equals()' method check for the content equivality.
Lets check the '==' operator..
if(s1==s2)
System.out.printlln("s1==s2 is TRUE");
else
System.out.println("s1==s2 is FALSE");
Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' everytime a new object is created.
Try running the program without 'new String' and just with
String s1 = "abc";
String s2 = "abc";
You will get TRUE for both the tests.
Explanation : 2
By definintion, the objects are all created on the heap. When you create an object, say,
Object ob1 = new SomeObject();
Object ob2 = new SomeObject();
We have 2 objects with exactly the same contents, lets assume. We also have 2 references, lets say ob1 is at address 0x1234 and ob2 is at address 0x2345. Though the contents of the objects are the same, the references differ.
Using == compares the references. Though the objects, ob1 and ob2 are same internally, they differ on using this operation as we comare references. ob1 at address 0x1234 is compared with ob2 at address 0x2345. Hence, this comparison would fail.
object.equals() on the other hand compares the values. Hence, the comparison between ob1 and ob2 would pass. Note that the equals method should be explicitly overridden for this comparison to succeed.
you need to use equals(); to compare String values
replace
if(type=="CPU 21")
with
if("CPU 21".equals(type))
== will compare two reference variable. while equals will check the object's equality
Also See
java-string-equals-versus ==

If == compares references in Java, why does it evaluate to true with these Strings?

As it is stated the == operator compares object references to check if they are referring to the same object on a heap. If so why am I getting the "Equal" for this piece of code?
public class Salmon {
public static void main(String[] args) {
String str1 = "Str1";
String str2 = "Str1";
if (str1 == str2) {
System.out.println("Equal");
} else {
System.out.println("Not equal");
}
}
}
The program will print Equal. (At least using the Sun Hotspot and suns Javac.) Here it is demonstrated on http://ideone.com/8UrRrk
This is due to the fact that string-literal constants are stored in a string pool and string references may be reused.
Further reading:
What is String literal pool?
String interning
This however:
public class Salmon {
public static void main(String[] args) {
String str1 = "Str1";
String str2 = new String("Str1");
if (str1 == str2) {
System.out.println("Equal");
} else {
System.out.println("Not equal");
}
}
}
Will print Not equal since new is guaranteed to introduce a fresh reference.
So, rule of thumb: Always compare strings using the equals method.
Java stores all Strings in a string table internally during a run. The references to the two strings are identical because in memory they're stored in the same place. Hence, Equal.
Your statement is right, that == compares object references. Try the same thing with any other class but Strings and you won't get the same result.
This code won't print Equal.
But if the two strings were the same, this case would be special.
Now that you've updated your code, it is the case :
A simple (but not totally exact) explanation is that the compiler see that the two strings are the same and do something like :
String str1 = "Str1";
String str2 = str1;
What really happens here is that the compiler will see the literal string and put it in the "String literal pool".
As a String can't be modified (it's immutable) the literal values of Strings (those found during compilation) are put in a "pool".
This way, if two different literal strings which have the same content (like in this particular case), the memory isn't wasted to store "Str1" and "Str1" two times.
People, you are forgetting that the process of placing literal strings in the pool is called "interning". The class String has a method called intern(). This method puts any string into the pool, even if it is not in the pool initially (not literal). This means that code like this:
String a = "hello";
String b = new String("hello");
b = b.intern();
System.out.println(a == b);
will print "true".
Now, why would someone need this? As you can imagine, string comparison a.equals(b) might take a long time if strings are the same length but different close to the end.
(Just look at the .equals() source code.).
However, comparing references directly is the same as comparing integers (pointers in C speak), which is near instant.
So, what does this give you? Speed. If you have to compare the same strings many, many times, your program performance will benefit tremendously if you intern these strings. If however you are going to compare strings only once, there will be no performance gain as the interning process itself uses equals().
I hope this explains this.
thanks
Comments above have summed it up pretty well.
I don't have a Java environment handy, but attempting the following should clarify things for you (hopefully this works as I anticipate).
String str1 = "Str1";
String str2 = "Str"; str2 += "1";
Should now print Not equal

What is String pool in Java? [duplicate]

This question already has answers here:
What is the Java string pool and how is "s" different from new String("s")? [duplicate]
(5 answers)
Closed 9 years ago.
I am confused about StringPool in Java. I came across this while reading the String chapter in Java. Please help me understand, in layman terms, what StringPool actually does.
This prints true (even though we don't use equals method: correct way to compare strings)
String s = "a" + "bc";
String t = "ab" + "c";
System.out.println(s == t);
When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both s and t point to the same object and some little memory saved.
Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.
I don't think it actually does much, it looks like it's just a cache for string literals. If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool.
String s1 = "Arul"; //case 1
String s2 = "Arul"; //case 2
In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.
if(s1 == s2) System.out.println("equal"); //Prints equal.
String n1 = new String("Arul");
String n2 = new String("Arul");
if(n1 == n2) System.out.println("equal"); //No output.
http://p2p.wrox.com/java-espanol/29312-string-pooling.html
Let's start with a quote from the virtual machine spec:
Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.
This may not occur - This is a hint, that there's something special about String objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:
1: a := "one"
--> if(pool[hash("one")] == null) // true
pool[hash("one") --> "one"]
return pool[hash("one")]
2: b := "one"
--> if(pool[hash("one")] == null) // false, "one" already in pool
pool[hash("one") --> "one"]
return pool[hash("one")]
So in this case, variables a and b hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true.
This is not the case if we use the constructor:
1: a := "one"
2: b := new String("one")
Again, "one" is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false
So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).
As programmers we don't have to care much about the String pool, as long as we keep in mind:
(a == b) && (a.equals(b)) may be true or false (always use equals to compare Strings)
Don't use reflection to change the backing char[] of a String (as you don't know who is actualling using that String)
When the JVM loads classes, or otherwise sees a literal string, or some code interns a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string. If another copy is added, the runtime arranges it so that all the literals refer to the same string object. This is called "interning". If you say something like
String s = "test";
return (s == "test");
it'll return true, because the first and second "test" are actually the same object. Comparing interned strings this way can be much, much faster than String.equals, as there's a single reference comparison rather than a bunch of char comparisons.
You can add a string to the pool by calling String.intern(), which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string). The pooled version (the string returned from intern) will be equal to any identical literal. For example:
String s1 = "test";
String s2 = new String("test"); // "new String" guarantees a different object
System.out.println(s1 == s2); // should print "false"
s2 = s2.intern();
System.out.println(s1 == s2); // should print "true"

Categories

Resources