Possible Duplicate:
Strings in Java : equals vs ==
Why is this Java code not working correctly? The if statement is always being read as False, invariably giving an output of 4 for any input, including Anish & "Anish".
开发者_StackOverflow社区import java.util.Scanner;
public class lkjlj {
public static void main(String args []) {
Scanner Pillai = new Scanner(System.in);
System.out.println("Enter Your name");
String nabeel = Pillai.nextLine();
System.out.println(nabeel);
if (nabeel == "Anish") {
System.out.println("Your Age is 6");
} else {
System.out.println("Your age is 4");
}
}
}
You should use .equals for String comparisons, not ==.
Use this: nabeel.equals("Anish")
In Java, String.equals
checks if two strings have the same content, while ==
checks if they are the same object.
use
if(nabeel.equals("Anish"))
{
...
}
because, To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality.
精彩评论