You need parenthesis:
System.out.println("The answer is " + (cal1-cal2) + ".");
Otherwise what you have is treated as
System.out.println(("The answer is " + cal1) - (cal2 + "."));
which is invalid since you can't subtract strings.
Why don't you have an error with the other operators? Well, *
and /
have higher precedences, so those are working as expected. +
, on the other hand, is overloaded to concatenate strings:
System.out.println("The answer is " + cal1+cal2 + "."); // concatenates, doesn't add
For example, if call1
is 1
and call2
is 2
, the result will be:
The answer is 12.
which isn't what you want. Again, this can be solved with parenthesis.