How do I compare strings in Java?

Status
Not open for further replies.

katherinetk

Newbie level 1
Joined
Nov 6, 2018
Messages
1
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Location
USA
Activity points
8
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.

Is == bad? When should it and should it not be used? What's the difference?
 

The method equals() is more intuitive and compares the content of both variables, whereas depending on how you have declared the types to be compared, the resulted evaluation '==' could not berhave as expected; In short, always prefer using built in methods rather than operators in oriented programming languages when the resourse is available.
 

It's suggested to review a Java reference or tutorial in this regard, e.g. the Complete Java Reference issued by Oracle Press. It explains



Code Java - [expand]
1
2
3
4
5
6
7
8
9
10
// equals() vs == 
class EqualsNotEqualTo {  
  public static void main(String args[]) {    
    String s1 = "Hello";
    String s2 = new String(s1);    
    System.out.println(s1 + " equals " + s2 + " -> " +                       
                                s1.equals(s2));    
    System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));  
  } 
}

 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…