Java Lesson 4 – Conditionals
Now that we can store things, it may be useful to be able to have our program make decisions. Having statements that make decisions is called conditionals, or under certain conditions. Here is the general look for a conditional statement.
if( condition to test )
{
actions to take if condition is true
}
When your program comes across a conditional, it will test the condition. Conditions usually test the contents of variables. If the condition is right, the code inside the block is executed. If the condition is not met, the program will skip the code block and resume the program. This functionality is incredibly useful for a lot of things. For example, you could test a player’s score to see if it’s higher than the top score. If it happens to be true, then a new score is on the list. Here’s an example.
public class Conditionals
{
public static void main(String[] args)
{
int age = 19;
if(age >= 18)
{
buy a lotto ticket
}
}
}
You can have multiple tests in one set of conditions. The program will check each condition in order until it finds one that has been met. Once that code has been executed, all other conditions will be ignored. You can also include an else at the end as an all else fails thing. If placed at the end of a set, if all other conditions have not been met, the code inside the else block will automatically start. Here’s another example.
public class ConditionalsTwo
{
public static void main(String[] args)
{
int age = 13;
if(age >= 21)
{
allow into bar
}
else if(age >= 18)
{
don’t allow into bar, but allow into smoking section
}
else
{
place in non-smoking section
}
}
}