- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech

Guided: Write Java SE Programs with Variables and Control Flow
Build confidence in writing clear and structured Java programs with this guided lab on variables and control flow. You’ll begin by declaring primitive and non-primitive data types such as byte, short, int, long, float, double, boolean, and String, learning when to use each for efficiency and clarity. Explore conditional logic with if–else statements, nested conditions, and switch to handle decision-making in real-world scenarios like grading scores and validating logins. Practice string formatting and validation using trimming, case conversion, and character checks. Then, dive into iteration with for, while, and do–while loops to process arrays, calculate totals, and repeatedly check user input. By the end of this lab, you’ll be equipped to design Java programs that use variables effectively, apply control flow to guide program behavior, and handle repetitive tasks with confidence and accuracy.

Lab Info
Table of Contents
-
Challenge
Introduction
Welcome to the Guided: Write Java SE Programs with Variables and Control Flow Lab. This hands-on Code Lab is designed for beginner to intermediate Java developers who want to strengthen their understanding of variables, data types, and control flow in Java. You will learn how to declare and use primitive types, apply conditions with
if–else
andswitch
, and work with different types of loops to process numbers and user input.Throughout this lab, you will build small, practical programs step by step, such as calculating totals, formatting names, validating logins, mapping days of the week, and checking odd or even numbers. Each exercise builds on the previous one, giving you practical experience in writing clear, structured, and efficient Java code. ### Key Takeaways:
- Declare and use variables with different primitive data types (
byte
,short
,int
,long
,float
,double
,boolean
) andString
. - Apply program logic using
if–else
statements, nested conditions, andswitch
statements. - Format and validate strings with Java’s built-in methods.
- Use
for
,while
, anddo–while
loops to repeat tasks and process input. ### Prerequisites
Java Knowledge
- Basic familiarity with Java syntax, such as declaring variables, methods, and classes
- Understanding of how to write and run a simple Java program
Tools and Environment Familiarity
- Comfortable using the terminal or command line.
- Experience with a modern code editor such as VS Code, IntelliJ IDEA, or Eclipse
- Ability to compile and run Java programs from the command line using
javac
andjava
### Exercise Files
All the exercise files will be under
src/main/java/org/lab
folder. ### Solutioninfo> The final code for each step is stored in the
__solution/codes
folder. For instance, the final code for Step 2 is available in the__solution/codes/Step02
directory. - Declare and use variables with different primitive data types (
-
Challenge
Working with numbers
In this step, you’ll learn how to use Java’s basic number types (
byte
,short
,int
,long
,float
, anddouble
). These types will let you store and work with numbers of different sizes. You will also practice creating constants withfinal
, and perform basic arithmetic/casting to compute totals and taxes.Explanation -
Java provides several integer types to store whole numbers of different sizes. Choosing the right type helps make programs efficient and prevents errors.
-
byte
: Stores very small numbers from −128 to 127. It is good for small counts, such as the number of teams in a sports tournament (e.g., 12 teams). -
short
: Stores numbers from −32,768 to 32,767. It is good for medium-sized values, such as the number of students in a school (e.g., 1,200 students). -
int
: Stores much larger numbers from −2,147,483,648 to 2,147,483,647. It is the most commonly used integer type and is ideal for calculations. For example, the population of a country (e.g., 27,200,000 people in Australia). -
long
: Stores even larger numbers, up to roughly 9 quintillion. It’s used when you expect extremely large values, such as tracking the distance between planets in meters (e.g., about 149,600,000,000 meters between Earth and the Sun). -
In this task, you used
byte
andshort
for smaller values andint
for the multiplication result. This shows how different data types can be combined effectively.
java src/main/java/org/lab/SportsTournament.java
You should see a response in your terminal as shown in the example response below.
Total players in the tournament: 420 ``` <details> <summary>Explanation</summary> - `double`: Stores fractional numbers and provides a precision of about 15–16 decimal digits. Because of this higher precision, `double` is generally safer and more reliable for most calculations compared to `float`. - `PLAYER_TAX_RATE` is a percentage written as a decimal. The value `0.16` represents 16%. - The calculation `salary * PLAYER_TAX_RATE` is performed in `double` (because one operand is a `double`), so the intermediate result is a decimal number. - Casting with `(int)` converts that decimal to a whole number by truncating the fractional part (removing everything after the decimal point). For example, `15999.84` becomes `15999`. Note that this is truncation, not rounding. - The keyword `final` in `final double PLAYER_TAX_RATE = 0.16;` makes the variable a constant, meaning its value cannot be changed once assigned. - For readability, you can write large numbers using underscores. For example, `int salary = 100_000;` is equivalent to `100000`. </details> Navigate to the **Terminal** and execute the following command to test the above changes.
java src/main/java/org/lab/SportsTournament.java
You should see a response in your terminal as shown in the example response below.
Total players in the tournament: 420 Total tax for the player: 16000
<summary>Explanation</summary> - `float`: Stores fractional numbers and provides a precision of about 6–7 decimal digits. - `CLUB_TAX_RATE` is a constant (`final`) of type `float`. The suffix `f` is required for float literals (`0.16f` means 16%). - `clubRevenue` is a `float` storing the club’s revenue amount (`2450000f`). - The expression `clubRevenue * CLUB_TAX_RATE` is calculated as a `float` because both operands are `float`, and the result is stored in `clubTax`. - Returning `clubTax` provides the computed tax for the club. - In this exercise, `float` is used to represent decimal values. Although `double` provides higher precision (about 16 decimal digits) and is more common in real-world applications, `float` is chosen here because it is simpler and sufficient for learning purposes. For most calculations where accuracy is important, `double` is safer to use. </details> Navigate to the **Terminal** and execute the following command to test the above changes.
java src/main/java/org/lab/SportsTournament.java
You should see a response in your terminal as shown in the example response below.
Total players in the tournament: 420 Total tax for the player: 16000 Total tax for the club: 392000.00
-
-
Challenge
Working with Boolean and Strings
In this step, you will work with String and boolean types in Java. You’ll practice using logical operators to check permissions, format names with string methods, and validate text by splitting and checking conditions.
Explanation boolean
stores a simple true/false value.||
is the logical OR operator. It evaluates totrue
when eitherisAdmin
istrue
orisEditor
istrue
(or both).- Example: Since
isAdmin
istrue
andisEditor
isfalse
,userCanAdd
istrue
. If both arefalse
,userCanAdd
isfalse
.
java src/main/java/org/lab/UserProfile.java
You should see a response in your terminal as shown in the example response below.
Can User Add Authors: true ``` <details> <summary>Explanation</summary> - A `String` variable contains a collection of characters surrounded by double quotes. - In Java, a `String` is actually an object, which means it has built-in methods that can perform certain operations on the text. For example, you can get the length of a string with the `length()` method. - `firstName` and `lastName` are typed as `String` variables. - `trim()` removes leading/trailing spaces so the output doesn’t include unwanted whitespace. - `toUpperCase()` converts the first name to uppercase to match the `LAST, FIRST` style. - String concatenation with `+` assembles the final format: trimmed last name, then `", "`, then the processed first name. For the given inputs, the final output is `HARDY, TOM`. </details> Navigate to the **Terminal** and execute the following command to test the above changes.
java src/main/java/org/lab/UserProfile.java
You should see a response in your terminal as shown in the example response below.
Can User Add Authors: true Display name: HARDY, TOM
<summary>Explanation</summary> - `char` stores a single character, such as a letter or symbol. Characters are written inside single quotes, like `'A'` or `'b'`. - In Java, a `String` is an object, which means it has built-in methods to perform operations on text. - `String[] parts = displayName.split(",", 2);` splits the display name into two parts at the first comma: last name and first name. The limit of `2` ensures it only splits once. - `String lastName = parts[0].trim();` takes the last name (the first part) and removes any extra spaces at the beginning or end. - `char lastNameInitial = Character.toLowerCase(lastName.charAt(0));` gets the first letter of the last name and converts it to lowercase for easier comparison. - `boolean hasValidLength = lastName.length() >= 2;` checks that the last name has at least two characters. - `boolean hasValidLastName = lastNameInitial == 'h';` verifies that the last name starts with the letter `h`. - `return hasValidLength && hasValidLastName;` returns `true` only if both conditions are satisfied. </details> Navigate to the **Terminal** and execute the following command to test the above changes.
java src/main/java/org/lab/UserProfile.java
You should see a response in your terminal as shown in the example response below.
Can User Add Authors: true Display name: HARDY, TOM Is valid Last Name: true ``` Congratulations! You’ve successfully learned how to use
boolean
variables with logical operators, format names using string methods liketrim()
andtoUpperCase()
, and validate text by splitting and checking conditions. These techniques will help you handle both logic and string processing effectively in your Java programs. -
Challenge
Working with if–else and switch
In this step, you will learn how to make decisions in Java programs using control flow statements. You’ll practice using
if–else
statements (including nested ones), a series ofif–else
statements for checking multiple ranges, andswitch–case
statements for working with many fixed values.Explanation if
statements let your program make decisions. The condition inside theif
must be eithertrue
orfalse
.- Use
if
when you want some code to run only if the condition is true. - Use
else
when you want other code to run if the condition is false. - Use
else if
when you want to check another condition after the first one is false.
- Use
equals()
: The method compares two strings and returns true if the strings are equal and false if not.==
would be incorrect for string comparison.- The outer if-else first validates the username by comparing
inputUser
withcorrectUser
variable. If the username is wrong, theresponse
is set toIncorrect username
and skips the password check, which keeps the logic simple. - The nested if-else validates the password by comparing
inputPass
withcorrectPass
variable. If the password is correct, theresponse
is set toLogin successful
else, the response is set toIncorrect password
.
java src/main/java/org/lab/StudentRecords.java
You should see a response in your terminal as shown in the example response below.
Login successful ``` <details> <summary>Explanation</summary> - `String response = "";` starts with an empty string to hold either the grade or the validation message. - The condition `if (score < 0 || score > 100)` validates the input. If the score is outside the valid range, it sets the message and skips the rest of the checks. - The if–else ladder is ordered from highest to lowest, ensuring that the score matches the first correct range it fits. - `"A"` is assigned for scores 90 and above, `"B"` for 80–89, `"C"` for 70–79, `"D"` for 60–69, and `"F"` for anything below 60. - `return response;` makes sure the method returns either the validation message or the appropriate grade. </details> Navigate to the **Terminal** and execute the following command to test the above changes.
java src/main/java/org/lab/StudentRecords.java
You should see a response in your terminal as shown in the example response below.
Login successful Grade of the student is: C
<summary>Explanation</summary> - The `switch` statement allows you to choose one block of code to run from many options: - The `switch` expression is evaluated once. - Its value is compared with each `case`. - If there is a match, the corresponding block of code runs. - The `break` statement stops the switch after the matching case has finished. - The `default` statement runs if no case matches. - `String response = "";` initialises a variable that will hold the day name or an error message. - The `switch (day)` selects a branch based on the numeric day input. Each `case` sets `response` to the correct day name. - A `break` is used after each case, so only the matching case runs and then exits the switch. - The `default` case covers numbers outside 1–7 and sets `response` to `"Invalid Day"`. - A `switch` is mostly used when you want to compare one variable against many constant values, making the code easier to read than multiple if–else statements. - `return response;` returns the final result to the caller. </details> Navigate to the **Terminal** and execute the following command to test the above changes.
java src/main/java/org/lab/Calendar.java
You should see a response in your terminal as shown in the example response below.
The name of the day is : Monday
-
Challenge
Working with loops
In this step, you will practice using different types of loops in Java to repeat tasks. You’ll use a
for
loop to calculate the sum of numbers in an array, awhile
loop to achieve the same result with manual control of the counter, and ado–while
loop to continuously check if numbers are odd or even until the user decides to stop.Explanation -
Loops allow you to run a block of code repeatedly while a specified condition is true. They are useful because they save time, minimize errors, and make code easier to read and maintain.
-
int sum = 0;
starts a variable to keep track of the total. -
The
for (int i = 0; i < nums.length; i++)
loop goes through each index of thenums
array. -
Inside the loop,
sum += nums[i];
adds the current array element to the total. This meanssum
keeps adding each number in the array. -
When the loop is done,
return sum;
sends back the total of all numbers in the array. -
A
for
loop is useful here because you know exactly how many elements you need to go through — the length of the array. -
A
for
loop evaluates its condition before each iteration (including the first). If it’s false initially, the body won’t run at all.
java src/main/java/org/lab/NumbersLoop.java
You should see a response in your terminal as shown in the example response below.
The sum of the numbers is : 27 ``` <details> <summary>Explanation</summary> - A `while` loop keeps running a block of code for as long as the given condition remains true. - `int sum = 0;` starts with a variable to hold the running total. - `int i = 0;` sets up a counter to track the current position in the array. - `while (i < nums.length)` repeats the loop until `i` reaches the size of the array. - Inside the loop, `sum += nums[i];` adds the current element to the total. - After that, `i++;` increases the counter so the loop moves to the next element. - Once the loop is finished, `return sum;` sends back the total sum of all numbers in the array. - A `while` loop is useful when you want to keep looping until a condition becomes false, and you manage the counter yourself. - A `while` loop always checks for the condition before executing the block. </details> Navigate to the **Terminal** and execute the following command to test the above changes.
java src/main/java/org/lab/NumbersLoop.java
You should see a response in your terminal as shown in the example response below.
The sum of the numbers is : 27 The sum of the numbers by using while loop is : 27
<summary>Explanation</summary> - A `do...while` loop is a variation of the `while` loop. It always executes the block of code once before checking the condition, and then continues repeating as long as the condition remains true. - `int number = 0;` initializes a variable to store the user’s input. - The `do { ... } while (number != -1);` loop ensures that the code inside runs at least once before checking the condition. - The loop continues as long as the entered number is not `-1`. Entering `-1` stops the program. - Inside the loop: - `System.out.print(...)` shows the instruction message to the user. - `number = scanner.nextInt();` reads the number entered by the user. - `showOddEven(number);` calls a method that prints whether the number is odd or even. </details> Navigate to the **Terminal** and execute the following command to test the above changes.
java src/main/java/org/lab/OddEvenCheck.java
Enter the number as per the prompt and you should see a response in your terminal as shown in the example response below.
Enter a number greater than or equal to 0 (enter -1 to stop):7 7 is odd. Enter a number greater than or equal to 0 (enter -1 to stop):2 2 is even. Enter a number greater than or equal to 0 (enter -1 to stop):-1 Program ended. ``` Great work! You’ve now learned how to use
for
,while
, anddo–while
loops. You used them to calculate sums and repeatedly check user input for odd or even numbers.Congratulations! You’ve successfully completed the lab.
-
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.