Reputation: 101
After trying to test this Bufferered Reader
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
if (Br.readLine() == "one") print1();
if (Br.readLine() == "two") print2();
}
public static void print1(){
System.out.print("1");
}
public static void print2(){
System.out.print("2");
}
}
Nothing I can type in will get it to print. If I change the first "if" statement to
if (Br.readLine().startsWith("one") print1();
it will print "1" if I type in "one". Why does this happen?
Upvotes: 0
Views: 84
Reputation: 22972
if (Br.readLine() == "one") print1();
if (Br.readLine() == "two") print2();
== is comparing references of two string which is not same because consider both as different String Objects.
In java String Variable implicitly converted to String object as your comparison "one" is now object stored at some location other that location of String retrived from Br.readLine()
So in short both referencec are not Equal.
While equals()
method compares String Object Values in this kind of case.
if (Br.readLine().equals("one")) print1();
if (Br.readLine().equals("two")) print2();
While in int (Primitive types) == works fine here AutoBoxing and UnBoxing takes place.
Integer i=new Integer(5);
if(i==5){System.out.println("SAME");}
Upvotes: 1
Reputation: 152
when you are comparing strings you should change up ==
to be .equals()
due to the fact that .equals()
compares the contents of the strings to each other or is used to compare objects. ==
checks for reference equality or is used to compare primitives. I changed your code below:
if (Br.readLine().equals("one")) print1();
if (Br.readLine().equals("two")) print2();
Upvotes: 2