Hello, i have a question. How do you compare 2 words or integers? the idea is a program should prompt the user to enter 2 words in one sentence (so like "apple orange") then it reads the 2 words and compares them to see if they are the same or not. Thank you!

Value comparison is done with the == operator.

For instance, the expression (5==5) will return true.

This operator works with all numerical values as well as with characters.

To compare strings, use the syntax (str1.equals(str2)).

For instance, ("apple".equals("orange")) will return false.

Kvass is right, but that isn't all you need to know to be able to do your program. Since the user is entering two words separated by a space, you will need to be able to get those two words into two separate Strings before you can follow Kvass's advice. The easiest way to do this would probably be to use a Scanner to read the text into two separate String variables.

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your words");
String first = keyboard.next();
String second = keyboard.next();

The code I gave you above should work for correct input, but given bad input, it will fail. If you read the tutorial I linked you to, you will figure out how to prevent your program from crashing if the user enters bad input. You can also check out the Scanner API to look at available methods of the Scanner class.

This article has been dead for over six months. Start a new discussion instead.