-1

why the first code gives output as "true" and second code gives output as "false"?

code 1 ............... String str1="abc"; String str2="abc";

  if (str1==str2)
      System.out.println("true");
  else
       System.out.println("false"); 

code 2

NOTE : Input to both string will be same value ....................

 Scanner sc=new Scanner(System.in);
 System.out.println("enter string 1");
 String String1=sc.next();
 System.out.println("enter string 2");
 String String2=sc.next();

 if(String1==String2)
     System.out.println("true");
 else
     System.out.println("false");
Erandi
  • 719
  • 3
  • 7
  • 16

1 Answers1

0

The operator == checks the object identity The .equals() method checks if the value is equal to another string's value use:

if (str1.equals(str2)) {
    ...
}
Victor2748
  • 4,149
  • 13
  • 52
  • 89