### if-then-else

No. 56

#### Providing better display

Q:

We reconsider Working with variables :

Source code Output
int a = -4,
b = 100;

System.out.println(a + "+" + b+ "=" + (a + b));
-4+100=96

Unfortunately a negative value yields:

Source code Output
int a = 100,
b = -4;

System.out.println(a + "+" + b + "=" + (a + b));
100+-4=96

This result looks awkward. Modify the code to see 100-4=96 in such cases. You may reconsider the findings from Why using braces in System.out.println(...) ? .

A:

The following simple solution does not work:

Source code Output
int a = 100,
b = -4;

if (b < 0) {
System.out.println(a + b + "=" + (a + b));
} else {
System.out.println(a + "+" + b + "=" + (a + b));
}
96=96

Since a and b are both variables of type int they get added rather than string style concatenated:

System.out.println(a + b + "=" + (a + b));
╲  ╱    ╱      ╲ ╱
96    ╱        96
╲  ╱        ╱
"96="      ╱
╲      ╱
"96=96"

Resolving this issue may be effected by adding an empty string ❶ forcing Java to use the concatenation + operator in favour of the arithmetic one:

System.out.println(a + ""❶ + b + "=" + (a + b));
╲ ╱       ╱            ╲ ╱
"100"     ╱             96
╲     ╱             ╱
"100-4"           ╱
╲          ╱
"100-4=96"
Source code Output
int a = 100,
b = -4;

if (b < 0) {
System.out.println(a + ""  + b + "=" + (a + b));
} else {
System.out.println(a + "+" + b + "=" + (a + b));
}
100-4=96

No. 57

#### Comparing for equality

Q:

Copy the following snippet into your IDE:

int count = 1;

if (count = 4) { // is count equal to 4?
System.out.println("count is o.K.");
}

The Java compiler will indicate an error:

Incompatible types.
Required: boolean
Found: int

Explain its cause in detail by examining the count = 4 expression.

### Tip

Java provides two similar looking operators = and == having (totally) different semantics.

A:

The two operators = and == are completely unrelated:

=

This is being called the assignment operator. A typical statement reads a = 34 assigning the int value 34 to a variable a.

Note this operator's semantics being completely different from even elementary math syntax. Consider:

$x = y ⇒ x 2 = y 2$

In math = denotes the equality of objects e.g. values, sets, functions and so on.

==

The comparison operator matching the usual math semantics comparing:

• Java primitive types for equality of value.

• Java objects for identity.

In particular an expression like count == 4 is of type boolean being either true or false.

More formally the expression count = 4 is of type int evaluating to 4 (surprise!). However an if (...) operates on boolean values only and if (4) thus does not make sense at all. The code in question may therefore be re-written as:

int count = 1;

int countAssignment = (count = 4); // Assigning expression count = 4 to variable countAssignment.

if (countAssignment) { // Error: An int is not a boolean!
System.out.println("count is o.K.");
}

Since the assignment operator is being evaluated from right to left we actually do not need braces:

...
int countAssignment = count = 4; // Assigning expression count = 4 to variable countAssignment
...

This code is equivalent to its counterpart with respect to compilation. The comment is count equal to 4? is thus misleading: The intended comparison requires using the == operator rather than an assignment operator =. Changing it the resulting expression is indeed of type boolean:

int count = 4 + 3;
final boolean test = (count == 4); // Now using "==" (comparison) in favour of "=" (assignment)
System.out.println("test=" + test);

Again we may omit braces here due to operator priority rules:

...
final boolean test = count == 4; // Now using "==" (comparison) in favour of "=" (assignment)
...

The boolean variable test will receive a value of false as expected. Thus our initial code just needs a tiny modification replacing the assignment operator «=» by the comparison operator «==»:

int count = 1;

if (count == 4) { // is count equal to 4?
System.out.println("count is o.K.");
}

### Note

In contrast to Java some programming languages like C and C++ allow for integer values in if (...) conditionals:

#include <stdio.h>

int main(int argc, char **args) {

int a = 3;
if (a = 4) {
printf("a has got a value of 4\n");
}
}

The integer expression count = 4 has got a value of 4. Integer values inside an if (...) statement will be evaluated as:

true

if the expression's value differs from zero

false

if the expression's value equals zero

Thus in C and C++ the expression if(count = 4) will always evaluate to true irrespective of the variable count's initial value. Most important: The C compiler will not issue an error or warning unless non-default, more restrictive compile time warning options are being activated. Consider this widely used «feature» to be dangerous at best.

For this reason it is good practice always using if (4 == count) rather than if (count == 4): Even in C you cannot assign a value to a constant literal. Thus an accidentally mistyped if (4 = count) statement will definitively result in a compile time error most likely saving its author from tedious debugging.