4.1.3.2 Condition


The basic form of a conditional statement is
if (condition) {
  statements 
}
else { 
  statements
}
where condition represents an expression which evaluates to a boolean value (i.e., true or false) and statements are a single Java statement or sequence of statements separated by semicolons. The if-statement is used for branching: depending on some condition, one sequence of Java statements is executed or another. The else part can be omitted.

As an example we present a Java applet that prints the number of characters and digits of the text entered in the input field.

The Applet

Java Code
The relevant method with the conditional statement is shown below. The complete source code can also be viewed.
  void countCharacters(String s) {
    char[] word = s.toCharArray();
    countDigits = 0;
    countNonDigits = 0;
    for (int i=0; i<word.length; i++) {
      if (Character.isDigit(word[i])) {
        countDigits++;
      }
      else {
        countNonDigits++;
      }
    }
  }
The program can be extended with a second test whether a non-digit is a letter via nested if-statements.
  void countCharacters(String s) {
    countDigits = 0;
    countLetters = 0;
    countOtherCharacters = 0;
    char[] word = s.toCharArray();
    for (int i=0; i<word.length; i++) {
      if (Character.isDigit(word[i])) {
        countDigits++;
      }
      else if (Character.isLetter(word[i])){
        countLetters++;
      }
      else {
        countOtherCharacters++;
      }
    }
  }
Then the applet looks as follows: