Conditions

A condition is simply asking a true or false question. In Java, the variable type that holds a true or false value is called a boolean.

To compare two values, there are a few important operators:

  • a == b evaluates to true if a and b have the same value. If a and b are objects, this will only be true if they both contain the address to the same instance.
  • a < b evaluates to true if a is greater than b
  • a <= b evaluates to true if a is greater than or equal to b
  • a > b evaluates to true if a is less than b
  • a >= b evaluates to true if a is less than or equal to b

If you want to combine multiple comparisons, there are three main operators:

  • a && b evaluates to true if both a and b are true
  • a || b evaluates to true if either a or b are true

To invert a boolean, use the ! (not) operator. !a is true if a is false and vice versa.

Perhaps the most common use cases of conditions is the if statement. The code inside the brackets following the statement only gets executed if the condition evaluates to true.

if (<condition>) {
	<code>
}

Optionally, you can add an else statement after an if statement to run code if the condition was not true.

if (<condition>) {
	<code that runs if condition is true>
} else {
	<code that runs if condition is false>
}

Additionally, you can combine multiple if and else statements to check multiple conditions. Only the code under the first true statement will run.

if (<condition 1>) {
	<code>
} else if (<condition 2>) {
	<code>
} else if (<condition 3>) {
	<code>
} else {
	<code>
}

Finally, if you are combining multiple if and else statements but only checking if a variable is == to a value, a switch statement is a cleaner way to represent these checks:

switch (<variable>) {
	case <value 1>:
		<code>
		break;
	case <value 2>:
		<code>
		break;
	default:
		// Runs if no other cases were matched
		<code>
		break;
}

Loops

Sometimes, you want some code to run on repeat a certain amount of times or until a certain condition is met.

If you want to run code a certain amount of times, a for loop is ideal.

for (<counter variable>; <condition>; <loop update>) {
	<code>
}

The most common version of this is when you want to run a loop n times.

for (int i = 0; i < n; i++) {
	<code>
}

In this example, i starts at 0 and is incremented by 1 (i++) each loop until i is no longer smaller than n. This results in n iterations of the code.

If you are unsure how many iterations to run the code, use a while loop. Here, it runs the code until the condition is false.

while (<condition>) {
	<code> 
}

With a while loop especially, be careful that the loop will always finish. Otherwise, the code will not continue past the loop.

To stop a loop early, use the break keyword.

while (<condition>) {
	if (<early exit condition>) {
		break;
	}
}