How To Compare Strings In Java Programming

I am trying to compare strings using eclipse. So when I type in square, it should match up with the "square" and then return a true statement.

But when I use the scanner to input the string, the string doesn't get compared right.
However, if I make a String shape and had its value as "square", then the if statement works. So it just doesn't work with the scanner. Anyone have any ideas?

My code is like this and I have everything declared, but I didn't want to type it out:

Scanner in = new Scanner(

shape = in.NextLine();

if (shape == "square") { true}
else {false}


Share this

Related Posts


8.1.12 delete

Java doesn't use == to compare Strings, you need to use a method. So you code should look like this:

if (shape.equals("square"){true}
else {false}

== is used only for primitive data types like: int, float, ... not Objects like: Integer, String, Float.

There was an error in this gadget