Sometimes you will need to have more complex conditions to determine what you need. This goes beyond having Boolean logic, but moves into finding a value in a series of values. This is where we might use a if else if
series of code blocks, or a switch
statement.
If Else If
Do you have a situation where you want to have multiple blocks run, depending upon what value your variable is? Well, you would use a series of if statements. But that means once you find the correct condition, you still have to keep on checking each potential condition. That might cause multiple true blocks to run. Consider the code below, and see if you can find the (potential logic error).
int age = 35;
if(age < 0) {
// how could this be????
}
if( age > 13) {
// now you're a teenage, right?
}
if( age > 18) {
// good news... you're and adult. right?
}
if( age > 21) {
// are you and adult now...?
}
if(age > 99) {
// what about now?
} else {
// could I be true with others, but not here, and this run inadvertently? yes!
}
Of course, you can use some boolean logic in here to make sure only one test is true, but that takes extra time. Consider the following code, and how it simplifies things by stopping testing once a condition is met.
int age = 35;
if(age < 0) {
// how could this be????
} else if( age > 99) {
// what about now?
} else if( age > 21) {
// are you and adult now...?
} else if( age > 18) {
// good news... you're and adult. right?
} else if(age > 13) {
// now you're a teenage, right?
} else {
// what age block is in here?
}
Notice, that it does take some work to rearrange the logic, but it is still a viable option, and much faster to run, especially if it is being run against a large set of data.
Switch Statement
Of course, if you want to speed things up, the switch statement might be the best option. Of course, it has similar limitations, like the switch statement in C/C++. That is, you must look for exact matches, but it might be a good option, especially if you have more than just a few if-else if blocks to code – all of which are looking for an exact match.
int jobCode = 10;
switch (jobCode) {
case 1:
// do stuff for when jobCode is 1
break;
case 2:
// do stuff for when jobCode is 2
break;
// continue on for all your exact matches for the job code
default:
// what do we do if there wasn't a match?
}
Notice that you have to use a break at the end of each case, otherwise you continue to do what is after the case that you matched.
More Complex Conditions in Java was originally found on Access 2 Learn