AP Notes, Outlines, Study Guides, Vocabulary, Practice Exams and more!

Java Lesson 4 - Variables

Jul 18, 2009

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
}
}
}

Need Help?

We hope your visit has been a productive one. If you're having any problems, or would like to give some feedback, we'd love to hear from you.

For general help, questions, and suggestions, try our dedicated support forums.

If you need to contact the Course-Notes.Org web experience team, please use our contact form.

Need Notes?

While we strive to provide the most comprehensive notes for as many high school textbooks as possible, there are certainly going to be some that we miss. Drop us a note and let us know which textbooks you need. Be sure to include which edition of the textbook you are using! If we see enough demand, we'll do whatever we can to get those notes up on the site for you!