This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
Closed 7 years ago.
I was reading about == operator in java and found that it used to compare memory reference the below example is from given link.
String obj1 = new String("xyz");
// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;
if(obj1 == obj2)
System.out.printlln("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");
Note in the code above that obj2 and obj1 both reference the same
place in memory because of this line: “String obj2 = obj1;”. And
because the “==” compares the memory reference for each object, it
will return true. And, the output of the code above will be:
After that I write code randomly to check == operator but why it returning true in this example?
String obj1 = "ABC";
String obj2 = "ABC";
if(obj1 == obj2)
System.out.println("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");
Does "ABC" string saved in the one memory place then obj1 and obj2 sharing that memory reference?
Even int also returning true.
int obj1=3;
int obj2=3;
Strings are a bit special as they use String interning.
So yes, behind the screens those two strings have the same memory reference (but do not count on it for string comparison. See this question).
Replace your strings by
Object obj1 = new Object();
Object obj2 = new Object();
and you will get the expected output.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Is c point to a or is c point to the same memory that a is pointing to?
Why does the following code print "We are equal"?
Thanks in advance
public static void main(String args[]) {
String a = "10";
String b = "10";
String c = a;
if(c.equals(b)) {
System.out.println("We are equal ");
}
else {
System.out.println("Not equal! ");
}
}
Java stores objects by reference... the reference just happens to be the value when we use primitives.
int is a primitive so
a == c => true
a == b => true
b == c => true
With Strings the situation is slightly different. Strings are effectively char arrays: char[] but are not considered primitive types in Java.. so:
"str1" == "str1" => false since you're comparing two object references now.
For this reason the Object class has the equals() method which allows you to compare reference objects (non-primitives) via something other than the object reference ID. The String (a subclass of Object.class) class overrides the equals method.
In your example (above) you say:
So why is ab==abc false. They are both pointing to same address.
This is incorrect. ab points to String that is "meowdeal" and abc points to a String that is also "meowdeal"... but crucially they are two distinct instances. Therefore:
ab==abc => false - here your checking for reference equality - are they the same object reference (no they are not)
ab.equals(abc) => true - here you're checking for string equality (is ab's "meowdeal" the same as abc's "meowdeal" - yes it is.
This is one of those curveball interview questions you might get from time to time so worth being aware of.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
I am writing a static analysis tool for Java programs. And during analysis of assignment operators, for example, I want to know if underlying objects are using copy-by-value or copy-by-reference.
In case of primitive data types, I know, variables use copy-by-value.
int x = 5;
int y = x; // Both are pointing to independent memory locations.
In case of objects, usually they copy reference value of other objects. For example,
MyClass obj1 = new MyClass();
MyClass obj2 = obj1; // Both instances pointing to the same memory location.
However, in special cases, such as
String str1 = "myString";
String str2 = str1; // Both pointing to independent memory locations.
str1 = null; // Only str1 gets null
Objects use copy-by value, in my opinion. Please correct me if I am wrong. Similarly, StringBuilder and other java/lang/* classes that are declared with final keyword, their objects/instances behave like that. However, when being passed as parameter to a method, their reference values are passed.
So my question is that is there any way to find all such special cases where objects always use copy-by-value behavior? How can I find all such classes? This may not be an easy task, any kind of suggestion is welcome. Thanks.
For :
String str1 = "myString";
String str2 = str1; // Both pointing to independent memory locations. NO!
str1 = null; // Only str1 gets null
Consider this example :
public static void main(String[] args) {
String s1 = "hello";
String s2 = s1;
System.out.println(s2 == s1); // true . Both pointing to same location
s1=null; // s2 still points to "hello"
}
This question already has answers here:
What is the Java string pool and how is "s" different from new String("s")? [duplicate]
(5 answers)
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
When we do
String a=new String("mac");
String b=new String("mac");
if(b == a)
{
System.out.println("condition 1 is true");
}
if(b.equals(a))
{
System.out.println("condition 2 is true");
}
condition 1 fails and condition 2 is true since b and a are two different objects
But when we do
String a="mac";
String b="mac";
if(b == a)
{
System.out.println("condition 1 is true");
}
if(b.equals(a))
{
System.out.println("condition 2 is true");
}
Both the conditions are true. Why didn't java create a new object for second case. If java creates a new object only when we use new() then if we give different values to both the strings then what happens internally in java?
When you declare like below, Java create String literals in the String constant pool, and both references a and b will refer that String object "mac" in the pool
String a="mac";
String b="mac";
So, both == and .equals() returning true.
But, when you create String object by using new operator, String objects are created in the heap like other regular objects in java.
So == operator will return false, since both references referring two different object in the heap.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why are these == but not `equals()`?
why this code will print
true
true
public class Test {
public static void main(String[] args){
String st1 = "abc";
String st2 = "abc";
Integer k1 = 100;
Integer k2 = 100;
System.out.println(st1 == st2);
System.out.println(k1 == k2);
}
}
To compare objects we use method equals(). But why it is ok in this way?
== compares object references. Because of you're Strings being hardcoded, they are interned and both use the same reference, therefor the 1st true. Also Integer caches commonly used numbers, so both of your Integers also reference the same object, which makes the second reference comparison true.
1) Both strings will be treated as string literals which will be interned and stored to same memory location.
== checks for reference equality, so both references point to same object and returns true.
2) Integer instances are cached for small range that is why k1 == k2 returns true for 100.
System.out.println(st1 == st2);
st1 is stored in the string constant pool (when first created); when the compiler sees st2="abc" it will just point st2 to the previously created object in the string constant pool.
i.e., st1 and st2 point to the same object ("abc") in the String constant pool and == operator checks if two reference variables point to the same object.
System.out.println(k1 == k2);
In this case, your wrapper instances are cached to small range thus == returns true.
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 ==