Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

Thinking in Java
Prev Contents / Index Next

if-else

The if-else statement is probably the most basic way to control program flow. The else is optional, so you can use if in two forms:

if(Boolean-expression)
  statement


or
if(Boolean-expression)
  statement
else
  statement


The conditional must produce a boolean result. The statement is either a simple statement terminated by a semicolon, or a compound statement, which is a group of simple statements enclosed in braces. Any time the word “statement” is used, it always implies that the statement can be simple or compound.

As an example of if-else, here is a test( ) method that will tell you whether a guess is above, below, or equivalent to a target number:

//: c03:IfElse.java
import com.bruceeckel.simpletest.*;

public class IfElse {
  static Test monitor = new Test();
  static int test(int testval, int target) {
    int result = 0;
    if(testval > target)
      result = +1;
    else if(testval < target)
      result = -1;
    else
      result = 0; // Match
    return result;
  }
  public static void main(String[] args) {
    System.out.println(test(10, 5));
    System.out.println(test(5, 10));
    System.out.println(test(5, 5));
    monitor.expect(new String[] {
      "1",
      "-1",
      "0"
    });
  }
} ///:~


It is conventional to indent the body of a control flow statement so the reader can easily determine where it begins and ends.

Thinking in Java
Prev Contents / Index Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire