Java Operators and Control Statements

Vahe Aslanyan
23 min readJan 4, 2024

--

Operators are vital, engaged in over 70% of code logic decisions, while control statements dictate the flow, essential in around 85% of Java applications.

This chapter will explore the pivotal role these elements play in crafting algorithms and object-oriented programs, ensuring you can create well-structured and effective Java code.

Resources

If you’re keen on furthering your Java knowledge, here’s a guide to help you conquer Java and launch your coding career. It’s perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  1. Java Data Structures Mastery — Ace the Coding Interview: A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  2. Foundations of Java Data Structures — Your Coding Catalyst: Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech’s website for these resources and more information on the bootcamp.

Connect with Me:

Arithmetic operators

At the heart of most programming tasks are operators. They dictate the flow and logic within algorithms, helping computers make decisions, process data, and deliver results.

Specifically, arithmetic operators are foundational pillars that offer essential functionalities, allowing us to execute complex operations seamlessly. These tools, although ubiquitous, sometimes go unnoticed in their daily use. Yet, their understanding is vital for anyone aspiring to code proficiently.

Basic Arithmetic Operators

Addition (+): More than a mere counting mechanism, the addition operator is indispensable in aggregation tasks. Whether you’re summing up totals or calculating a grand sum, + remains at the core.

int sum = 3 + 4;  // sum holds value 7

Subtraction (-): An unsung hero when it comes to pinpointing differences or making alterations. It can be vital when budgeting, calculating time differences, or even tracking inventory changes.

int diff = 10 - 3;  // diff holds value 7

Multiplication (*): While it can represent repeated addition, its true prowess lies in scaling and proportionate increase. From calculating areas to understanding growth, multiplication is pivotal.

int product = 7 * 3;  // product is 21

Division (/): A tool often used to partition values. Whether distributing resources, calculating ratios, or determining average values, division serves as a crucial operation.

double quotient = 20.0 / 3;  // quotient is approximately 6.67

Modulus (%): Moving past just division, modulus allows for the understanding of remainders. It’s paramount in cyclical operations and certain algorithms like those dealing with circular arrays.

int remainder = 7 % 3;  // remainder is 1

Unary Operators

  • Increment (++): A succinct way to enhance a value. It’s particularly beneficial in loop counters and iterative processes.
  • Prefix: By using ++a, the value of 'a' is increased before the current operation gets executed.
  • Postfix: With a++, the current operation utilizes 'a' before increasing its value.
  • Decrement ( — ): Serving as the inverse of increment, it methodically diminishes a value, commonly used in reverse iterations and counters.
  • As with increment, prefix and postfix nuances apply to the decrement operator as well.

Compound Assignment Operators

These operators infuse arithmetic operations with assignment. They offer concise code, improving its readability while ensuring efficiency.

int x = 10;
x += 5; // An elegant way of saying x = x + 5; x now holds 15

The Importance of Data Types

The behavior of arithmetic operations can vary depending on the data types employed.

Floating-point arithmetic: While it affords precision, you need to remain vigilant about rounding errors or floating-point anomalies.

double result = 10.0 / 3;  // result holds 3.3333...

Integer arithmetic: It delivers whole numbers, eschewing any decimal fractions. Ideal for countable entities but can lead to unintended truncations.

int resultInt = 10 / 3;  // resultInt holds 3, the fraction is discarded

Be wary of integer divisions, ensuring that you choose the correct data type based on the computational context.

Type Promotion in Expressions

Java strives to avoid accidental data loss by promoting data types in mixed-type operations. For example, an operation involving an int and a double will convert the int to a double to ensure a uniform type for accurate computation.

Mathematical Methods & Classes

Java’s Math class is a reservoir of handy mathematical utilities.

Math.pow(a, b) efficiently computes 'a' raised to the power of 'b'.

double eight = Math.pow(2, 3);  // eight holds 8.0

Math.sqrt(x) returns the square root of 'x', a common function in distance calculations and quadratic algorithms.

double squareRoot = Math.sqrt(64);  // squareRoot holds 8.0

These methods magnify Java’s computational prowess, taking away the need for manually crafting these algorithms.

Practical Scenarios & Examples

For instance, consider you’re managing a shop and need to calculate the total cost after adding a service charge:

int totalCost = 50;
totalCost += 25; // Compound assignment, totalCost is now 75

Or, perhaps you’re developing a geometry application and need to calculate the diagonal length of a square:

double sideLength = 8.0;
double diagonal = sideLength * Math.sqrt(2); // Using Math class for square root

Relational operators

Relational operators, also known as comparison operators, serve as the cornerstone in the world of decision-making for developers. They pave the way for crafting conditional statements, driving loops, and orchestrating the flow in algorithms by determining the truth value of specific conditions.

Java boasts a collection of relational operators that serve the purpose of comparing two values. At their core, these operators yield a boolean outcome — either true or false:

Equality (==): This operator states whether two values share parity.

int a = 5;
boolean result = (a == 5); // The outcome stored in 'result' is true

Inequality (!=): As the counter to equality, it checks if two values aren’t the same.

int b = 7;
boolean result = (b != 5); // Here, 'result' is true since 7 isn't 5

Greater Than (>): It evaluates if the value on the left is greater than the one on the right.

boolean check = (10 > 3);  // 'check' is true, 10 does surpass 3

Less Than (<): This operator checks if the value on the left is smaller than the one on the right.

boolean check = (2 < 8);  // As expected, 'check' is true here

Greater Than or Equal to (>=): A dual-purpose operator, it confirms if the left value either is greater than or equal to the right.

boolean equalityOrGreater = (7 >= 7);  // This yields true since 7 equals 7

Less Than or Equal to (<=): Similarly dual-purposed, it verifies if the left value is less than or equal to the right.

boolean equalityOrLess = (4 <= 5);  // 'equalityOrLess' will store true

Relational Operators and Object References

Distinguishing between primitive data types and objects is vital in Java, especially when employing the == operator.

With primitive data types, == straightforwardly checks whether values are equal.

For objects, the == operator delves deeper, determining if both references point to an identical memory location. It doesn't evaluate content equality. Instead, you'll use the equals() method for that purpose.

String str1 = new String("Hello");
String str2 = new String("Hello");
boolean refCheck = (str1 == str2); // This returns false; distinct memory locations
boolean contentCheck = str1.equals(str2); // True here since the content is identical

Chaining Relational Operators

Using various relational and logical operators together can produce intricate conditions:

int age = 25;
boolean isAdult = (age >= 18 && age <= 65); // 'isAdult' stands true for ages 18 through 65

But there are some potential pitfalls you should be aware of:

Floating-point Comparisons: Precision errors can distort direct floating-point comparisons using relational operators. To sidestep this, consider comparing the absolute difference against a minuscule threshold.

double result = 0.1 + 0.2;
boolean isEqual = (result == 0.3); // False here due to precision glitches
boolean isNearlyEqual = Math.abs(result - 0.3) < 0.000001; // True since the difference is minuscule

Auto-boxing Hazards: The quirk of auto-boxing in Java can spawn unexpected results when comparing wrapper objects:

Integer num1 = 127;
Integer num2 = 127;
boolean check1 = (num1 == num2); // True here due to integer caching within the range of -128 to 127
Integer num3 = 200;
Integer num4 = 200;
boolean check2 = (num3 == num4); // This turns out false; they're different references

Practical scenarios and applications:

  • Sorting Algorithms: Algorithms like Bubble Sort or Quick Sort lean on relational operators to determine the sequential order of elements.
  • Decision-making in Applications: If an application is evaluating loan eligibility predicated on age and income, or sifting data in accordance with user specifications, you’ll find relational operators at work.
  • Gaming: Be it adjudging victors based on score metrics or launching events post certain milestones, relational operators sculpt the gaming narrative.

Exercises & Challenges

  • Basic Exercises: Task yourself with architecting conditions that sort grades (A, B, C, and so forth) anchored on scored marks.
  • Intermediate Challenges: Take a stab at designing a rudimentary high-score tracker for any game.
  • Advanced Puzzles: Venture into implementing the binary search algorithm. It predominantly hinges on relational operators to pinpoint elements.

An Advanced Program: Efficient Filtering System:

public class FilterSystem {
    // Mock database entries
private static final String[] DATABASE = {
"Product A: Price $100, Category Electronics",
"Product B: Price $50, Category Books",
"Product C: Price $150, Category Electronics",
"Product D: Price $30, Category Apparel",
// ... more entries
};
public static void filterByPriceRange(int min, int max) {
for (String entry : DATABASE) {
String[] splitEntry = entry.split(" ");
int price = Integer.parseInt(splitEntry[3].substring(1)); // Extract price
if (price >= min && price <= max) {
System.out.println(entry);
}
}
}
public static void main(String[] args) {
filterByPriceRange(50, 150); // Filters entries with prices between $50 and $150
}
}

Logical operators

Before diving deeper into object oriented programming, it’s important to understand logical operators. They serve as tools for establishing truth values of expressions. And combined with relational operators they allow more complex conditions to be created.

Fundamental Logical Operators

Java offers a suite of logical operators to help you evaluate and combine boolean expressions:

  • Logical AND (&&): Returns true if both operands are true.
boolean result = (5 > 3) && (7 < 10);  // result is true
  • Logical OR (||): Returns true if at least one of the operands is true.
boolean result = (5 < 3) || (7 < 10);  // result is true
  • Logical NOT (!): Inverts the truth value of the operand.
boolean result = !(5 > 3);  // result is fals

Short-Circuit Behavior in Java

Java supports short-circuit evaluation for its logical operators. This means:

  • For &&, if the left operand is false, the right operand is not evaluated.
  • For ||, if the left operand is true, the right operand is not evaluated.

This behavior is not only efficient but can also be useful in avoiding potential runtime errors:

String str = null;
if (str != null && !str.isEmpty()) {
System.out.println("String is not empty");
} else {
System.out.println("String is empty or null");
}

In the above example, using the && operator ensures that str.isEmpty() is only called if str is not null, avoiding a potential NullPointerException.

Logical Operators with Non-Boolean Values

While Java’s logical operators primarily work with boolean values, bitwise logical operators can be used with integers:

  • Bitwise AND (&)
int result = 5 & 3;  // result is 1
  • Bitwise OR (|)
int result = 5 | 3;  // result is 7
  • Bitwise XOR (^): Returns 1 for differing bits and 0 for matching bits.
int result = 5 ^ 3;  // result is 6

Remember, these operators work on the individual bits of integers.

Truth Tables: Deciphering Logical Operations

Understanding logical operations becomes more intuitive with truth tables. They map all possible truth values of inputs to their resulting outputs.

AND (&&)

ABA && BTTTTFFFTFFFF

OR (||)

ABA || BTTTTFTFTTFFF

NOT (!)

A!ATFFT

Practical Applications of Logical Operators

  • User Input Validation: By combining multiple conditions, you can rigorously validate user inputs.
int age = 25;
boolean hasLicense = true;
if (age >= 18 && hasLicense) {
System.out.println("Allowed to drive");
} else {
System.out.println("Not allowed to drive");
}
  • Game Development: Crafting game logic, like determining if a player has met all conditions to progress to the next level.
  • Security: Evaluating multiple conditions to grant or deny access.

Exercises & Challenges — Solutions

Basic Exercise:

Problem: Given three boolean variables a, b, and c. Determine if only one of them is true.

Solution: The idea is to use the OR (||) operator to check if any one of the variables is true and then ensure that not more than one of them is true.

boolean a = ... // Assign some value
boolean b = ... // Assign some value
boolean c = ... // Assign some value
// Begin the conditional check
if (
// The following conditions are checking each scenario where only one variable is true:
(a && !b && !c) // First condition: 'a' is true AND 'b' is false AND 'c' is false
||
(!a && b && !c) // Second condition: 'a' is false AND 'b' is true AND 'c' is false
||
(!a && !b && c) // Third condition: 'a' is false AND 'b' is false AND 'c' is true
) {
// If any of the above conditions is met, only one of the variables is true
System.out.println("Only one of the variables is true.");
} else {
// If none of the above conditions is met, either all are false, all are true, or two are true.
System.out.println("Either none or more than one of the variables is true.");
}

Intermediate Challenge:

Problem: Implement a basic “AND” gate simulator using only the “NOT” and “OR” operators.

Solution: Recall the logical identity (A AND B) = NOT(NOT A OR NOT B). Using this, we can simulate an AND gate with NOT and OR operators.

// Declare and initialize a boolean variable for Input A
boolean A = ...; // Replace '...' with the actual value or method of retrieval
// Declare and initialize a boolean variable for Input B
boolean B = ...; // Replace '...' with the actual value or method of retrieval
// Calculate the "AND" operation using only the "NOT" and "OR" operators:
// The expression '!A || !B' will be true if either 'A' is false OR 'B' is false.
// Thus, by using '!', we are essentially checking if BOTH 'A' and 'B' are true.
boolean ANDResult = !( !A || !B );
// Print out the result of the "AND" operation
System.out.println("AND Result: " + ANDResult);

Advanced Puzzle:

Problem: Design a system that takes a sequence of binary inputs and outputs their logical AND, OR, and XOR results.

Solution: The idea is to loop through the binary sequence and maintain running AND, OR, and XOR results.

// Declare an integer array 'binaryInput' containing a sequence of binary values (0s and 1s).
// This serves as our sample input.
int[] binaryInput = {1, 0, 1, 0, 1};
// Start by initializing the results (AND, OR, XOR) with the first value in the binary sequence.
// This will serve as a starting point for our calculations.
int ANDResult = binaryInput[0]; // Start with the first binary value for AND
int ORResult = binaryInput[0]; // Start with the first binary value for OR
int XORResult = binaryInput[0]; // Start with the first binary value for XOR
// Use a loop to iterate over the binaryInput array starting from the second element (index 1).
for (int i = 1; i < binaryInput.length; i++) {
// For each binary value, update the ANDResult by performing a logical AND operation
// between the current ANDResult and the current binary value.
ANDResult &= binaryInput[i];

// Similarly, update the ORResult by performing a logical OR operation
// between the current ORResult and the current binary value.
ORResult |= binaryInput[i];

// For XORResult, perform a logical XOR operation
// between the current XORResult and the current binary value.
// XOR will return 1 only if the two compared bits are different.
XORResult ^= binaryInput[i];
}
// After processing all the binary values, print out the results:
System.out.println("Logical AND Result: " + ANDResult); // Shows the result of logical AND operation
System.out.println("Logical OR Result: " + ORResult); // Shows the result of logical OR operation
System.out.println("Logical XOR Result: " + XORResult); // Shows the result of logical XOR operation

Note: This solution assumes a binary sequence using integers 1 and 0. The same logic applies if you were using a boolean array.

Control Statements in Java — if, else, switch

Control statements, the core of any programming language’s decision-making capabilities, are indispensable when guiding how a program behaves under various scenarios. Consider them your program’s “brain,” making decisions on its behalf according to certain inputs or conditions.

In Java’s vast world of program execution, control statements offer dynamic ways of controlling program flow. In this chapter we will examine three primary ones: if, else and switch.

The if Statement

Every decision-making process starts with a question. The if statement in Java serves as this question. It evaluates a given condition: if the condition holds true, it proceeds to execute a specified block of code.

Syntax:

if (condition) {
// Block of code to be executed if the condition is true
}

Example:

Let’s consider voting as an example. The basic criteria to vote in many countries is age. If an individual is 18 or older, they are allowed to vote.

int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}

In this example, since 20 is greater than 18, the program will output: “You are eligible to vote.”

The if-else Statement

Life is full of choices. Similarly, in programming, there are often two paths to take: one if a condition is met and another if it isn’t. The if-else statement in Java caters to this type of situation.

Syntax:

if (condition) {
// Block of code executed if condition is true
} else {
// Block of code executed if condition is false
}

Example:

Continuing with our voting example:

int age = 15;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}

Here, since 15 is less than 18, our program will print: “You are not eligible to vote.”

The if-else-if Ladder

What if there are multiple conditions to check? That’s where the if-else-if ladder comes in handy. It allows the program to evaluate a series of conditions in sequence.

Syntax:

if (condition1) {
// Executed if condition1 is true
} else if (condition2) {
// Executed if condition2 is true
} else {
// Executed if none of the above conditions hold true
}

Example:

Suppose we’re categorizing grades:

int marks = 75;
if (marks >= 85) {
System.out.println("Grade A");
} else if (marks >= 70) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}

Given the marks are 75, the program will output: “Grade B”.

The switch Statement

When dealing with scenarios where a variable could equate to multiple known values, and each value requires different processing, the switch statement is your tool of choice.

Syntax:

switch (expression) {
case value1:
// Code executed for value1
break;
case value2:
// Code executed for value2
break;
// You can have any number of case statements
default:
// Code executed if none of the cases are met
}

Example:

For instance, consider a simple day tracker:

int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Another day");
}

Given the day is set to 2, our program will announce that it’s “Tuesday”.

Cautionary Note: The break keyword ensures that once a match is found and its corresponding block of code is executed, the program exits the switch block. Omitting it could lead to unintended results as the program "falls through" to subsequent case blocks.

Nested Control Statements

Just like inception, control statements can exist within other control statements. This ability lets developers sculpt intricate logical constructs for detailed decision-making.

Example:

Consider an eligibility check for driving:

int age = 20;
boolean hasDrivingLicense = true;
if (age >= 18) {
if (hasDrivingLicense) {
System.out.println("You can drive a car.");
} else {
System.out.println("You are eligible, but you need a driving license.");
}
} else {
System.out.println("You are not eligible to drive.");
}

Practical Scenarios & Applications

  • User Input Validation: Using control statements, you can ensure that the input given by the user follows specific criteria. For instance, checking if a user-entered password meets minimum length and contains required characters:
String password = userInput(); // This is a hypothetical function to get user input
if (password.length() >= 8 && password.contains("@")) {
System.out.println("Password is strong.");
} else {
System.out.println("Password does not meet criteria.");
}
  • Menu Systems: Especially in console-based applications, users often choose from a list of options. A switch statement makes implementing this seamless.
int choice = getUserChoice(); // Hypothetical function
switch(choice) {
case 1:
showProfile();
break;
case 2:
editSettings();
break;
default:
System.out.println("Invalid choice.");
}
  • Gaming Logic: Control statements are important in games. They can determine game outcomes based on player decisions, check winning conditions, or evolve game narratives.

Exercises & Challenges

Basic Exercise: Basic Calculator

Craft a basic calculator that can execute operations like addition, subtraction, multiplication, and division grounded on user preference using switch statements.

import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user for input
System.out.println("Enter first number:");
double num1 = scanner.nextDouble();
System.out.println("Enter second number:");
double num2 = scanner.nextDouble();
System.out.println("Choose operation (+, -, *, /):");
char operation = scanner.next().charAt(0);
// Switch case for calculator operations
switch (operation) {
case '+':
System.out.println("Result: " + (num1 + num2));
break;
case '-':
System.out.println("Result: " + (num1 - num2));
break;
case '*':
System.out.println("Result: " + (num1 * num2));
break;
case '/':
if (num2 != 0) { // Avoid division by zero
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Cannot divide by zero!");
}
break;
default:
System.out.println("Invalid operation chosen.");
}
scanner.close();
}
}

Intermediate Challenge: Traffic Light System

Construct a rudimentary traffic light system. Given a color (Red, Yellow, Green), your program should display corresponding messages, like “Stop” for Red.

import java.util.Scanner;
public class TrafficLightSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user for traffic light color
System.out.println("Enter traffic light color (Red, Yellow, Green):");
String color = scanner.nextLine().trim().toLowerCase();
// Switch case for traffic light messages
switch (color) {
case "red":
System.out.println("Stop");
break;
case "yellow":
System.out.println("Prepare to stop");
break;
case "green":
System.out.println("Go");
break;
default:
System.out.println("Invalid color entered.");
}
scanner.close();
}
}

Advanced Puzzle: Student Grade Classification:

Develop a program that classifies student grades (A, B, C, and so forth) relying on given score intervals using the if-else-if ladder.

import java.util.Scanner;
public class GradeClassification {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user for student score
System.out.println("Enter student score (0-100):");
int score = scanner.nextInt();
// Grade classification using if-else-if ladder
if (score >= 90 && score <= 100) {
System.out.println("Grade A");
} else if (score >= 80 && score < 90) {
System.out.println("Grade B");
} else if (score >= 70 && score < 80) {
System.out.println("Grade C");
} else if (score >= 60 && score < 70) {
System.out.println("Grade D");
} else if (score >= 0 && score < 60) {
System.out.println("Grade F");
} else {
System.out.println("Invalid score entered.");
}
scanner.close();
}
}

Loops: for, while, do-while in Java – Navigating Repetition

Loops form the cornerstone of many algorithms and routine tasks in Java. Their primary function is to repeat a block of code multiple times, driven by specific conditions.

This section offers a deep dive into the core loop constructs available in Java: the for, while, and do-while loops.

The for Loop

The for loop provides a concise way to iterate over a range of values or elements in a collection. It's typically used when the number of iterations is known beforehand.

Syntax:

for (initialization; condition; increment/decrement) {
// Block of code to be repeated
}

Example:

To print numbers from 1 to 5:

for (int i = 1; i <= 5; i++) {
System.out.println(i);
}

Points to Remember:

  • Initialization: Sets a starting point for the loop.
  • Condition: If this evaluates to true, the loop continues – otherwise, it stops.
  • Increment/Decrement: Modifies the loop variable after each iteration.

The while Loop

The while loop repeatedly executes a block of code as long as a specified condition evaluates to true.

Syntax:

while (condition) {
// Block of code to be repeated
}

Example:

To print numbers from 1 to 5:

int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}

Points to Remember:

Ensure the condition in a while loop eventually becomes false. Otherwise, you’ll have an infinite loop.

The do-while Loop

Similar to the while loop, but with a critical difference: the do-while loop checks its condition after the loop has executed, guaranteeing the loop's body will run at least once.

Syntax:

do {
// Block of code to be repeated
} while (condition);

Example:

Prompting user input until a valid number is received:

int number;
do {
System.out.println("Enter a number between 1 and 10:");
number = scanner.nextInt();
} while (number < 1 || number > 10);

Points to Remember:

Use the do-while loop when the loop's body must execute at least once, regardless of the condition's initial state.

Enhanced for-loop (for-each)

Introduced in Java 5, the enhanced for loop simplifies iterating over collections and arrays.

Syntax:

for (Type variable : collection/array) {
// Block of code
}

Example:

Printing all elements in an array:

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}

Points to Remember:

The enhanced for loop is read-only. This means that you cannot modify the current element during iteration.

Loop Control Statements

  • break: Exits the current loop immediately.
  • continue: Skips the rest of the current iteration and proceeds to the next iteration.

Example:

Print numbers from 1 to 10 but skip 5:

for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}

Practical Scenarios & Applications:

Iterating Over Large Data Sets: In data-driven applications, large datasets (like those in databases, files, or even arrays/lists) often need to be processed. Loops make it feasible to traverse each data element sequentially, applying operations like transformation, computation, or simply extraction.

Example: Imagine you have a list of 10,000 employees, and you want to calculate the average salary:

double totalSalary = 0;
int numberOfEmployees = employeesList.size();
for (Employee emp : employeesList) {
totalSalary += emp.getSalary();
}
double averageSalary = totalSalary / numberOfEmployees;
System.out.println("Average Salary: " + averageSalary);

Game Loops Where the Game State is Repeatedly Updated: Most video games operate on a continuous loop, known as the “game loop.” Within this loop, user inputs are processed, game state and physics are updated, and visuals are rendered. This loop runs numerous times per second.

Example: A basic game loop might look like this:

while (gameIsRunning) {
processUserInputs(); // e.g., move character, jump, etc.
updateGameState(); // e.g., move non-player characters, update scores, etc.
renderGraphics(); // draw the current state of the game on the screen
delay(16); // a simple way to aim for ~60 frames per second
}

User Input Validation: When taking inputs from users, there’s no guarantee they’ll provide valid data. Loops can be used to repeatedly prompt users until valid input is received.

Example: A program asking the user for a number between 1 and 100 might use a loop like this:

int userInput;
do {
System.out.println("Enter a number between 1 and 100:");
userInput = scanner.nextInt();
} while (userInput < 1 || userInput > 100);

Searching and Sorting Algorithms: Searching and sorting are fundamental operations in computer science, and both heavily depend on loops. Whether it’s a simple linear search or a complex merge sort, loops are integral.

Examples:

Linear Search: To search for a value in an array:

int[] numbers = {10, 20, 30, 40, 50};
int valueToFind = 30;
boolean found = false;
for (int num : numbers) {
if (num == valueToFind) {
found = true;
break;
}
}
if (found) {
System.out.println(valueToFind + " was found in the array.");
} else {
System.out.println(valueToFind + " was not found in the array.");
}

Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order:

int[] numbers = {64, 34, 25, 12, 22, 11, 90};
int n = numbers.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (numbers[j] > numbers[j+1]) {
// swap numbers[j] and numbers[j+1]
int temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
}
}
}

By understanding these practical applications of loops, you’ll gain a clearer insight into their utility and indispensability in various programming scenarios.

Exercises & Challenges:

Programming is a journey of solving real-world problems by translating them into a language that computers can understand.

While theory provides us with the tools, it’s through hands-on problem-solving that we truly internalize the essence of programming. The exercises that follow are designed to take you through such hands-on experiences.

Basic Exercise: Fibonacci Numbers Using a While Loop

The Fibonacci sequence is a series of numbers where a number is the sum of the two preceding ones, starting from 0 and 1. This sequence has a rich historical context and can be found in many parts of nature, from the spirals of galaxies to shells to the pattern of leaves.

The challenge here is to use the while loop, a control structure that keeps executing its block until a specified condition is met, to generate this intriguing sequence.

public class FibonacciWhileLoop {
public static void main(String[] args) {
int n = 10; // Number of Fibonacci numbers to print
int t1 = 0, t2 = 1;
        int count = 1;  // To keep track of how many numbers have been printed        // Print the first two Fibonacci numbers
System.out.print("First " + n + " Fibonacci numbers: " + t1 + ", " + t2);
// Use a while loop to calculate the rest of the numbers
while (count <= n - 2) {
int sum = t1 + t2;
System.out.print(", " + sum);
t1 = t2;
t2 = sum;
count++;
}
}
}

Intermediate Challenge: Menu-Driven Program

A common application in software development is the creation of menu-driven programs. These are interactive programs that allow users to choose from a list of options, leading them through different functionalities of an application.

Using the do-while loop, we aim to design a basic structure for such a program. The loop ensures that the menu is presented to the user until they decide to exit, allowing for repeated interactions.

import java.util.Scanner;
public class MenuDrivenProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Start with a do-while loop to keep showing the menu until the user chooses to exit
int choice;
do {
// Print out the menu
System.out.println("\\nMenu:");
System.out.println("1. Calculator");
System.out.println("2. Conversion Tools");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt(); switch (choice) {
case 1:
System.out.println("Calculator chosen!");
// Implement the calculator here...
break;
case 2:
System.out.println("Conversion tools chosen!");
// Implement conversion tools here...
break;
case 3:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice! Please select from the menu.");
break;
}
} while (choice != 3); // Exit when user chooses 3
scanner.close();
}
}

Advanced Puzzle: FizzBuzz Using a For Loop

FizzBuzz is a classic programming puzzle, often used in interviews to gauge a candidate’s understanding of logic and control structures. The problem might seem simple but is quite effective at illustrating the concept of condition-based execution.

Using the for loop, a control structure that iterates over a sequence, we'll implement this popular challenge.

public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) { // Looping through numbers 1 to 100
// If number is divisible by 3 and 5, print "FizzBuzz"
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
}
// If number is divisible by 3, print "Fizz"
else if (i % 3 == 0) {
System.out.println("Fizz");
}
// If number is divisible by 5, print "Buzz"
else if (i % 5 == 0) {
System.out.println("Buzz");
}
// If number is not divisible by either 3 or 5, print the number
else {
System.out.println(i);
}
}
}
}

Resources

If you’re keen on furthering your Java knowledge, here’s a guide to help you conquer Java and launch your coding career. It’s perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  1. Java Data Structures Mastery — Ace the Coding Interview: A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  2. Foundations of Java Data Structures — Your Coding Catalyst: Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech’s website for these resources and more information on the bootcamp.

Connect with Me:

--

--

Vahe Aslanyan
Vahe Aslanyan

Written by Vahe Aslanyan

Studying Computer Science and experienced with top tech firms, I co-founded LunarTech to revolutionize data science education. Join us for excellence.

No responses yet