Frage

I'm current learning Java and working through a text book.

I have this piece of code given by the book which works bit like a calculator:

int num1= Integer.parseInt(args[0]);
int num2= Integer.parseInt(args[2]);
String msg = args[0] + args[1] + args[2] + "=";

if (args[1].equals("+")) msg += (num1 + num2));
else if (args[1].equals("-")) msg += (num1 + num2));

and so on.

In console you would do something like: java Args 10 + 2

What I want to know is if something like this can work (I haven't managed to make it work yet)

if(args[1] == "-") msg += (num1-num2));
War es hilfreich?

Lösung

The equals() method checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" (except the argument values as they are not compile-time constants) such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

if (string1.equals(string2)) {
    ...
}  

Taken from: Java String.equals versus == , with some modifications.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top