Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

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

equals( ) Versus ==

It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:


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));  
  } 
}

The variable s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

Hello equals Hello −> true
Hello == Hello −> false
 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top