String literals vs string objects hashcode [duplicate] - java

This question already has answers here:
why '==' is returning false even after my hashcode value is same
(3 answers)
Closed 5 years ago.
I read that strings declared as literals are created on String Constant Pool
String s1 = "Hello";
String s2 = "Hello"; -> This will not create a new object and will refer to the s1 reference.
And strings declared with new keyword are created on both Heap Memory and String Constant Pool
String s3 = new String("Hello"); -> This will create a new object in the heap.
But will it create a new constant in the String Constant Pool also or will it use the one from s1?
I have this following code.
Hashcode for all s1, s2, and s3 are return as same.
public class question1 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3); // not sure why false result, s3 will create a separate constant in the pool? There is already a constant with value "Hello" created by s1. Please confirm if s3 will again create a constant.
}
}
I understant that == compares the object.
Are there two "Hello" defined in the String Constant Pool, one from s1 and one from s3?

String literals are automatically "interned," which places them in a pool. This minimizes the number of instances required. So, the two literals use the same String instance. hashCode() operates on the contents of the String in a consistent way. If two String instances have the same characters, then they will have the same hash code.

Related

Using "==" in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
What is the difference between "text" and new String("text")?
(13 answers)
Closed 3 years ago.
public class Test {
public static void main(String[] args)
{
String s1 = "HELLO";
String s2 = "HELLO";
System.out.println(s1 == s2); // true
}
}
But when I use :
public class Test {
public static void main(String[] args)
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2); // false
}
}
Can anybody please explain the difference here? Thankyou!
In the first example
String s1 = "HELLO";
String s2 = "HELLO";
the values of s1 and s2 are compile-time constants. Thus, the compiler does only generate a single String-object, holding the value "HELLO" and assings it to both s1 and s2. This is a special case of Common Subexpression Elimination, a well-known compiler optimization. Thus s1 == s2 returns true.
In the second example, two different Strings are constructed explicitly through new. Thus, they have to be separate objects per the semantics of new.
I created an Ideone demo a while back that highlights some cases that show this behaviour.
You can enforce that the same String is return by using String::intern():
String s1 = new String("HELLO").intern();
String s2 = new String("HELLO").intern();
System.out.println(s1 == s2); // will print "true";
Ideone demo
In case of String literal,before creating new Object in String Constant Pool ,JVM will check already same Object persist in SCP area or not if yes it will point to same object instead of creating new Object.Hence, below code s1 == s2 is true
String s1 = "HELLO";
String s2 = "HELLO";
System.out.println(s1 == s2); // true
but we are creating new object by using new keyword, it will create object in heap area, hence s1 and s2 are pointing to two different object, hence it is return false
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
from here How do I compare strings in Java?
== compares the objects reference pointer. When 2 objects are same exact object it will be true.
Instantiating a string using double quotes uses the string pool, creates a string once and reuses it.
Instantiating a string wit new always creates a brand new string.
== tests for reference equality (whether they are the same object).
First Case
System.out.println(s1 == s2); // true
Because you are comparing literals that are interned by the compiler and thus refer to the same object. Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions - are "interned" so as to share unique instances, using the method String.intern.
Second Case
System.out.println(s1 == s2); // false
You are comparing the Object reference which is different so you are getting false.
Please check https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28
i first case u comparing two strings with its ASCII values. thats why...//true
and in second case you are comparing two functions/methods. thats why... //false
the first one is true because s1 and s2 refer to the same string literal in the method area, the memory references are the same. ( == checks just the references in string). when the same string literal is created more than once, only one copy of each distinct string value is stored.
the second one is false because s1 and s2 refer to two different objects in the heap. different objects always have different memory references.

Java String intern function result problem [duplicate]

This question already has answers here:
The return of String.intern() explained
(3 answers)
Closed 3 years ago.
I'm learning Java now, and i read this question:What is Java String interning? - Stack Overflow
but i read other articles which provide some examples i don't understand:
public static void main(String[] args) {
String str2 = new String("str") + new String("01");
str2.intern();
String str1 = "str01";
System.out.println(str2 == str1); //true
String s4 = new String("1");
s4.intern();
String s5 = "1";
System.out.println(s4 == s5); //false
String s = new StringBuilder("aa").append("bb").toString();
String s2 = new StringBuilder("cc").toString();
System.out.println(s.intern() == s); //true
System.out.println(s2.intern() == s2); //false
}
the result in Java 11( it should be same in Java 8) is :
true
false
true
false
i don't know why results are different, i suppose it to be all true.
can anyone explains it?
Let's look at what intern actually does (emphasis mine):
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.
When this code is run:
str2.intern();
The string pool only contains "str" and "01". str2 is "str01", which is not in the string pool, so the object that str2 refers too is added to the string pool. Therefore, when the next line is reached, since "str01" is already in the pool, str1 will refer to the same object as str2.
Note that the reason why str2 == str1 is not because intern somehow changes which object str2 refers to. It doesn't do anything to str2. Strings are immutable after all.
Now we can understand the first false. In the line:
String s4 = new String("1");
Because of the string literal "1", "1" is added to the string pool. Note that the object that is added to the string pool is not the same as the object to which s4 refers. Now you call s4.intern(), which does nothing to s4, and returns the object that is in the string pool. But you are ignoring the return value. This is why s4 != s5, and s4.intern() == s5.
The reason for s2.intern() != s2 is much simpler - s2 refers to a different object than "cc" in the string pool! s2.intern() is supposed to return the object in the string pool, so of course it is not the same object!

In Java, by new operator is it possible to create different objects with same String content? [duplicate]

This question already has answers here:
Does java optimize string literal toLowerCase()?
(2 answers)
How do I compare strings in Java?
(23 answers)
How == returns false even though two Strings s1 and s3 having same hashcode? [duplicate]
(4 answers)
Closed 3 years ago.
In the below code, by hashCode() it seems 2 objects got created. Then although s1 == s3 is giving true, but why s1 == s4 is giving false ?
public class Main {
public static void main(String[] args) {
String s1 = new String("jordi") ;
String s2 = s1.toUpperCase() ;
String s3 = s1.toLowerCase() ;
String s4 = new String("jordi") ;
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println(s4.hashCode());
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s1==s4);
}
}
This gives output as :
101312786
70775026
101312786
101312786
false
true
false
s1 == s4
This performs reference comparison. So you're comparing the is both s1 and s4 point to the same object or not (which they don't - since you explicitly created two different objects)
When we use == operator for s1 and s4 comparison then it is false since both have different addresses in memory. It compares for memory address
Value objects (objects whose identity is unimportant and whose value is the only important thing about them, such as String and Integer), override equals and hashCode so that, for example, they can be used as keys in a HashMap. The hashCode value for String is specified in detail specifically so that any two strings with the same content will hash to the same value.
Your s1 and s3 are the same object because String#toLowerCase() has an optimization that returns this and avoids creating a new object if the entire string is already lowercase.
Use the .equals method instead of == for strings. Java gets a little screwy when you try to compare two strings with == instead of .equals()
Here's your code but fixed.
public static void main(String[] args) {
String s1 = new String("jordi");
String s2 = s1.toUpperCase();
String s3 = s1.toLowerCase();
String s4 = new String("jordi");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println(s4.hashCode());
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}

Java Strings Confusion [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
if (s1 == s2) is giving true
while (s3 == s4) is giving false.
Can somebody give a detailed explanation onto what is String pool, heap, how many objects are created in each line and how many objects created in total.
Why s3==s4 is giving false?
A detailed explanation will be much appreciated.
When you do new String(...), it is evaluated at runtime and hence creates two different instances and you end up getting s3 == s4 as false. Same thing happens when you use StringBuilder and do something like sb.toString() which is again evaluated at runtime.
For Example,
StringBuilder sb = new StringBuilder();
String foo = sb.append("abc").toString();
String bar = new String("abc");
String foobar = "abc";
Here foo, bar and foobar are all different objects and hence foo == bar or foo == foobar will evaluate to false.
On the other hand s1 == s2 returns true because abc one declared, already exists in the String Pool and in this case both the objects points to the same reference in the pool.
String Class in java is defined in java.lang package and it is exactly that, a class and not a primitive like int or boolean.
Strings are developed to offer operations with many characters ans are commmonly used in almost all the Java applications
Some interesting facts about Java and Strings:
String in immutable and final in Java and in this case JVM uses String Pool to store all the String objects.
What are different ways to create String Object?
We can create String object using new operator like any normal java class or we can use double quotes (literal assignment) to create a String object.
There are too several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilderetc etc.
To your Question:
When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.
So when you do
String s1 = "abc";
String s2 = "abc";
those are checked in the StringPool and since s1 already exist there, s2 will take the same reference, hence, s1 ==s2 is true.
but when you do:
String s3 = new String("abc");
String s4 = new String("abc");
you are using the new operator, therefore the JVM is not checking if there is an string already in the heap, it will just allocate a new space for s4, so is s3==s4 ??? of course no.
Please take a look at the image below for a more illustrative example.

what happens with new String("") in String Constant pool

if i create a string object as
String s=new String("Stackoverflow");
will String object created only in heap, or it also makes a copy in String constant pool.
Thanks in advance.
You only get a string into the constant pool if you call intern or use a string literal, as far as I'm aware.
Any time you call new String(...) you just get a regular new String object, regardless of which constructor overload you call.
In your case you're also ensuring that there is a string with contents "Stackoverflow" in the constant pool, by the fact that you're using the string literal at all - but that won't add another one if it's already there. So to split it up:
String x = "Stackoverflow"; // May or may not introduce a new string to the pool
String y = new String(x); // Just creates a regular object
Additionally, the result of a call to new String(...) will always be a different reference to all previous references - unlike the use of a string literal. For example:
String a = "Stackoverflow";
String b = "Stackoverflow";
String x = new String(a);
String y = new String(a);
System.out.println(a == b); // true due to constant pooling
System.out.println(x == y); // false; different objects
Finally, the exact timing of when a string is added to the constant pool has never been clear to me, nor has it mattered to me. I would guess it might be on class load (all the string constants used by that class, loaded immediately) but it could potentially be on a per-method basis. It's possible to find out for one particular implementation using intern(), but it's never been terribly important to me :)
In this case you are constructing an entirely new String object and that object won't be shared in the constant pool. Note though that in order to construct your new String() object you actually passed into it a String constant. That String constant is in the constants pool, however the string you created through new does not point to the same one, even though they have the same value.
If you did String s = "Stackoverflow" then s would contain a reference to the instance in the pool, also there are methods to let you add Strings to the pool after they have been created.
The new String is created in the heap, and NOT in the string pool.
If you want a newly create String to be in the string pool you need to intern() it; i.e.
String s = new String("Stackoverflow").intern();
... except of course that will return the string literal object that you started with!!
String s1 = "Stackoverflow";
String s2 = new String(s1);
String s3 = s2.intern();
System.out.println("s1 == s2 is " + (s1 == s2));
System.out.println("s2 == s3 is " + (s2 == s3));
System.out.println("s1 == s3 is " + (s1 == s3));
should print
s1 == s2 is false
s2 == s3 is false
s1 == s3 is true
And to be pedantic, the String in s is not the String that was created by the new String("StackOverflow") expression. What intern() does is to lookup the its target object in the string pool. If there is already a String in the pool that is equal(Object) to the object being looked up, that is what is returned as the result. In this case, we can guarantee that there will already be an object in the string pool; i.e. the String object that represents the value of the literal.
A regular java object will be created in the heap, and will have a reference s type of String. And, there will be String literal in String Constant Pool. Both are two different things.
My answer is YES!
Check the following code first:
String s0 = "Stackoverflow";
String s1 = new String("Stackoverflow");
String s2 = s1.intern();
System.out.println(s0 == s1);
System.out.println(s1 == s2 );
System.out.println(s0 == s2);
//OUTPUT:
false
false
true
s0 hold a reference in the string pool, while new String(String original) will always construct a new instance. intern() method of String will return a reference in the string pool with the same value.
Now go back to your question:
Will String object created only in heap, or it also makes a copy in String constant pool?
Since you already wrote a string constant "Stackoverflow" and pass it to your String constructor, so in my opinion, it has the same semantic as:
String s0 = "Stackoverflow";
String s1 = new String(s0);
which means there will be a copy in String constant pool when the code is evaluated.
But, if you construct the String object with following code:
String s = new String("StackoverflowSOMETHINGELSE".toCharArray(),0,13);
there won't be a copy of "Stackoverflow" in constant pool.

Categories