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.
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:
Java: Integer equals vs. ==
(7 answers)
Closed 5 years ago.
if (responseEntity.getBody().getMeta().getCode() != ApiExceptionEnum.SUCCESS.code()) {
return null;
}
code like this,
responseEntity.getBody().getMeta().getCode() -> Integer 1
ApiExceptionEnum.SUCCESS.code() -> Integer 1
sometimes it will return null !!
why ?
the response is from redis
In this case == or != checks whether compared objects are pointing to the same place in memory. To compare values stored in compared objects, use .equals() method inherited by all Java objects from Object class.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public class HelloWorld{
public static void main(String []args){
String a= "hello";
String ab= a +"John";
String abc = "helloJohn";
System.out.println(ab==abc);
}
}
It prints ab==abc false. Shouldnt it be true..??
Use yourStringVar.equals(anotherString) to check if they contain the same sequence of character, use == to check if they refer to the same object.
In java, String is an object, so two String-objects which have same content will not be equal (because those are different objects), hence abc == ab is not true.
But there are methods to compare the contents of String objects. These are:
abc.equals(ab)
or
abc.compareTo(ab) == 0
You should use for String equals/equalsIgnoreCase. '==' compares objects, NOT VALUES. Because when you make String a = "aa" means you create new object.(like new String("aa")). In java there're equals() and hashCode() methods inherited from Object class, but you may override them.
This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
In Program 1 I have declared two String and initialized them as "MADAM". When running I am checking the equality of their reference variable (by '==' operator') then I am getting a "true" response.
But in Program 2 I am declaring a String 'S' and initialize it as "MADAM". After that i am running a reverse loop and storing the characters of 'S' in reverse order in other String variable. Now i have again tried to check the equality of reference variable (by '==' operator') and am getting the response as 'false'. As both the String objects are of same value and are stored in constant Pool Area so both the variable should equate and the output in both the scenario should be 'true'. But WHY it is not same?
Program 1:
class Reverse {
public static void main(String[] args) {
String s="MADAM"; String rev="MADAM"; System.out.println(s==rev);
}
}
Output - true
Program 2:
class Reverse {
public static void main(String[] args) {
String s="MADAM"; String rev="";
for(int x=s.length()-1;x>=0;x--) { rev+=s.charAt(x); }
System.out.println(s==rev);
}
}
Output- false
In program 1 java compiler saves "MADAM" string in one memory location and assigns both "s" and "rev" to that location hence "s==rev" returns true because they both refer to the same address.
you should use "equals()" method to compare two strings. e.equals(rev);
have a look at this question:
Java String.equals versus ==
In your first class both strings are initialize to same object. So both are pointing to same memory location.
Next class, Rev is intilialized to "" value and see to madam so both have got different memory location. So false.
In essence,
if you use == for comparison, you are comparing their identity.
If you want to compare the object's value, use .equals()
String s="MADAM"; String rev="MADAM"; System.out.println(s==rev);
The above code will return true, because both Strings will be stored in the same memory location.
However, you can try the following, it will return you false:
String s1 = "aaa";
String s2 = new String("aaa");
System.out.println(s1 == s2); //false (comparing memory location)
System.out.println(s1.equals(s2)); //true (comparing value)
Side note: It is generally a bad practice to create Strings using new String(""). It was only used for demonstration purposes only.
This question already has answers here:
Java: Why can String equality be proven with ==?
(3 answers)
Closed 8 years ago.
class test {
public static void main(String[] args) {
String a = "Hiabc";
String b = "abc";
String c = "abc";
System.out.println(a.substring(2,5)==b);
System.out.println(b==c);
}
}
output:
false
true
As far as I understand, Java's == look for addresses of the two compared objects. Yet, I don't understand why b==c is true because they must have different addresses. Also, if b==c, then why is a.substring(2,5), which is "abc" == b false?
As far as I understand, Java's == look for addresses of the two compared objects.
Almost correct. Java uses references not addresses, e.g. a reference is strongly typed: See https://softwareengineering.stackexchange.com/questions/141834/how-is-a-java-reference-different-from-a-c-pointer
why b==c is true
The variable b and c are initialized with the same string reference, because they reference the same string literal "abc".
why doesn't substring expression reference the string literal "abc"?
Because the javadoc of substring() says
Returns a new string that is a substring of this string.
So the method does not ensure that a reference to a string from the constant pool is returned. If you want this you have to do
a.substring(2,5).intern()
and than
a.substring(2,5).intern()==b
will be true.
Never compare strings with == in Java.
Use .equal or .equalIgnoreCase methods instead.
The difference between a.substring(2,5) and b is because substring created another String object and it's on a different location than b. It's not about the characters ...