-1
import java.util.Scanner;

public class NewClass {
    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter your name");
        String name = scanner.nextLine();
        System.out.println("Is "+ name + " really your name?");
        String answer1 = scanner.nextLine();
        if (answer1 == "yes"){
        System.out.println("Alright ");
        }else  {System.out.println("Liar!");
    }
    }
}

It outputs Liar! even though I typed yes, so that answer1 equals yes. Why?

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110

1 Answers1

4

Because with == you are testing reference equality, not value equality. Good reading.

Instead answer1 == "yes" do answer1.equals("yes").

Community
  • 1
  • 1
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110