JAVA: Conditions



Basic Conditions

The keyword ‘if’ signifies a conditional statement in java. A condition in java can be written as a simple if or as an if/else statement.

A simple if statement provides a section of code that will run ONLY when the condition is true. Here is an example testing if a user has won a scholarship.
System.out.println("Welcome to our site.");
if(scholarship.equals("yes")){
	System.out.println("Congratulations, you have won a scholarship.");
}
System.out.println("Please feel free to navigate our site for information about paying for college.");
In this example, ALL viewers will see the output from lines 1 and 5. However, only users with a scholarship value of "yes" will see the output from line 3. This line is conditional, only output when the boolean expression in the parenthesis of the if statement evaluates to true.

Note that in line(2), there is no semi-colon at the end of the line AND that the conditional code is contained in a set of curly {} braces.
An if/else statement provide two conditional paths - one to be executed when the boolean expression is true and another for when it is false. Here is an example that checks a string to see if it is equal to “password”:
System.out.print("Enter your password:");
String input=reader.nextLine();
if(input.equals("password"))
	System.out.println("Welcome!!");
else
	System.out.println("Sorry, your password is incorrect!");
In this example, ALL users will see the prompt to enter their password. If they enter the correct password, they will see a Welcome message, otherwise they will see the Sorry message.

A few things to note here:
  • There are no curly braces. This is because each of the conditional sections of code is only one line. In this type of situation, the curly braces are optional. However, if either section had more than one line of conditional code, they would have to be contained in curly braces.
  • Still no semi-colon after the condition
  • The else portion of the code does not have a condition or parenthesis. This is because it is connected to the if statement. The if statement has a condition. When that expression is true, the if code runs; when it is false, the else code runs.

Nested Conditions

Sometimes, a more complex system of conditions is necessary. Nested conditions are when a condition is placed in another condition, either inside the if block or in the else block. Here is an example that checks to see if a senior has met their Government class requirement:
if(grade==12){
	if(govmt>=60)
		System.out.println("Gov Req. Met");
	else
		System.out.println("Need to re-take Gov.");
}
else{
	System.out.println("Make sure you take gov. before you graduate.");
}
See that in this example, there is a full if/else statement inside the if portion of another if/else statement. Any valid code is allowed to be written inside a condition, including other conditions. The code about the grade being >=60 will ONLY execute if the student is in 12th grade. Otherwise, control shifts directly to line(7) and 8
This type of nesting can go very deep, depending on the desired options for the user. Often times, when nesting in the else block, we find that we are generating a list of mutually-exclusive events (events where one or the other, but not both can occur). When this is the case, we use an else-if chain:
if(score>=9)
	letter=’A’;
else if(score>=8)
	letter=’B’;
else if(score>=7)
	letter=’C’;
else if(score>=6)
	letter=’D’;
else
	letter=’F’;
In this example, our options are mutually exclusive - it is not possible for a student to get an 8 AND a 9 at the same time. They can only get one or the other. So, we can use an else-if chain - a shorthand of nested conditions.

Don't be confused thinking that there are conditions with the else statements. Notice that everywhere there is a condition, there is an if statement as well.

Finally, the final else is the catch-all. If none of the conditions evaluate to true, then the final else will catch all other inputs and assign a value of 'F';

Switch Statements

An alternative to nesting conditionals is a structure called a switch statement. A switch statement takes an integer or character (you cannot run switch statements on any other type of variable in Java) variable and allows for different cases, or options, for the value of the variable. There is also a default case that "catches" any values not specified in a case. The general form of a switch is:
switch(variable)
{
	case ___: <code for case>; break;    //__is replaced by an int or 'char' value
	case ___: <code for case>; 
	case ___: <code for case>; break;
	default:     <code for default>;
}
In this example, the variable is a pre-defined int or char value in the program. Each case then checks it's value against the variable (running == in the background). If the case value matches the variable value, the code for that case executes. You can write as many lines of code in each case as desired. The break statement in each case signals the end of the code for that case.

Absence of a break statement can bee seen in line (4). In a situation like this, if the case in line(4) catches, all of the code for that case AND all of the code for the case in line(5) will execute. In other words, controls "falls into" the next case and continues until it finds a break statement.

The default case is always at the end and is the "catch-all" like the else at the end of an else if chain. Since there are no other cases following the default, a break is not needed.
Below, you will find a full code example of a switch statement that is the equivalent code of the previous example in the nested conditions section. This code also shows the use of break statement (as well as their absence). Here is an example that assigns a letter grade based on a score out of 10:
switch(score/3)
{
	case 10:
	case 9: letterGrade='A';     
		break;
	case 8: letterGrade='B';
		break;
	case 7: letterGrade='C';
		break;
	case 6: letterGrade='D';
		break;
	case 5:
	case 4:
	case 3:
	case 2:
	case 1:
	case 0: letterGrade='F';      
		break;
	default: System.out.println(\"Not a valid score\");
}
In this example, you will see first that the score is divided by 3. This is because the quiz being graded was out of 30. Instead of writing 30 different cases, we can uses Java's integer division (remember an int divided by an int results in an int) to generate a score out of 10.

You can see the absence of code and break in line(3). So, if the value of the score variable is 10, control will enter the structure at case 10:. No code will execute there, but control will "fall into" case 9 due to the lack of break. Thus, a value of 10 will be evaluated as an A. The break in case 9 will then transfer control out of the switch statement.

The same type of control fall happens with lines(12-16), as all of those values count as an F.

The default at the end catches any values not included in the switch and lets the user know that their input was not valid.