3

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".

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");  
        }
    }  
}
peterh
  • 11,875
  • 18
  • 85
  • 108
Ravin
  • 47
  • 2
  • As a matter of style, you should use pillai (lowercase) instead of Pillai (captalized). Captalized words are normally used for class names. – hugomg May 30 '11 at 17:09

3 Answers3

12

You should use .equals for String comparisons, not ==.

Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
  • 3
    +1 good answer though explanation why especially for the OP being Java beginner would be appreciated. Luckly others provided it. – Boro May 30 '11 at 16:38
  • Well, considering how many times the question has been asked, it didn't seem worth it to answer it in detail. I knew it would be closed as a duplicate quickly. – Paul Tomblin Jun 01 '11 at 15:00
10

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.

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
8

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.