Java Notes
if Statement - Overview
Purpose
The purpose of the if
statement is to make decisions,
and execute different parts of your program depending on a boolean true/false value.
About 99% of the flow decisions are made with if
.
[The other 1% of the decisions use the switch/case
statement.]
General Forms
The if
statement has this form:
Do these statements before. if (condition) { Do this clause if the condition is true. } Do these statements after.
or
Do these statements before. if (condition) { Do this clause if the condition is true } else { Do this clause if the condition is false } Do these statements after.
Good programming practice - Always use braces
Style. It is good programming style to always write the curly braces, {}
,
altho they are not needed if the clause contains only a single
statement.
- Reliability. When code is modified, the indentation is such a strong indicator of structure that the programmer may not notice that the addition of a statement at the "correct" indentation level really isn't included in the scope of the if statement. This is a surprisingly common error.
- Readability. It is faster to read code with the braces because the reader doesn't have to keep in mind whether they are dealing with an un-braced single statement or a braced block.
Braces have been used in most language that have descended from Algol, including C, C++, Java, C#, etc because the language designers want to make it easy for programmers in earlier languages to make the transition. Unfortunately, they are extremely error prone, and languages such as Visual Basic and Python have chosen better solutions that don't use braces.
Condition is true
or false
The value of condition must be true
or false
(a boolean
value). It is often a comparison.
. . . int score; // Integer score on test. String scoreStr; // Temporary String form of score input. String comment; // Message to the user. scoreStr = JOptionPane.showInputDialog(null, "Your score?"); score = Integer.parseInt(scoreStr); if (score < 60) { comment = "This is terrible"; } else { comment = "Not so bad"; } JOptionPane.showMessageDialog(null, comment); . . .
The code above will display one of two messages, depending on the value of score.
'else' is not required
It is not necessary to have theelse
part of an
if
statement. Maybe only 50% of the time there is
an else
part.
Form
Theif
statement without an else
has this form:
if (condition) { do this if the condition is true }
Example
Here is apaintComponent()
method with an if statement without an
else
clause.
public void paintComponent(Graphics g) { super.paintComponent(g); // draw background etc. if (marks < 50) { g.setColor(Color.red); } g.drawString("Score = " + marks, 10, 50); }When the
paintComponent()
method begins, the Graphics context g
uses Color.black by default. Therefore there is no need to set the color to black.
Braces { }
not required for one statement
If the true
or false
part of
and if
statement has only one statement,
you do not need to use braces (also called "curly brackets").
Form
Theif
statement doesn't need braces if there is only
one statement in a part. Here both the true
and false
parts have only one statement:
if (condition) one statement to do if condition is true else one statement to do if condition is false
Example 1 - true and false parts
Here is apaintComponent()
method both with and without braces
which is possible only because each clause contains only one statement.
public void paintComponent(Graphics g) {
super.paintComponent(g); // call parent to paint background
if (marks < 50) {
g.setColor(Color.red); // bad marks in red
}else{
g.setColor(Color.black); // good marks in black
}
g.drawString("Score = " + marks, 10, 50);
}
and now without braces. Altho correct, it is not as safe a style.
public void paintComponent(Graphics g) {
super.paintComponent(g); // call parent to paint background
if (marks < 50)
g.setColor(Color.red); // bad marks in red
else
g.setColor(Color.black); // good marks in black
g.drawString("Score = " + marks, 10, 50);
}
Example 2 - only a true part
If there is only atrue
part of the if
statement, it only needs braces if there is more than one statement.
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (marks < 50)
g.setColor(Color.red); // bad marks in red
g.drawString("Score = " + marks, 10, 50);
}
If the if condition is false, this will not set the color,
so the default color will be used (black).
Should you always use braces?
If there is one statement, many programs use braces to make the code more robust. This is a safer practice because any later addition of a statement to one of the clauses will require braces. If you don't have the braces with multiple statements, the compiler may not give any error message, but your code will not do what was expected.What is a statement?
A statement is a part of a Java program. We have already seen some simple statements:- Assignment statement (eg,
x = 1;
). - Method call statement (eg,
g.setColor(Color.red);
). if
statement.
if
statement uses braces.
Indent to make programs readable
There are several methods to make programs readable.
How can you easily make the reader see which statements
are inside the true part and false part of an if
statement.
The best way to show this is to indent the statements that are inside. To do this you move the statements to the right by a few spaces. People commonly use two, three, or four spaces. Choose one number (eg, I use 2 or 3), and use it for all programs.
Java doesn't care about your indentation -- it is for humans (including yourself!).
Example 1 - No indentation - BAD BAD BAD
Here is thepaintComponent()
method from a previous page without
indentation. This is small, so it's easy to see which statements
are in the true and false parts. If the if
statement is
much larger, it will be unreadable without indentation.
public void paintComponent(Graphics g) { super.paintComponent(g); if (marks < 50) g.setColor(Color.red); else g.setColor(Color.black); g.drawString("Score = " + marks, 10, 50); }
Example 2 - No indentation and no line breaks
Even a very short method is almost unreadable when you take out the line breaks and spaces. Here is the same method:
public void paintComponent(Graphics g) {super.paintComponent(g);if (marks<50)
g.setColor(Color.red);else g.setColor(Color.black);g.drawString("Score = " + marks,10,50);}
if inside if
You can put an if
statement inside another if
statement.
Example -- series of tests
This code is correctly indented, but ugly and hard to read. It also can go very far to the right if there are many tests.
if (score < 35) g.setColor(Color.magenta); else if (score < 50) g.setColor(Color.red); else if (score < 60) g.setColor(Color.orange); else if (score < 80) g.setColor(Color.yellow); else g.setColor(Color.green);
Nearest 'else'
If you use braces, there is no problem with deciding which
else
goes with which if
For example,
if (age < 24) { if (height > 200) { c = Color.red; } } else { c = Color.blue; }
Because the true and false parts are both single statements, you might want to leave out the braces and write:
if (age < 24) if (height > 200) c = Color.red; else // DANGER: which 'if' goes with this 'else' c = Color.blue;
But this is WRONG, because 'else' always goes with the nearest 'if' when there are no braces. This code is the same as:
if (age < 24) { if (height > 200) c = Color.red; else c = Color.blue; }
Advice: Always use braces on if
statements
These kinds of errors are very hard to find. This is another good reason to always use braces.
Watch out for semicolons on your if statements
Why does the following code always say it thinks the user is lying?
String ageStr = JOptionPane.showInputDialog(null, "How old are you?"); int age = Integer.parseInt(ageStr); if (age > 120 || age < 0); System.out.println("I think you're lying about your age!");
It's the semicolon! if you put a semicolon directly after the condition
in an if
statement, Java thinks it's finished with the body
of the statement. The indentation of the next line, which is so important
to human readers, is ignored by Java.
This is another error that's harder to make if you always follow the condition by an opening brace.
Series of tests
It is common to make a series of tests on a value, where theelse
part contains only another if
statement.
If you use indentation for the else part, it isn't
easy to see that these are really a series of tests which
are similar. It is better to write them at the same indentation
level by writing the if
on the same line
as the else
.
Example -- series of tests
This code is correctly indented, but ugly and hard to read. It also can go very far to the right if there are many tests.if (score < 35) g.setColor(Color.magenta); else if (score < 50) g.setColor(Color.red); else if (score < 60) g.setColor(Color.orange); else if (score < 80) g.setColor(Color.yellow); else g.setColor(Color.green);
Example -- using 'else if' style
Here is the same example, using a style of writing theif
immediately after the else
. This is a common
exception to the indenting rules, because it results in much more
readable programs:
if (score < 35) g.setColor(Color.magenta); else if (score < 50) g.setColor(Color.red); else if (score < 60) g.setColor(Color.orange); else if (score < 80) g.setColor(Color.yellow); else g.setColor(Color.green);
Complaint
Some programming languages recognize this as a common kind structured-programming construction, and have a special 'elseif' statement. This would be a nice thing to add to Java.