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. 56
Providing better display
Q: |
We reconsider Working with variables :
Unfortunately a negative value yields:
This result looks awkward. Modify the code to see
|
||||||||
A: |
No. 57
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: |
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);
|
|