Home Java Java-tips Flow If 'else' Not Required

Ask Questions?

View Latest Questions

Advertisement


 
 

'else' Not Required
Posted on: July 26, 2006 at 12:00 AM
It is not necessary to have the else part of an if statement. Maybe only 50% of the time there is an else part.

Java Notes

'else' Not Required

'else' is not required

In this section we will learn about if else statement in more detail with example. 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
Advertisement


DMCA.com