If/Else
if/else
The control structure that is probably most common between languages is the if and the if/else construct.
Example of how if can be used
As you might expect the if statement tests if something is true. Although what Java considers to be "true" can be subtly different from some other languages. For Java true is always a boolean test. It does not have any concept of true being zero, one or minus one, it is always a boolean comparison.
An if test must always evaluate to a boolean value, you cannot test if it returns 1, zero or -1 or anything but a boolean
If the test is true the lines of code immediately afterwards are executed, otherwise different lines get run.
To give a typical example
int i=0; if (i==1){ System.out.println("Good morning"); }
The curly braces create a block of code, which means if the test is true it will execute multiple lines of code. You can use the if statement without the braces so it is only the next line that is executed conditionally, using this format the previous example would appear as
int i=0; if (i==1) System.out.println(" Good morning");
However, many people consider this to be bad style as it is too easy to get confused as to where the impact of the if statement starts and stops.
The if/else construct is a close relation of the lone if statement. It adds a block of code that will execute only if the test of the if statement was false. Thus
int i=0; if (i==1){ System.out.println("Good morning"); }else{ System.out.println("Good afternoon"); }
This is an either/or construct. If the value of i is equal to one then "Good morning" is output, if it is not then "Good afternoon" is output.
The final variation on the if construct is else/if. If you have a situation with more than two alternatives you can have an arbitrary number of else ifs before the final else.
if(i==0){ System.out.println("Good morning"); }else if (i==1){ System.out.println("Good afternoon"); }else{ System.out.println("Good night"); }
This is really just an extension of the if/else construct with additional if statements after the else.
Note that whatever is tested between the parenthesis must evaluate to a boolean value. Thus the test in the example if(i==0) is either true or false, it is not a number. This is in contrast to the C/C++ languages (and possibly some others) where there is a convention that an evaluation that returns zero is false and any other value is true.
In C/C++ you can test with syntax such as
int i=1; if(i){ //do something }
In Java an if clause must be a boolean test. Thus you can re-state that example as
if(i==1){ //do something }
Also note that the test is performed with the == operator and not the assignment operator =. Sooner or later everyone tries to compile code with a test like this
if(i=1){ //do something }
This simply assigns the value of 1 to the variable i, rather than testing the condition. Luckily Java will flag this type of error at compile time.