Search for more details......

Compareing two Strings in Java


When you want to compare two String variables in java, you could not use == operator to do that.
(If you used == to compare String it never equals, because of == operator check the memory location of these two objects. Not the content(actual object) )

equals method returns a boolean value you can check it. That value true if equals that two Strings.

equals

You can get equality of two Strings by calling equals method.


Example

public class StringComp{

    public static void main(String args[]){

        String name1="abc";//Create two String variables to test

        String name2="abc";


          if(name2.equals(name1)){//Check that two variables equal?


                 System.out.println("Same name") ;//If equal names prints 'Same name'


          } else{

                 System.out.println("Different names");  //If different names prints 'Different names'


         }

   }


}

No comments:

Post a Comment