0

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?

1
  • 4
    Don't compare strings with ==. Use .equals() instead. Commented Mar 21, 2014 at 2:23

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1
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");}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.