Java Notes
‘else’ Not Required
‘else’ is not required
It is not necessary to have the else
part of an if
statement. Maybe only 50% of the time there is an else
part.
Form
The if
statement without an else
has this form:
if (condition) { do this if the condition is true }
Example
Here is a paintComponent()
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.
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-10-31