## The if conditional statement

No. 53

### 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 changing the two variables' values 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.

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. Resolving this issue may be effected by adding an empty string ❶ forcing Java to use the concatenation + operator in favour of the arithmetic one:

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. 54

### 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 underlying expression.

### Tip

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

A:

Java provides two seemingly similar but completely unrelated operators:

=

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.

Thus (count = 4) is an expression evaluating to 4. So the code in question may 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 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:

...
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.

No. 55

### Replacing else if (...){...} by nested if ... else statements

Q:

A computer newbie did not yet read about the else if(...) branch construct but nevertheless tries to implement the following logic:

if (a < 7) {
System.out.println("o.K.");
} else if (b == 5) {
System.out.println("Maybe");
} else {
System.out.println("Wrong!");
}

a and b are supposed to be int variables. Please help our newbie using just if(...){...} else {...}  avoiding else if(...) {} branch statements!

### Tip

As the title suggests you may want to nest an inner if(...) inside an outer one.

A:

The solution requires replacing the else if(...) branch by a nested if(...){ ...} else statement and moving the final else block into the nested one.

if (a < 7) {
System.out.println("o.K.");
} else {
if (b == 5) {
System.out.println("Maybe");
} else {
System.out.println("Wrong!");
}
}

No. 56

### Static code analysis

Q:

Consider the following snippet:

int count = 3;
count++;

if (count < 5)
return;
return;

System.out.println("Failed!");

This Java code mimics the Apple goto fail SSL bug's structural problem. Since Java does not offer goto statements we use return instead for terminating the current context.

Copy this code into your IDE and:

1. Explain the resulting error. What is wrong? How do you correct this error?

2. Explain the count++ statement's purpose.

### Tip

There is no real application logic in the given code. It is an example meant to explain formal Java language features. What happens if you correct the compile time error and in addition purge the count++ statement?

3. What is the underlying idea of these warning and error messages?

A:

1. Like in the Apple goto fail SSL bug the code is poorly indented. Using your IDE's auto formatting feature (how?) you get:

int count = 3;
count++;

if (count < 5)
return;
return;

System.out.println("Failed!");

The second return statement will leave the context unconditionally regardless of the preceding if (count < 5) and the count variable's value in particular. Thus the final System.out.println("Failed!") can never be reached resulting in a compile time error.

Removing the erroneous return resolves the error leaving us with happily compiling code:

int count = 3;
count++;

if (count < 5)
return;

System.out.println("Failed!");

Conclusion: The Apple goto fail SSL bug could not have been occurring in Java due to language features.

2. Removing count++ leaves us with:

int count = 3;

if (count < 5) ❶
return;

System.out.println("Failed!");
 Compiler warning: Condition 'count < 5' is always 'true'.

This warning is due to static compile time code analysis: The count variable's value is not being altered throughout its scope. It could actually be declared as final int count = 3 disallowing subsequent assignments. Thus the return inside if (count < 5) will always be executed.

Despite its simplicity having the count++ statement in place defeats the compiler's ability to discover that count now having a value of 4 still being smaller than 5.

3. The underlying idea is preventing programmers from coding carelessly: Even the if (count < 5) statement is most likely an unintended bug.

### Important

Conclusion: Watch out for compiler warning messages and do not ignore them!

In many cases compiler warnings reveal serious flaws. Correction on average will save you lots of cumbersome time debugging your code.

No. 57

### Post modifying an exam's marking

 Q: After completely marking an examination a lecturer decides to globally add a number extra bonus points to a specific task . The task does have an upper limit of points to be awarded at maximum. We provide an example: On completely fulfilling a given task 12 points will be awarded. So after marking the exam participants' points range from 0 to 12 points being represented by the variable pointsReached. After completing his marking our lecturer wants to add three more points to all participants without breaching the 12 point limit. Complete the following code by assigning this modified number of points to the variable newResult. public static void main(String[] args) { int pointsReached = 1; int maximumPoints = 12; int pointsToAdd = 3; final int newResult; // TODO: Assignment to variable newResult System.out.println("New Result:" + newResult); } A: The basic task is to add up the values of pointsReached and pointsToAdd. When exceeding the limit we just assign the limit itself: public static void main(String[] args) { final int pointsReached = 1; final int maximumPoints = 12; final int pointsToAdd = 3; final int newResult; if (maximumPoints <= pointsReached + pointsToAdd) { newResult = maximumPoints; } else { newResult = pointsReached + pointsToAdd; } System.out.println("New Result:" + newResult); }This basically means calculating the minimum of the two expressions pointsReached + pointsToAdd and maximumPoints. This may as well be be implemented by: public static void main(String[] args) { final int pointsReached = 1; final int maximumPoints = 12; final int pointsToAdd = 3; final int newResult = Math.min(maximumPoints, pointsReached + pointsToAdd); System.out.println("New Result:" + newResult); }You will fully understand the above expression Math.min(...) after finishing the “Static Final Variables” section of [Kurniawan].

No. 58

### At the bar

 Q: This example uses existing program code to be explained later. You'll implement an interactive application which implements a dialogue with a user asking for input to be entered in a terminal like window as being shown in the following video: Figure 185. Using a Scanner class collecting user input. Your Browser does not support the video tag A bar uses a software system for picking up orders. The bar will serve just orange juice and beer. For legal reasons the latter will only be served to persons of at least 16 years of age. We show three possible user dialogues: On offer: 1=Beer 2=Orange juice Your choice:>1 Tell me your age please:>15 Sorry, we are not allowed to serve beer to underage customers On offer: 1=Beer 2=Orange juice Your choice:>2 o.K. On offer: 1=Beer 2=Orange juice Your choice:>4 Sorry, invalid choice Since you may not yet know how to enable Java™ applications asking for user input simply use the following recipe to get started: public static void main(String[] args) { try (final Scanner scan = new Scanner(System.in)) { // Creating a scanner for reading user input System.out.print("Please enter a value:"); final int userInput = scan.nextInt(); System.out.println("You entered: " + userInput); // TODO: Implement «at the bar» logic } // Auto closing scanner }Copy this boilerplate code into your IDE. The IDE will assist you adding a required import java.util.Scanner; statement in your code's header section. Execute this code. You should see a dialogue like: Please enter a value:112 You entered: 112Then extend the above code implementing the desired behaviour. A: package start; import java.util.Scanner; public class BarOrder { public static void main(String[] args) { final Scanner scan = new Scanner(System.in); System.out.print("On offer:\n 1=Beer\n 2=Orange juice\n\nYour choice:>" ); final int beverageChoice = scan.nextInt(); // Read user input switch (beverageChoice) { case 1: System.out.print("Tell me your age please:>"); final int age = scan.nextInt(); if (age < 16) { System.out.println("Sorry, we are not allowed to serve beer to underage customers"); } else { System.out.println("o.K."); } break; case 2: System.out.println("o.K."); break; default: System.err.println("Sorry, invalid choice"); break; } scan.close(); } }

No. 59

### Roman numerals

Q:

Write an application which turns a positive integer values up to and including 10 into Roman numeral representation:

Enter a number:>9
IX

Regarding user input you may start from ??? again. If the user enters a value smaller than one or greater than ten the following output is to be expected:

Enter a number:>11
Decimal value 11 not yet implemented

### Tip

You may use a series of if () {...} else if () {...} ... statements.

A:

try (final Scanner scan = new Scanner(System.in)) {

System.out.print("Enter a number:>");
final int number = scan.nextInt();

if (1 == number) {
System.out.println("I");
} else if (2 == number) {
System.out.println("II");
} else if (3 == number) {
System.out.println("III");
} else if (4 == number) {
System.out.println("IV");
} else if (5 == number) {
System.out.println("V");
} else if (6 == number) {
System.out.println("VI");
} else if (7 == number) {
System.out.println("VII");
} else if (8 == number) {
System.out.println("VIII");
} else if (9 == number) {
System.out.println("IX");
} else if (10 == number) {
System.out.println("X");
} else {
System.out.println("Decimal value " + number + " not yet implemented");
}
}