if-then-else
Interest:2.56 Done! |
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. 50
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 ❶ 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"
|
No. 51
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
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);
|