Java Tutorial/Control Structures I - Decision structures

Decisions structures are used so that your program doesn't have to do the same thing each time it is executed. They basically answer a "question" on the spot, during execution.

Booleans
The decisions structures need a question to answer. This is done through booleans. A boolean is one of several primitives, which are essentially raw data.

A boolean represents two values - true and false. They can be assigned directly, but are usually constructed from a set of many operators. These operators include (but are not limited to):

These operators can be used together. You can use parentheses with these operators as well, to produce different booleans.

would result in true

would result in true, as the part within the parentheses is true

would result in false as the second part is false

Prepared BY: Chronicle Jerome

Statements
There are several statements that are used with the above booleans.

The statement
The if statement is used by itself. The structure is:

For example, if you wanted to say something like, "if 5 is not equal to 6, then print out 'not equal'":

If you get an error when using an if statement, then make sure that you do not have a semicolon after it:

The statement
You can use the if statement with the else if and else statements. The structure is:

It means, "if boolean is true, then do ... if not and boolean2 is true, then do ...". For example, in order to write out "If 5 is equal to 6, then write 'equal' to the console. If not and 7 is equal to 7, write '7=7' to the console":

Only "7=7" will be printed. However, if we replaced the first boolean with, only "equal" would be printed.

The statement
You can also add in the else statement. Note that you do NOT have to have an else if statement with the else statement. The structure is:

It means, "if boolean is true, then do ... else if boolean2 is true, do ... if both of the previous were false, then do ...". For example, to write out "if 5 equals 5, print '5=5'; if not, print '5!=5'":

Only "5=5" would be printed.