Decisions in Java – The IF Statement
Two Actions – The if-else Statement
In performing a task, we often want to take one of two possible actions depending on the conditions at
the time.
Java uses an if statement similar to the form shown above.
If the <boolean expression> evaluates to true, the first block of code will be executed. If the
<boolean expression> evaluates to false, the second block of code will be executed.
It is also possible to illustrate the action of statements with a flow chart. As the program executes, we
travel along the paths of the flow chart diagram, following the direction of the arrows.
Page 1 of 7
If you have homework, then
you should do it
otherwise
you can go to a movie.
if (<boolean expression>)
{
<statement1 - to be executed for true expression>
}
else
{
<statement2 - to be executed for false expression>
}
Evaluate
<expression>
Execute
<statement1>
Execute
<statement2>
false
true
Decisions in Java – The IF Statement
Example 1 – This program compares two integers supplied by the user and prints an appropriate
message.
One Action – The if Statement
There are times when we only want to take action when a condition is true, but we do nothing if the
condition is false.
Java allows us to write an if statement that has no else branch.
Page 2 of 7
class IfElseDemo
{
public static void main (String [] args)
{
int first, second;
System.out.println("Please give one integer");
first = In.getInt();
System.out.println("and a second integer");
second = In.getInt();
if (first == second)
{
System.out.println("The values are equal");
}
else
{
System.out.println("The values are not equal");
}
}
}
Evaluate
<expression>
Execute
<statement>
true
false
if (<boolean expression>)
{
<statement1 - to be executed for true expression>
}
Decisions in Java – The IF Statement
Example 2 – This program determines the magnitude of a value using the absolute value method from
the Math class. Any negative value is changed to positive, while positive values are unaffected.
Programming Template for If Statements
Page 3 of 7
class IfDemo
{
public static void main (String [] args)
{
float number;
System.out.print("Please enter a number: ");
number = In.getFloat();
if (number < 0)
{
System.out.println("Negative changed to positive");
number = Math.abs(number);
}
System.out.println("The magnitude is " + number);
}
}
class <ClassName>
{
public static void main (String [] args)
{
// declare any variables below
// end of variable declarations
if (<boolean condition>)
{
<statements if condition is true>
}
else
{
<statements if condition is false>
}
}
}
Decisions in Java – The IF Statement
Exercises
1. Write Java statements to perform each task.
(a) Add one to the value of zeroCount if the variable total has the value zero.
(b) Add one to the value of pageCount if the variable lineCount is greater than pageLength.
(c) Set the value of the boolean variable leftSide to true if the int variable page is even, and to
false if page is odd.
(d) Determine if the the int variable n is a perfect square and then display an appropriate
message. (difficult question)
2. Write a program that will ask the user for two int values and determine which one has the greatest
value (i.e., higher on the number line). The program should output something like, "The number x
has the greatest value", where x is one of the numbers.
3. Write a program that will ask the user for two int values and determine if the first divides evenly
into the second, displaying a message depending on the result. For example, the number 2
divides evenly into 4, but 4 does not divide into 2 (so order matters). Hint: You may find the
modulo operator (%) useful here.
4. Write a program that will ask the user for two float values and compare their magnitudes. For
example, if the user entered 3 and -9, the program should respond that -9 has the greater
magnitude.
5. Write a program that solves an equation of the form
a xb = 0
. The program should prompt the
user for values of a and b, then solve the equation for x and print the results. The program should
take appropriate action if a is zero.
6. A quadratic equation in the form
a x
2
b xc = 0
has roots (or zeroes) given by
x =
b±
b
2
4 a c
2 a
Write a program that determines the values of the roots, root1 and root2, of the quadratic
equation after asking the user to input values for a, b, and c. The program should take show
appropriate messages if:
(a) the value of a is zero (in which case, see Exercise #4), and
(b) there are two, one, or zero real roots (you cannot take the square root of a negative
number).
Hint: There are two roots for the quadratic, which can be determined using the following code.
Page 4 of 7
root1 = (-1 * b + Math.sqrt(b^2 – 4 * a * c)) / (2 * a);
root1 = (-1 * b - Math.sqrt(b^2 – 4 * a * c)) / (2 * a);
Decisions in Java – The IF Statement
Solutions
1.
(a)
if (total == 0)
{
zeroCount = zeroCount + 1;
}
(b)
if (lineCount > pageLength)
{
pageLength = pageLength + 1;
}
(c)
// use modulo (%) to see if page is divisible by 2 (remainder 0)
// or not divisible by 2 (remainder 1)
remainder = page % 2;
if (remainder = 0)
{
leftSide = true; // page is even
}
else
{
leftSide = false; // page is odd
}
(d)
// determine square root of value, but rounded down
squareRoot = (int) Math.sqrt(value);
// square that result
rootSquared = squareRoot * squareRoot;
if (rootSquared == value)
{
System.out.println(value + " is a perfect square");
}
else
{
System.out.println(value + " is NOT a perfect square");
}
Page 5 of 7
Decisions in Java – The IF Statement
2.
class GreatestValue
{
public static void main (String [] args)
{
int first, second;
System.out.println("Please give one integer");
first = In.getInt();
System.out.println("and a second integer");
second = In.getInt();
// determine which value is greatest
if (first >= second)
{
System.out.println(first + " is the greatest value");
}
else
{
System.out.println(second + " is the greatest value");
}
}
}
3.
class PerfectSquares
{
public static void main (String [] args)
{
int first, second;
System.out.println("Please give one integer");
first = In.getInt();
System.out.println("and a second integer");
second = In.getInt();
// check if second value divides evenly into the first
// using the modulo operator – look for zero remainder
if (second % first == 0)
{
System.out.println(first + "divides into " + second);
}
else
{
System.out.println(first + "does not divide into " +
second);
}
}
}
Page 6 of 7
Decisions in Java – The IF Statement
4.
class Magnitudes
{
public static void main (String [] args)
{
float x, y;
System.out.println("Please give one real number");
x = In.getFloat();
System.out.println("and a second real number");
y = In.getFloat();
// compare the magnitudes of the values
if (Math.abs(x) >= Math.abs(y))
{
System.out.println(x + " has the greater magnitude");
}
else
{
System.out.println(y + " has the greater magnitude");
}
}
}
5.
class SolveLinearEquation
{
public static void main (String [] args)
{
float a, b, x;
System.out.println("We will solve: a x + b = 0");
System.out.println("Please give a value for a");
a = In.getFloat();
System.out.println("Please give a value for b");
b = In.getFloat();
// x = -b / a, but cannot divide by zero
if (a != 0)
{
x = -1 * b / a;
System.out.println("x = " + x);
}
else
{
System.out.println("a = 0 gives division by zero");
}
}
}
Page 7 of 7