Java "abc" == "abc" operation [duplicate] - java

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 7 years ago.
When we do:
String a = new String("abc");
String b = new String ("abc");
and do a a == b it returns false because they are 2 diferent objects.
But when we have this:
String c = "abc";
String d = "abc";
and we do a c == d it returns true. Why is that? Should it return false also? Why does the == operator behaves as a .equals() method in this case?

This happens because Java uses a so called Stringpool and tries to reuse old String-Literals to save some memory. But if you say "new String" you always create a new Object based on the Literal. See: here I would suggest you to always use the Objects.equals(a, b) if you want to make sure the objects are equal (or call equal on the Object itself if you're sure it's not null)

Related

why is jvm returning false when comparing two objects of same type? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
how to check reference equality in an object which implements content equality?
(5 answers)
Closed 4 years ago.
public class Test
{
public static void main(String[] args)
{
String s = new String("test");// ***
String s1 = s.toUpperCase();
String s2 = s.toLowerCase();
String s3 = s1.toLowerCase();
System.out.println(s==s1);//first case
System.out.println(s==s2);//second case
System.out.println(s==s3);//third case
}
}
1) Why does it return false for the third case(commented). Both s3 and s are pointing test yeah? But it seems JVM creates another object named test for s3 in the heap memory. But it is not the same for the second case(commented). It uses the object which was previously created as s(commented as *** in the code). Why is that?
2) And what happens to s1 object TEST because s3 is created from s1. Will s1 be destroyed or will it be in heap?
Here String s = new String("test"); object will be created in heap area (not inside String pooled area) but any other string returned after any operation will be created in String pooled area. To answer your question:
s==s3 returned false as they are two different objects.
s1 won't be collected by garbage collector until it is being referenced.

Difference in the results of String comparison in Java? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
How many Strings are created in memory?
(4 answers)
Closed 4 years ago.
How does Java implement the below string comparisons
public class MyClass {
public static void main(String args[]) {
String a = "Chaipau";
String b = "pau";
System.out.println(a == "Chai"+"pau"); //true
System.out.println(a == "Chai"+b); //false
}
}
This is different from How do I compare strings in Java? , as the answer does not contain the why a new object is created in the second case , when it could have pointed to the same object reference as it is done in the first case.
"Chai"+"pau" is semantically identical to "Chaipau", and thus is the same instance that a refers to.
"Chai"+b is evaluated at runtime (because b is not a compile-time constant expression), creating a new instance of String, and thus is not the same instance that a refers to.

Why BigInteger.ONE not equals to new BigInteger("1") in java? [duplicate]

This question already has answers here:
Compare two objects with .equals() and == operator
(16 answers)
Closed 7 years ago.
While using BigInteger class in Java8, i wrote this piece of code
System.out.println(new BigInteger("1")==BigInteger.ONE);
Ideally it should print true but its output is false. Why its output is false?
== checks if the objects point the same reference, so that if a = b the condition a == b. It's recommended to only do this with primitive types.
To check if the objects' content is the same, use the function equals(Object otherObject). For example:
new BigInteger("1").equals(BigInteger.ONE);
This will return true, as both objects' content is the same. Using == will return false though, as each object have different references.
Another example would be this:
MyObject object1 = new MyObject(30);
MyObject object2 = object1; //this will make them have the same reference
// This prints true, as they have the same content.
System.out.println(object1.equals(object2));
// This will print true, as they point the same thing, because they have the same reference
System.out.println(object1 == object2);
// We can see they have the same reference because if we edit one's field,
// the other's one will change too.
object1.number = 10;
System.out.println(object1.number); // prints 10
System.out.println(object2.number); // prints 10 too
new BigInteger("1")==BigInteger.ONE
Can rewrite as
BigInteger bigint =new BigInteger("1");
BigInteger bigint2= BigInteger.ONE;
Now
System.out.println(bigint ==bigint2); //false
Because they points to different references.
== checks the reference. Not the value inside them.
You can try using equals() method to check their equality.
Because you're using == instead of .equals(yourNumberToBeCompared)
You should do:
System.out.println(new BigInteger("1").equals(BigInteger.ONE));

why strings are showing different behaviour during concatenation? [duplicate]

This question already has answers here:
How to Compare strings in java [duplicate]
(6 answers)
Closed 7 years ago.
String a = "x";
String b = "x";
System.out.println(a==b);
It prints "true" as it shares the same memory in String constant pool. But when I write the following code,
String a = "x";
String b = a + "y";
String c = "xy";
System.out.println(b==c);
Its printing false.
I know '==' compares the instances.
My Question is - why instance is not same in the second scenario. When creating a new String, It always checks whether the same string is available in the pool or not. Then after creating String b i.e. "xy" is available in the pool. So when I'm trying to create String c with the same "xy", it should not create new instance. It should share the same memory rather than creating a new instance. Then, Why in the second scenario the instances are different??
here, a + "y" creates a new String object hence, == returns false. It checks for object references and not object equality.
When comparing strings, you should use the equals method.
== operator checks whether both references variable refer to same object
equals() method checks there the contents of objects are same
Learn the difference between == operator and equals method in case of strings
Problem is String is immutable, every update operation on string results into new string, and the == check the instance and not its value in case of class types.
Try final:
final String b = a + "y";
or use equals():
System.out.println(b.equals(c));
Edited:
String literals are directly available in string pool it is not same in this case String b = a + "y", here its in heap. You can use intern() to make it available in string pool.
String b = (a + "y").intern();
System.out.println(a==b);//true
This might work, and the explanation for why can be found here.
String a = "x";
String b = a + "y";
String c = "xy";
System.out.println(b.equals(c));

Understanding how string comparison works in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I am new to Java and I have difficulties in understanding String comparison. Can anyone explain the differences between the following scenarios?
Scenario 1 :
String a = "abc";
String b = "abc";
When I run the if(a == b) it returns true.
Scenario 2 :
String a = new String("abc");
String b = new String("abc");
and run if(a == b) then it returns false.
What is the difference?
== operator compares the references of two objects in memory. If they point to the same location then it returns true.String object in java are Immutable, so when you create Strings like in scenario1 then it didn't create new string. It just points the second string to the memory location of first string.
However, .equals() method compares the content of the String. When strings has same value then this method returns true.
So, in general it is recommended to use equals() method instead of ==.
It's because of Java String constant memory pool. Same valued literals are stored once.
String a = "abc";
String b = "abc";
// Now there is 1 string ("abc") and 2 references pointing to it.
String a = new String("abc");
String b = new String("abc");
// Now you have 2 string instances and 2 references.
Scenario 1 returns true because of a compiler optimization.
In general you should use equals() instead of == to compare strings.
In Java you need to use like this if(str.equals(str2)) which compares actual value of string rather than references.
Case1:
String a = "abc";
String b = "abc";
if(a == b)
In this case abc is cached in String constant pool thus a new string is not created String b = "abc"; b just refers to the string created by a it returns true as a and b both point to the same Object in the memory.
Case2:
String a = new String("abc");
String b = new String("abc");
and run if(a == b) then it returns false.
Here a two Strings are created and == operator just checks if two references point to the same reference, which it doesnt in this case thus it returns false
Two ways of creating string are
1) String s ="hello"; No. of string literal = 1 i.e. "hello" - No. of String objects on heap = 0
2) String s= new String("hello"); - No. of string literals =1 and No. of string objects =1
Java maintains a string pool of "LITERALS" and objects are going to stay on heap.
Advantage of string pooling: 1) Reduced memory usage*(PermGenSpace Issue) 2) Faster Comparision i.e == comparision 3) Faster lookup
Disadvantages: 1) Overhead of maintaining pool
How to pool String objects? Use Intern() on a string to add it to the pool. Downside of interning: 1) You may forget to intern some strings and compare them by == leading to unexpected results.
The reason is that the String literal "abc" will be turned into a global String instance for all its ocurrences, it will be the same String instance therefore you can be sure that "abc" == "abc". It is possible for the compiler to do that because String instances are immutable. However, if you explicitly allocate the String they will be two different instances and they will also be different to the String instance implicitly created by the compiler i.e. new String("abc") != new String("abc") and "abc" != new String("abc").
Another good example to understand what the compiler is doing is to look at this code:
"abc".contains("a");
you see that the literal behaves like an instance of a String type. You may exploit this to minimize programming errors e.g.
// this is OK and the condition will evaluate to false
String myStringValue = null;
if ("abc".equals(myStringValue)) { // false
whereas this code results in NPE:
// this will produce a NPE
String myStringValue = null;
if (myStringValue.equals("abc")) { // NPE

Categories