Conditions and Comparisons
if (n == 7)
doSomething();
You have already been using conditional statements
(if
statements) and comparisons (e.g. ==
,
<
, …). This section includes some details that you
should keep in mind as you code.
Braces
If you want to do more than one thing, you need to use braces
{ ... }
. The code within the braces runs if the
condition is true.
boolean condition = true;
if (condition)
{
doSomething();
doSomethingElse();
}
In general, braces specify a scope for local variables. Variables declared within a scope cannot be accessed outside of that scope.
Comparison Operators
The comparison operators in Java (==
,
<
, >
, <=
,
>=
, !=
) are binary operators
(they take two input values) that return a boolean value.
if (i%3 == 0)
{
System.out.println("Fizz");
}
Logical Operators
The logical operators &&
and
||
are binary operators that take two boolean values as
input. The logical operator !
is a unary operator that
takes a single boolean value as input. See the next section for more
details on the logical operators.
if-else
chains
You can add as many else if
conditions as you want.
The conditions are checked in order. If there is a final
else
statement, this code is run if none of the other
conditions hold.
if (i%2 == 0)
{
System.out.println("Even");
}
else if (i == 7 || i == 3)
{
System.out.println("Lucky");
}
else
{
System.out.println(i);
}