Sitemap
Scott Maitland

Scott Maitland

I am a Glasgow-based Software Engineer. I love all things tech, and I am a big gaming geek.

Java Conditionals & Loops

6 min readJun 17, 2023

--

This article is being written as a way for me to improve and work on my ability to articulate technical knowledge and deepen my understanding of Java.

In programming, conditionals and loops are utilized to make decisions. They can be used for singular events like asking, "Are you tired?", or for repetitive tasks like checking a shopping list for eggs by asking, "Is this item eggs?" for each item. Based on the answer, you would either continue through the list or stop.

Logical Conditions

Java uses logical conditions from mathematics, just like other languages, in order to determine true or false statements. Here is a list of logical conditions you will commonly find:

  • Less than operator <
    -
    10 < 20 is true
    -
    20 < 10 is false
  • Less than or Equal to operator<=
    - 10 <= 20 is true
    - 20 <= 10 is false
  • Greater than operator >
    - 20 > 10 is true
    -
    10 > 20 is false
  • Greater than or Equal to operator >=
    - 20 >= 10 is true
    - 10 >= 20 is false
  • Equal to operator ==
    - 10 == 10 is true
    - 10 == 20 is false
  • Not Equal to operator !=
    - 10 != 20 is true
    -
    10 != 10 is false

Decision Conditions

We can code logical conditions into a program in a manner where we can tell the program to take a different action based on the result of a logical condition check. Let’s take a look at some decision conditions:

  • if — if the condition is true, it will run a specific code block.
int x = 10;
int y = 20;

// An if statement
if(x < y) {
System.out.println(x + " is less than " + y);
}

// Outputs "10 is less than 20!"
  • else — if the condition is false, it will jump to the defined else block and run this, ignoring the first code block.
int x = 40;
int y = 15;

// An else statement
if(x < y) {
System.out.println(x + " is less than " + y);
} else {
System.out.println(y + " is greater than " + x);
}

// Outputs "40 is greater than 15!"
  • else if — if the first condition is false, then it will jump to the defined else if block and run a new condition to test, ignoring the other code blocks.
int x = 40;
int y = 15;

// An else-if statement
if(x < y) {
System.out.println(x + " is less than " + y);
} else if(x > y){
System.out.println(x + " is greater than " + y);
} else {
System.out.println(x + " is equal to " + y);
}

// Outputs "40 is greater than 15!"

We can take a look at a fun example of how The Matrix uses a decision condition in the scene where Morpheus offers Neo a choice between the blue pill and the red pill! 🤯

Morpheus from The Matrix offers Neo the choice

Here is an illustration of a program starting and immediately hitting a decision point that depending on the result, will take the program down one of two paths.

Press enter or click to view image in full size
Neo’s decision in The Matrix is based on making 1 of 2 choices.

The above can be represented in Java, in an if-else statement. Let’s pretend we’re making a text-based game version of the Matrix and we want to know what option the user chose, we could call getDecision() which will check if pillColor is set to blue.

String pillColor = "red";

public void getDecision(){
if(pillColor.equals("blue")){
System.out.println("Ignore is bliss!");
} else {
System.out.println("Buckle your seatbelt Dorothy, because Kansas is going bye-bye!");
}
}

// Outputs "Buckle your seatbelt Dorothy, because Kansas is going bye-bye!"

As we can see in the above code snippet, the `pillColor` variable holds the String value of "red”. Therefore, because the condition pillColor.equals("blue") is false, the program will not execute the block that prints "Ignorance is bliss” . In fact, Java won’t even enter that code block at all and instead immediately jumps to the else block to print "Buckle your seatbelt Dorothy, because Kansas is going bye-bye!"
What pill would you have chosen, huh? 🤨

Cypher from The Matrix

Loops

Looping is very useful in development, it is used as a way of controlling how many times we execute a code block based on a condition. In Java, we have 4 loops available to use:
- For
- For-Each
- While
- Do-while

For loop

This loop is made up of 3 statements to instruct the parameters for how the loop should operate within - for(statement 1, statement 2, statement 3)
- Statement 1 is executed once before the code block is executed
- Statement 2 is defining what the condition is that executes the code block
- Statement 3 is executed after each time the code block is executed

Get Scott Maitland’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s look at a simple loop, where we want to just print “Hello World” 3 times

for(int count=0; count < 3; count++){
System.out.println("Hello World");
}

/* Outputs:
Hello World
Hello World
Hello World
*/

Now that you’ve seen the code for the for loop, let me explain in more detail:
- Statement 1 count i = 0 is starting our count off at 0
- Statement 2 count< 3 is our condition for executing the code block, it checks if on this loop the value stored by count is less than 3.
- Statement 3 count++ is taking the value stored by count and increasing it by 1, which will in turn mean that on the next loop, statement 2’s logical condition check will read as 1 < 3
Once the condition on statement 3 is false (when count reaches 3), the program will no longer execute this loop and move on to the next code section.

For-Each loop

This loop is a loop that can be used with arrays, and it has a simpler syntax than the For loop. The For-Each loop is constructed by giving it what type the array is, a variable name to use within the loop to represent each element, and the array name to loop over. Let’s look at the example of looping over an array of gaming devices.

String[] devices = {"PS5","Xbox Series X","Nintendo Switch","Steam Deck"};

// Let's loop over the array just to print out each elements value
ForEach(String device: devices){
System.out.println(device);
}

/* Outputs:
PS5
Xbox Series X
Nintendo Switch
Steam Deck
*/

What is happening here? behind the scenes, the ForEach loop is iterating through the devicesarray starting at index 0, and updating our temporary String device with whatever String is stored in the element so that when the code block is executed, it’s printing the value stored in device.

While loop

While loops will execute a block of code, as long as a condition holds true, for example, if we wanted to print 0 to 10 we could just give our while loop the condition of count < 10 . Let’s see an example:

int count= 0;
while (count < 10) {
System.out.println(count);
count++;
}

Just as with the other loops, we’ve defined a variable starting at 0, and we tell the code block to increment that count by 1 for each loop, but unlike the other loops the while loop will keep running until the condition is true, whereas the For and ForEach loop executes until the condition is false. Therefore, be aware of creating infinite loops if your condition will never resort to false! While loops can be important however as sometimes we might not know how many iterations we want to perform beforehand, say we are given dynamic data and it is necessary to loop over each element.

Do-while loop

Finally, the do-while loop is almost identical to the while loop, only we define and execute a code block first, then check the condition, the key difference is that even if the condition is true before the do-while is executed, the code block will run at least once before the condition is checked and then the code block would not be executed again.

int count = 10;
do {
count++;
System.out.println("The number is " + count);
}
while (count!= 10);
}

/* Outputs:
The number is 10
*/

I’ve hoped you’ve enjoyed this article, and that it has helped in your understanding of conditionals and loops in Java.

What would you like me to write about next, I’m open to any suggestions :)

--

--