Java Reference
In-Depth Information
This provides an explicit choice between two courses of action - one for when the
if
expression is
true
and another for when it is
false
.
We can apply this in a console program and try out the
random()
method from the
Math
class at the
same time.
Try It Out - if-else
When you have entered the program text, save it in a file called
NumberCheck.java
. Compile it and
then run it a few times to see what results you get.
public class NumberCheck {
public static void main(String[] args) {
int number = 0;
number = 1+(int)(100*Math.random()); // Get a random integer between 1 & 100
if(number%2 == 0) { // Test if it is even
System.out.println("You have got an even number, " + number); // It is even
} else {
System.out.println("You have got an odd number, " + number); // It is odd
}
}
}
How It Works
We saw the method
random()
in the standard class
Math
in the previous chapter. It returns a random
value of type
double
between 0.0 and 1.0, but the result is always less than 1.0, so the largest number
you will get is 0.9999... (with the number of recurring digits being limited to the maximum number that
the type
double
will allow, of course). Consequently, when we multiply the value returned by 100.0
and convert this value to type
int
with the explicit cast, we discard any fractional part of the number
and produce a random integer between 0 and 99. Adding 1 to this will result in a random integer
between 1 and 100, which we store in the variable
number
. We then generate the program output in
the
if
statement. If the value of
number
is even, the first
println()
call is executed, otherwise the
second
println()
call in the
else
clause is executed.
Note the use of indentation here. It is evident that
main()
is within the class definition, and the code
for
main()
is clearly distinguished. You can also see immediately which statement is executed when
the
if
expression is
true
, and which applies when it is
false
.
Nested if Statements
The statement that is executed when an
if
expression is
true
can be another
if
, as can the statement
in an
else
clause. This will enable you to express such convoluted logic as "if my bank balance is
healthy then I will buy the car if I have my check topic with me, else I will buy the car if I can get a
loan from the bank". An
if
statement that is nested inside another can also itself contain a nested
if
.
You can continue nesting
if
s one inside the other like this for as long as you still know what you are
doing - or even beyond if you enjoy confusion.
To illustrate the nested
if
statement, we can modify the
if
from the previous example: