Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

Java: Use Simple If Statements

A conditional statement in a Java application begins with a condition and ends with a task. You use conditional statements every day. Another example of a conditional statement is, “Choose the item that most closely matches your age from this list for your prize.”

Programs can use that sort of conditional statement too! The main purpose of this chapter is to show you how to write conditional statements in a way that the computer understands, but from a logical perspective, you already know everything required to use conditional statements.

Computers rely heavily on math used to express an idea to make certain decisions. Consequently, the condition part of a conditional statement is also called an expression. An expression always equates to a value of true or false, so it’s a Boolean value.

However, when you think about it, you use Boolean expressions in your daily conversation. For example, “If the item costs less than $5.00, then I’ll buy it.” The condition — item costs less than $5.00 — is a Boolean expression.

The if statement is the easiest of the conditional statements to understand and you’ll find that you use it often. An if statement consists of a condition that looks like this:

if (expression)

where expression is the condition that you want to check. The task associated with the if statement appears within curly braces like this:

{
   Tasks you want to perform...
}

Every if statement follows the same pattern of condition followed by task. With this pattern in mind, in the following example you create an application that relies on an if statement to make a decision about a number that you type.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.