+ 1

Why is String a not equal to String b?!!Please read the description and let me know.

//I made this program to test the if statement import java.util.Scanner ; public class Program { public static void main(String[] args) { String a ="hi"; Scanner x =new Scanner (System.in); String b =x.nextLine(); if (a==b){System.out.println("Yes"); } else {System.out.println ("No");} } } //I input "hi" as the value of b. But the output was "No".Why? I did not put the quotes when I input the value of b. Please help me understand this. I will be highly grateful.

26th Aug 2017, 1:23 PM
Atin Roy
Atin Roy - avatar
4 Answers
+ 3
Try using a.equals(b) instead of a==b. In non-primitive types (like String), equals checks if the properties of two objects are equal (which is what you want), but == will only return true if a and b refer to THE SAME String object. But in your case, a and b are two separate, independent objects, so == will always be false, even if the properties of the two objects are equal.
26th Aug 2017, 1:39 PM
Daniel de Lizaur
+ 4
Use a.equals(b) instead of a==b...
26th Aug 2017, 3:43 PM
Dragon Slayer Xavier
Dragon Slayer Xavier - avatar
+ 3
Thanks a lot.
27th Aug 2017, 3:33 PM
Atin Roy
Atin Roy - avatar