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.
Related
This question already has answers here:
How to override equals method in Java
(11 answers)
Closed 6 years ago.
public class Employee {
String name;
public Employee(String var){ this.name=var;}
}
public class Main {
public static void main(String[] args){
String s1=new String("joe");
String s2=new String("joe");
Employee e1=new Employee("joe");
Employee e2=new Employee("joe");
system.out.println("When comparing String obj:"+s1.equals(s2)); output:TRUE
system.out.println("When comparing Employee obj:+e1.equals(e2)): output:FALSE
I know we have to override Employee class but Why it is working for String class and I couldn't able to locate the equals override method in Oracle docs for String class also.Please need help !!
In first case you are checking string.
In second case you are checking object of employee.
because two object have different memory address.
more details
String.equals() returns true if the two strings are not null and contain the same sequence of characters, as specified in the documentation by Oracle. This is different from Object.equals() : Object.equals() returns true if two references point to the same object in memory, see https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
The reason the example works as it does is because String overrides the equals method to check the content of the String, whereas the Employee class uses the Object.equals method, which checks memory location.
Different classes have different criteria for what makes 2 objects "equal". Normally, equals() returns true if it is the same Object:
Object a = new Object();
Object b = new Object();
return(a.equals(b));
This will return false, eventhough they are both "Object" classes, they are not the same instance. a.equals(a) will return true.
However, in cases like a String, you can have 2 different instances but String equality is based on the literal characters that make up those Strings:
String a = new String("example");
String b = new String("example");
String c = new String("another");
a.equals(b);
a.equals(c);
These are all different instances of String, but the first equals will return true because they are both "example", but the 2nd will not because "example" isn't "another".
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 String literals concatenation
(2 answers)
Closed 8 years ago.
public class SubString1
{
public static void main(String[] args)
{
String s="Sachin";
String sb=s+"Tendulkar";
String sbc="SachinTendulkar";
System.out.println(sb==sbc);
}
}
Output : false.
Please Explain how the output is false??
I couldn't understand the logic behind this type of object creation. According to me both should refer to same instance and Answer should have been true.
Please Explain.
They are different object references. Strings in Java are immutable.
If you want to compare the actual content of the Strings, use the .equals method.
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 ...
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have java syntax. Sory I'm still not figure out why this happen.
public class TestString {
public static void main(String [] args){
int i=-1;
String a=((Object)i).toString();
if(a=="-1"){
System.out.println("Same");
}else{
System.out.println("Not");
}
}
}
And then the result is "Not" what the problems why -1 string different with -1 int in object?
You have to use .equals() on string to compare.
String's equal method overridden in such a way.
Try
public class TestString {
public static void main(String [] args){
int i=-1;
String a=((Object)i).toString();
if(a.equals("-1")){
System.out.println("Same");
}else{
System.out.println("Not");
}
}
}
Strings have to be compared with the .equals() method.
You are using reference equality instead of object equality.
Since "-1" in the literal table has a different heap address than a newly allocated a, it returns false.
If for some reason you find yourself allocating a lot of String objects that share the same value(s) and want to test them by reference instead, consider using String#intern():
final String a = [...].intern(); // allocated
if (a == SOME_INTERNED_STRING_1) {
[...]
else if (a == SOME_INTERNED_STRING_2) {
[...]
}
==
compares reference which is not same in your case so if you want to compare string values then use
.equals() method
The == operator checks to see if two objects are exactly the same object . You can go for equals method to check if the value are equal or not