+ 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.
4 ответов
+ 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.
+ 4
Use a.equals(b) instead of a==b...
+ 3
Thanks a lot.