Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

'if' Statement - 'else if' style

JavaFAQ Home » Java Notes by Fred Swartz Go to all tips in Java Notes by Fred Swartz


Bookmark and Share

Java: 'if' Statement - 'else if' style

Series of tests

It is common to make a series of tests on a value, where the else 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 the if 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.



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy