I think the logic is sound but then again it don't work

Hey all am new to java and to this forum.

I was hoping some one could point out why my code is wrong. I am not nesisarily looking for some one to fix whats wrong with it, but for some one to explain whats wrong with my methodology ( i think i will learn better that way)

here is the ofending code

import java.util.Scanner;
public class letters2 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);

String ans = null;

System.out.print("Please choose yes or no y/n: ");
ans = reader.next();

if (ans == "y" )
System.out.print("You chose Yes y: ");
else if (ans == "n" )
System.out.print("You chose No n: ");


The problem is that it dosent go through the steps properly, (or at least how i want it to) regardles of the ans you type it goes straight to End!

all help would be apreciated


  • Beginner,
    You have found one of the most common stumbling blocks to noobs in Java, the operation of the "[color=Red]==[/color]" operator versus the [color=Red]equals[/color] method.
    In essence your program is comparing two string objects. When the == operator is used for two objects, what is determined is if the object references point to the same object. I know what I just said probably doesn't make sense, but it will one day.

    When comparing an object, ie. ans in this case, use the equals method to test if its content is the same as another string.
    [code] if (ans.equals("y")) {
    System.out.print("You chose Yes y: ");
    } else if (ans.equals("n")) {
    System.out.print("You chose No n: ");
    The == is basically only used to compare [link=http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html]primitives[/link]. (<= that is a link if you are interested)

    regards, se52
  • "==" operator perform shello comparison so whenever creating new objects it returns false.
    "equals" is a overridden method in string class so it perform deep comparison. so use Equals rather than ==.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!