if-then-else
Use
if (4 == variable) ...in favour of:
if (variable == 4) ... ❶
|
Some programming languages allow for interpreting integer
values as logical expressions. In »C / C++« for example an
A Java™ compiler will flag this as a
compile time error. On contrary in »C / C++« this is perfectly
correct code: The term Changing the order however even in »C / C++« results in a compile time error since we cannot assign a value to a literal: We are thus able to avoid this type of error in the first place. |
No. 53
Providing better display
|
Q: |
We reconsider Working with variables :
Unfortunately a negative value yields:
This result looks awkward. Modify the code to see
|
||||||||
|
A: |
The following simple solution does not work:
Since System.out.println(a + b + "=" + (a + b));
↘ ↙ ↙ ↘ ↙
96 ↙ 96
↘ ↙ ↙
"96=" ↙
↘ ↙
"96=96"Resolving this issue may be effected by adding an empty
string ❶ turning
our int variable int a = 3: String s = a + ""❶; This allows for left to right string concatenation: System.out.println(a + ""❶ + b + "=" + (a + b));
↘ ↙ ↙ ↘ ↙
"100" ↙ 96
↘ ↙ ↙
"100-4" ↙
↘ ↙
"100-4=96"
We may as well do this conversion explicitly: int a = 100,
b = -4;
if (b < 0) {
System.out.println(Integer.toString(a) + "" + b + "=" + (a + b));
} else {
System.out.println(a + "+" + b + "=" + (a + b));
} |
No. 54
Comparing for equality
|
Q: |
Copy the following snippet into your IDE: The Java™ compiler will indicate an error: Incompatible types. Required: boolean Found: int Explain its cause in detail by examining the TipJava™ provides two similar looking
operators |
|
A: |
The two operators
More formally the expression 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: 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 Again we may omit braces here due to operator priority rules: The NoteIn contrast to Java™ some
programming languages like C and C++ allow for integer values
in The integer expression
Thus in C and C++ the expression For this reason it is good practice always using |
Branches containing exactly one statement don't require a block definition.
double initialAmount = 3200;
if (100000 <= initialAmount)
System.out.println("Interest:" + 1.2 * initialAmount / 100);
else if (1000 <= initialAmount)
System.out.println("Interest:" + 0.8 * initialAmount / 100);
else
System.out.println("Interest:" + 0); |
|
