Possible Duplicate:
Java String.equals versus ==
I thought this would be a neat way of structuring a picker method but the output is not going to the first two if statements and only outputs the last
public int myPickerMethod(){
System.out.println("please select from the options ");
System.out.println("please select 1 for option 1 ");
System.out.println("please select 2 please select 2 for option 2");
String input = keyboard.readLine();
System.out.println("input = " + input);
if(input=="1"){
return 1;
}
else if(input=="2"){
return 2;
}
else{
return 42;
}
}
Here is my result from the terminal:
please select from the options
please select 1 for option 1
please select 2 please select 2 for option 2
1
input = 1
response = 42
Same goes if I put 2 in. the “response” print statement is the output from the method from a print statement in the main class.
I have not tried this way before but I figured it should work. I don’t really get why it isn’t. Anyone able to clear this up? Thanks
For testing Object (non-primitive type) equality, use
Object.equals().The
==operator checks whether the references to the objects are equal. A test for reference equality is done within theString.equals() method, among other checks. Below is the Java source for theString.equals()method: