In the short time that I’ve been programming, I’ve found that if-else-if statements and switch statements both are incredibly powerful, but to use they each have situations to which they are most appropriate. If and switch are both control flow statements, as defined by Oracle's tutorials. Next I will go a little more in-depth about if and switch statements.
The If Statement
If statements are the simplest and easiest control flow statements to handle. The block of code after and if statement executes if and only if all the conditions contained in the if clause are met. Writing an if statement is very simple:
if(boolean)
{
//code here executes *if* boolean's value is true
}
Note:
This boolean can be a variable or a method that returns a boolean.
--OR--
if(boolean expression)
{
//code here executes *if* boolean expression is true
}
Also note that if expressions CANNOT be followed by semicolons if the conditional code block they represent is to execute correctly.
There are multiple ways to write code that follows an if-statement. If you only need to execute one line of code under a certain condition, then you do not need to use brackets to surround that code.
boolean isRaining = true; if(isRaining) System.out.print("You'll get wet!"); //Since only one line of code needs executing, I need not use brackets
However, it is good convention to use brackets, as whenever an if statement's code block contains more than two lines of code, brackets become necessary.
What is a boolean expression?
A boolean expression is one that compares two values, and returns either true or false.
Boolean expressions use relational operators, of which there are 6:
> Greater than
< Less than
>= Greater than OR equal to
<= Less than OR equal to
== Equal to
!= NOT equal to
Notice that to test if one number is equal to another, you must use TWO equals signs.
For example, let's say you are comparing two integers, x and y. You may write a program like this:
The result of this program would be:
10 is greater than 4
The Not (!) Operator
Java also offers a powerful negation operator to save programmers time and headache. The not operator, which is the exclamation point (!), turns true to false, and false to true.
Using the not operator is simple: place it before the boolean or boolean expression that is to be negated. See the examples below:
The if statement above can be read, "if it is NOT (!) raining". To think about this a different way, the code block following the if statement will only execute if isRaining is false. This program would not put out anything, as the isRaining is negated from true to false, so the if statement's code does not execute.
int num = 2; if(!(num > 5)) //notice the ! operator BEFORE the boolean expression { System.out.println("Your number is not greater than 5..."); }
For more on conditional, relational, and other operators, click here.
The Else Statement
Along with the use of the if statement comes the else statement. An else statement MUST be preceded by an if statement, and can not contain boolean expressions. Else statements contain blocks of code just like if statements. The block of code that follows an else statement only executes if the boolean or boolean expression of the preceding if statement returns false.
Else statements can also be combined with if statements so that multiple conditions are tested if an initial test returns false. To use if, else-if, and else, generally follow this pattern:
if(boolean expression)
{
//code here executes if boolean expression is true
}
else if(boolean expression)
{
//code here executes if boolean expression is true
//AND the previous boolean expression is false
}
else if(boolean expression)
{
//code here executes if boolean expression is true
//AND the previous boolean expression is false
}
else
{
//This code only executes if none of the previous boolean expressions are true
}
So, to save the computer some thinking, I could rewrite my previous program as such:
By using the above code instead of three separate if statements, the program takes less time to run. This is because the program only checks the else-if statement if the first if statement returns false, and only performs the else statement's code block if the first two if statements are false. Though in this case the time difference is not noticeable, imagine the scope of the difference over a program that spans thousands of lines. That's a pretty big difference.
Also, this is important to note: else statements always go to the nearest if statement that does not already have an else statement attached to it. If there is no such if statement, the compiler will become angry with you, and may explode.
Nesting If Statements
If statements can also contain other if statements, which is called nesting of if statements. Nested if statements are very useful for outlining decision structures. Here is a quick example of nested if statements...
In the above program, there is an if statement inside of an if statement. The program only checks the value of isTooHot if isSunny is true.
Running Multiple Tests
If statements also allow for multiple tests to be performed in one clause. This can be done by using conditional operators. The most common conditional operators are:
&& AND - both conditions must be true
|| OR - at least one of the conditions must be true
^ XOR - ONLY one of the conditions may be true
These operators are placed between the two statements they are meant to evaluate.
If both booleans, isSunny and isRaining are true, then and only then will the print statement execute.boolean isSunny = true; boolean isRaining = true; if(isSunny && isRaining) \\both must be true { System.out.print("Look for a rainbow!"); }
If you use && and || in the same statement without parenthesis, the && statement will be checked first. See the statement below:
true || false && true || false
Java looks at this statement like this:
true || (false && true) || false
So it is reduced...
true || false || false
(true || false) || false
true || false
true
However, you can place parenthesis around tests, much like in math, to change the order in which they will be evaluated.
((true || false) && true) || false
(true && true) || false
true || false
true
XOR (^) is an interesting operator. When placed between two booleans or boolean expressions, it will only return true if one of the boolean expressions is true and the other is false. This is useful for situations when you want a program to continue only if a condition exists, while at the same time excluding the existence of another condition. XOR is not too commonly used. A more lengthy way to write an XOR is as such:
where a and b are booleans,
if(a && !b || b && !a)
is the same as
if(a ^ b)
The Ternary ? Operator
Sometimes when you code an if statement, all you are really wanting to change is a single value. For example, you may check if an integer is less than zero, and set the value of a String to "negative" if it is:
String status; int num = -2; if(num < 0) { status = "negative"; } else { status = "non negative"; }
However, that code is kinda bulky for just a single variable's value being changed. Have no fear, ?: is here! The ternary conditional operator ? allows you to perform boolean evaluations and change the value of a variable by these evaluations. That sentence probably sounds like Charlie Brown's parents, so here's the syntax:
Object o = (booleanExpression ? value_if_true : value_if_false);
So that previous if statement above rewritten would be simply:
String status; int num = -2; status = (num < 0 ? "negative" : "non negative"); //variable = (booleanExpression ? valueTrue : valueFalse);
I have found this ? operator extremely useful for shortening code that would have otherwise been bulky.
The instanceof Keyword
Sometimes you may want to test if an Object is an instance of a certain class. Perhaps you want to class cast an Object to a String, but first you want to make sure that the Object is a String. There is a simple way to do this: the instanceof keyword. The syntax is as follows:
variable instanceof Class
instanceof returns either true or false -- true if the given variable is an instance of the given class, and false otherwise.
Look at the code below:
So, if start (a String) is an instance of the String class (which, obviously, it is), then the value of end will be set as the value of start. Otherwise, end we be set to empty (""). Since start is an instance of String, the output of this program will be "cake".
For more on instance of, see here (toward the middle of the page).
If Summary
If statements allow certain blocks of code to execute only under certain conditions. They can test booleans or boolean expressions, and can even relate multiple booleans and boolean expressions at once using && and ||. Boolean expressions test two values against one another using <, >, <=, >=, ==, and !=. ! is used to negate the value of a boolean or boolean expression. If statements can also be nested within one another when && and || are insufficient.
The ? operator provides a way to shorten if statements that would only change the value of a single variable and do nothing else.
The Switch Statement
If statements are very powerful, but sometimes they can become quite repetitive and annoying to write. Think about a program that performs different actions based on an integer. The code would look something like this:
int num = 3; if(num == 0) { //code } else if(num == 1) { //different code } else if(num == 2) { //even more code } //... and on until, let's say, 5
Obviously, that program would be rather monotonous to write. The switch statement offers an alternative to situations like the above.
Writing a Switch
The switch statement takes one argument that controls the path of execution it will follow. Switch is very useful when you would otherwise be using a list of if statements that all check the value of the same variable. The general syntax of the switch statement is thus:
Note that "variable" used below has many restrictions. Variable can only be an int, short, byte, char, Enum, String, and a few other special classes that wrap the aforementioned such as Character, Byte, Short, and Integer.
Also note that brackets are required in a switch statement.
switch(variable)
{
case value:
//code here
break;
case value:
//code here
break;
default:
//code here
break;
}
I know this is really unclear at the moment; so let's go in depth about each section.
The Control Value
Referred to as "variable" above, the control value of a switch statement does as the name implies: controls which path of execution the switch statement will follow. As noted above, this control value can be any of the primitive data types int, short, byte, or char and can also be done with Strings or Enums. Some classes that wrap the primitive data types mentioned before may also be used to control the switch's execution. These classes include Character, Byte, Short, and Integer.
Important: Strings only work in switch statements since Java 7.
The Cases
A switch statement's possible paths of execution are outlined by its cases. Unsurprisingly, cases must be of the same data type or class as the control value. So, if your control value is an integer, your cases must be too (ie, case 8, case 45). If your control value is a String, your cases must follow suit (case "happy", case "sad").
Cases should be followed by the code that is to execute if the control value is equal to the case value. Blocks of code that follow cases should not be enclosed in brackets. However, after a block of code, the line of code "break;" must be used. Otherwise, the program would continue reading and executing the lines of code that follow, even if they are part of a different case.
The Default Case
It is good convention to also place a "default" case in the body of a switch statement. This is done just like with cases, but instead, you mark the start of the default case with "default:". Default cases are useful it you want to execute certain code when none of the previous cases values are matched by the control value. In fact, the default case does exactly that. If, after checking every single case, a program finds no matches between case values and the control value, it then looks to execute the default case.
An Example
Below is an example of how to use the switch statement.
By using the switch statement, I avoided the monotony of a chunk of if, else-if statements.String weatherCondition = "Cloudy"; switch(weatherCondition.toLowerCase()) { //This can also be thought of as a group of if statements case "sunny": //Or, if(weatherCondition.toLowerCase().equals("sunny")) System.out.println("The sun is out! Hooray!"); break; //Remember the break, this tells the program to stop here! case "cloudy": //Or, if(weatherCondition.toLowerCase().equals("cloudy")) System.out.println("Uh-oh, clouds block the sun! :("); break; //Remember the break, this tells the program to stop here! case "rainy": System.out.println("Better get a jacket, it's wet out!"); break; //Remember the break, this tells the program to stop here! default: //If weatherCondition.toLowerCase() doesn't equal any of the above cases, this executes System.out.println("Aw, snap, I don't know what to say about the current weather!"); break; }
Another Example
Sometimes you may want to create a switch statement that does not use break statements to halt its execution. In other words, maybe your control variable doesn't control which path of execution will be followed, but rather the starting point of execution in a list of code. For this example, let's say I want to find which days come after a given day in a week. I could use a switch statement for this, as such:
ArrayList<String> days = new ArrayList<String>(); String day = "Monday"; switch(day.toLowerCase()) { case "sunday": days.add("Monday"); case "monday": days.add("Tuesday"); case "tuesday": days.add("Wednesday"); case "wednesday": days.add("Thursday"); case "thursday": days.add("Friday"); case "friday": days.add("Saturday"); break; }
What the above does is finds the starting day, then continues executing all the code listed BELOW the case that represents the starting day. So, in the case of this program, the day is "Monday". Therefore, the ArrayList days would have the days "Tuesday", "Wednesday", "Thursday", "Friday", and "Saturday" added to it, because nothing is telling the program to stop executing. This is called letting a switch statement fall through. For a more detailed example of this, see Oracle's tutorials.
Switch Summary
Switch statements offer alternatives to series of if statements that involve different tests upon the same simple variable. The control value of a switch can be int, short, byte, char, Enum, String, and an instance of certain number wrapping classes. Switch statement bodies contain cases that outline the possible paths of execution of the switch based on the value of the control variable. Switch statements should contain default cases that execute code if none of the previous case values are met. Providing an easy way to diverge a program's execution path into a plethora of parts, switch statements can be quite beneficial.
If and Switch: When to use Which
Now that if and switch statements have both been explained, it's time to analyze: which is more appropriate in certain situations?
If and switch seem related to each other in the same manner as while and for. Switch statements work well when critiquing the value of a single variable, and save time and space in these situations, just as for provides a more concise and contained way to write count-controlled loops. Furthermore, switch statements and count-controlled loops fit very well together simply due to the nature of their coding.
Just as while allows for broader test statements, so does if when compared to switch. When dealing with difficult logic that spans a plethora of variables, if statements are the most appropriate. They allow for multiple tests to be performed as well as logical comparisons of these test values. If statements can also be nested to allow for critically defined and logically understandable paths of execution.
So, when deciding which statement you should use, simply ask yourself: can I relate all the possible paths of execution to a single variable? If so, then switch is best, as it saves time and is easy to read. If no, then you need to use if, as switch can only handle conditional situations that rely on a single variable.
Whoo! My first tutorial! I've fact checked with numerous sites and reliable sources (thanks, JavaPF!), so I hope that this information is neither lacking nor incorrect.
Thanks to JavaPF for looking it over, and to newbie for his advice for additions to the tutorial!
If you notice any errors in the content or even a little grammar error, please tell me! Thanks!