-2

Why if condition become false value even if the ans is hell. Is there something wrong with the program or what. I am using blueJ for java.

import java.util.Scanner;
public class QuizContest
{
Scanner value = new Scanner(System.in);
public void Contest()
{
    System.out.println("Please type- hell");
    String ans=value.next();       
    if(ans=="hell")
    {
        System.out.println("Congratulation. You are right");
    }
    else
    {
        System.out.println("You are wrong");
    }
}
}
deaddroid
  • 410
  • 2
  • 12
  • 4
    Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – akash Dec 25 '15 at 10:32

1 Answers1

0

Comaparing string in java should be done with equals(), not == change:

if(ans=="hell")

to:

if(ans.equals("hell"))

When you are comparing with ==, you expect both arguments to be the exact same instance in memory. this works well with primitives, but not with objects like String

Nir Levy
  • 12,750
  • 3
  • 21
  • 38