These classnotes are depreciated. As of 2005, I no longer teach the classes. Notes will remain online for legacy purposes

JAVA01/If-Else Statements

Classnotes | JAVA01 | RecentChanges | Preferences

if statements

If you want to test a condition in a Java program, the most basic way is with an if statements. As you learned previously, the boolean type is used to store only two possible values: either true or false. The if statement works along those same lines, testing some condition and determining if it is true or false.

For example, if I had two integers defined thusly:

 int a = 5;
 int b = 6;

I could test if they were the same like this

 if (a == b) {
   // Yay, they are equal
 }

I could also test if a was greater than b like this

 if (a > b) {
  // Yay, a is greater than b
 }

else

If a conditional if statement returns false, it simply skips the block of code underneath it and proceeds on with the rest of the program. If, however, you want to do something else when the if statement fails, you can use the else statement

 if(a == b) {
   // Yay, they are equal
 } else {
   // Darn, they aren't equal
 }



Classnotes | JAVA01 | RecentChanges | Preferences
This page is read-only | View other revisions
Last edited May 29, 2003 12:57 am (diff)
Search:
(C) Copyright 2003 Samuel Hart
Creative Commons License
This work is licensed under a Creative Commons License.