Java Programming Day 4

HimanshiHimanshi
21 min read

Day 4: Deep Dive into Java Conditionals, Logical Operators & Loops — Step-by-Step Practice and Programs


1️⃣ WeatherConditionChecker — Logical Operators with User Input


What This Program Does

  • Takes two inputs from the user: temperature and whether it’s sunny.

  • Checks if temperature is between 0°C and 30°C and if it’s sunny or not.

  • Prints messages about the weather based on these conditions.


Why This Program Is Important

Understanding how to combine multiple conditions with logical operators (&&, ||, !) is fundamental in programming. It helps you build programs that can make complex decisions just like humans do.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;  // Import Scanner class for input

public class WeatherConditionChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);  // Create Scanner object to read input

        System.out.print("Enter the temperature: ");  // Ask user for temperature
        double temp = scanner.nextDouble();  // Read the temperature as a decimal (e.g., 25.5)

        System.out.print("Is it sunny? (true/false): ");  // Ask if it’s sunny
        boolean isSunny = scanner.nextBoolean();  // Read boolean input (true or false)

        // Check if temperature is between 0 and 30 AND it is sunny
        if (temp <= 30 && temp >= 0 && isSunny) {
            System.out.println("The weather is good.");  // First message if all true
            System.out.println("It is Sunny outside.");  // Second message for sunny
        } 
        // Else if temperature is in range but NOT sunny
        else if (temp <= 30 && temp >= 0 && !isSunny) {
            System.out.println("The weather is good.");  // Weather still good
            System.out.println("It is Cloudy outside.");  // Different message for cloudy
        } 
        // Else if temperature outside 0-30 range (either below 0 or above 30)
        else if (temp > 30 || temp < 0) {
            System.out.println("The weather is bad.");  // Weather is bad here
        }

        scanner.close();  // Close Scanner to free resources
    }
}

Line-by-Line Breakdown

  • import java.util.Scanner;: This allows us to read input from the keyboard.

  • Scanner scanner = new Scanner(System.in);: Creates a Scanner object named scanner to read user input.

  • System.out.print("Enter the temperature: ");: Prints prompt without a newline.

  • double temp = scanner.nextDouble();: Reads the next decimal number typed by the user and stores in temp.

  • System.out.print("Is it sunny? (true/false): ");: Asks user for sunny info.

  • boolean isSunny = scanner.nextBoolean();: Reads boolean input (true or false).

  • if (temp <= 30 && temp >= 0 && isSunny): Checks if temp between 0 and 30 inclusive AND it’s sunny.

  • System.out.println("The weather is good.");: Prints “weather good” message.

  • System.out.println("It is Sunny outside.");: Prints “sunny” message.

  • else if (temp <= 30 && temp >= 0 && !isSunny): Checks if temp in range but NOT sunny (! means NOT).

  • else if (temp > 30 || temp < 0): Checks if temp outside range (above 30 or below 0).

  • scanner.close();: Closes the scanner object to free system resources.


Why These Conditions?

  • && (AND) ensures all conditions must be true to execute the block.

  • || (OR) means if any condition is true, execute that block.

  • ! negates boolean (true becomes false and vice versa).


Important Notes & Practical Tips

  • Always close your Scanner when done to prevent resource leaks.

  • Input for scanner.nextBoolean() must be exactly true or false, or it will throw an exception.

  • Logical operators are the backbone of decision making in programming.

  • Make sure you understand the precedence: ! > && > || (NOT has higher priority than AND, which has higher priority than OR).


Quick Quiz for Yourself

  • What happens if the temperature is 25 and user inputs false for sunny?

  • Why can’t we just use one if condition without else if here?

  • How would you modify the program to also consider rain or snow?


2️⃣ UsernameValidator — String Validation Using Conditions


What This Program Does

  • Takes username input from the user.

  • Checks if username is between 4 and 12 characters.

  • Checks if username contains spaces or underscores, which are not allowed.

  • If valid, welcomes the user; otherwise, shows error messages.


Why This Program Is Important

Validating user input is essential for security and data integrity. This example shows how to check string length and substring presence.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class UsernameValidator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your username: ");
        String username = scanner.nextLine();  // Reads entire line as username

        // Check username length outside valid range
        if (username.length() < 4 || username.length() > 12) {
            System.out.println("Username must be between 4-12 characters.");
        } 
        // Check if username contains spaces or underscores
        else if (username.contains(" ") || username.contains("_")) {
            System.out.println("Username must not contain any whitespaces or underscores.");
        } 
        // Username passes all checks
        else {
            System.out.println("WELCOME " + username);
        }

        scanner.close();
    }
}

Line-by-Line Breakdown

  • String username = scanner.nextLine();: Reads full user input including spaces until Enter is pressed.

  • username.length(): Returns how many characters the username has.

  • username.contains(" "): Checks if username has any space.

  • username.contains("_"): Checks if username has underscores.

  • Logical OR || means if either condition is true, username is invalid.

  • The last else is executed only if all previous conditions fail.


Why Use These Checks?

  • Length limits protect from overly short or long usernames.

  • Spaces and underscores might not be allowed in your username rules.

  • Using string methods keeps validation simple and readable.


Important Notes & Practical Tips

  • You can chain multiple validation rules easily with logical operators.

  • For more complex validation, consider regular expressions (regex).

  • User feedback should be clear — tell users exactly what’s wrong.


Quick Quiz

  • What happens if username is “abc”?

  • How would you allow underscores but not spaces?

  • Can .contains() check for multiple characters or patterns? (Hint: No, for complex pattern use regex)


3️⃣ NamePromptWhile — Looping Until Non-Empty Input


What This Program Does

  • Continuously prompts the user for their name.

  • Doesn’t proceed until the user enters something (non-empty input).


Why This Program Is Important

Sometimes you need mandatory input — you must force the user to enter valid data before moving on.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class NamePromptWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = "";  // Start with empty string

        // While the name is empty, keep asking for input
        while (name.isEmpty()) {
            System.out.print("Enter your name: ");
            name = scanner.nextLine();  // Reads user input
        }

        System.out.println("Hello " + name);  // Greet the user

        scanner.close();
    }
}

Why Does This Work?

  • name.isEmpty() returns true if string length is zero.

  • Loop keeps running as long as user enters an empty string.

  • When user enters any character(s), .isEmpty() returns false and loop exits.


Important Notes

  • Using .isEmpty() is safer than checking name == "" because string equality uses .equals() in Java.

  • You can use .trim() if you want to avoid inputs with only spaces.

  • Always validate input before processing.

Quick Quiz

  • How would you reject input with only spaces?

  • What would happen if you forgot to update name inside the loop?

  • How is while different from do-while?


4️⃣ GameQuitLoop — User-Controlled Loop Exit with While Loop


What This Program Does

  • Keeps asking the user to press Q to quit a game.

  • The loop continues until the user enters Q (case-insensitive).

  • Prints a message when the user exits the game.


Why This Program Is Important

User-controlled loops are very common. Here, we learn to:

  • Accept string input.

  • Normalize user input (case-insensitive comparison).

  • Use a loop that depends on user input to terminate.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class GameQuitLoop {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String response = "";  // Initialize empty string for user input

        // Loop keeps running as long as response is NOT "Q"
        while (!response.equals("Q")) {
            System.out.print("You are in a Game!! Press Q to quit: ");
            response = scanner.nextLine().toUpperCase();  // Convert input to uppercase
        }

        System.out.println("You have exited the game!!");  // Exit message

        scanner.close();
    }
}

Line-by-Line Explanation

  • String response = "";: Initialize response to empty, so loop starts.

  • while (!response.equals("Q")): Loop continues while response is not exactly "Q".

  • scanner.nextLine().toUpperCase(): Reads full user input and converts it to uppercase so input is case-insensitive (q or Q both accepted).

  • When the user inputs "Q", !response.equals("Q") becomes false and loop stops.

  • Then program prints exit message and closes scanner.


Important Concepts

  • .equals() is used to compare strings in Java, not ==.

  • .toUpperCase() helps us avoid writing multiple checks for both "q" and "Q".

  • Using ! (NOT) operator negates the boolean condition — this is common in loops waiting for a specific exit input.


Practical Tips

  • For better UX, consider trimming input before converting case: scanner.nextLine().trim().toUpperCase()

  • If you want to accept multiple commands to quit, you can use OR (||) in the while condition.

  • Always prompt the user clearly about how to exit the loop.


Quick Quiz

  • What happens if the user enters just Enter without any letter?

  • How would you modify the code to also accept lowercase 'q' without toUpperCase()?

  • Why can’t we use response == "Q" in Java to compare strings?


5️⃣ AgeValidationWhile — Input Validation with While Loop


What This Program Does

  • Asks the user to input their age.

  • If the age entered is negative, it keeps asking again until a valid (non-negative) age is entered.

  • Finally, prints the valid age.


Why This Program Is Important

Input validation is essential for reliable programs. This example shows how to force the user to provide valid numeric input.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class AgeValidationWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age;

        System.out.print("Enter your age: ");
        age = scanner.nextInt();  // Read initial age input

        // If age is negative, ask repeatedly until valid input
        while (age < 0) {
            System.out.print("Your age can't be negative!!! Enter your age again: ");
            age = scanner.nextInt();
        }

        System.out.println("You are " + age + " years old.");

        scanner.close();
    }
}

Line-by-Line Explanation

  • int age;: Declare variable for user age.

  • age = scanner.nextInt();: Read integer input.

  • while (age < 0): Check if age is negative, if so repeat block.

  • Inside loop, prompt again and read new input.

  • When age is zero or positive, loop exits and program continues.

  • Print valid age.


Important Concepts

  • while loops check the condition before running the loop body.

  • This ensures that the input is validated before proceeding.

  • Prevents illogical data like negative ages.


Practical Tips

  • If you want to be super safe, handle exceptions when user inputs non-integers (try-catch blocks).

  • Add a maximum age limit if needed (like age > 120).

  • Always provide clear instructions for re-entering invalid data.


Quick Quiz

  • What happens if the user enters a negative number twice?

  • How can you ensure the program doesn’t crash if user inputs a letter instead of a number?

  • How would you validate the age to be between 0 and 120?


6️⃣ AgeValidationDoWhile — Input Validation with Do-While Loop


What This Program Does

  • Same as the previous one: ensures user enters a valid age (non-negative).

  • But uses a do-while loop, which executes the input prompt at least once before checking.


Why This Program Is Important

do-while loops are great when you want the code inside the loop to run at least once, even if the condition is false initially.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class AgeValidationDoWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age;

        do {
            System.out.print("Enter your age: ");
            age = scanner.nextInt();

            if (age < 0) {
                System.out.println("Your age can't be negative!!!");
            }
        } while (age < 0);  // Repeat if age is invalid

        System.out.println("You are " + age + " years old.");

        scanner.close();
    }
}

Line-by-Line Explanation

  • do { ... } while(condition);: Loop body runs first, then condition is checked.

  • Prompts for age and reads input.

  • If age < 0, prints error message.

  • Loop repeats until user enters a valid age.

  • After loop, prints valid age.


Differences from Previous Program

  • while loop checks condition before running.

  • do-while guarantees prompt runs at least once — useful for mandatory input scenarios.


Practical Tips

  • do-while is perfect for menu-driven programs where the menu must show before user chooses.

  • This style avoids duplicating input prompt outside and inside the loop.


Quick Quiz

  • What if user enters valid age first time? Does do-while still work correctly?

  • How is the user experience different with do-while vs while?

  • Can do-while loops cause infinite loops? How to avoid that?


7️⃣ NumberRangeWhile — Validating Input in a Range Using While Loop


What This Program Does

  • Forces user to input a number between 1 and 10.

  • If input is outside this range, keeps asking until valid.


Why This Program Is Important

Range checking is common, e.g., for menu choices or numeric input.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class NumberRangeWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = 0;  // Initialize with invalid value

        // Continue looping while number is less than 1 or greater than 10
        while (number < 1 || number > 10) {
            System.out.print("Enter a number between 1-10: ");
            number = scanner.nextInt();
        }

        System.out.println("You hit " + number);

        scanner.close();
    }
}

Line-by-Line Explanation

  • int number = 0; starts with invalid value to enter loop.

  • while (number < 1 || number > 10): condition is true if number out of range.

  • Prompt user each time inside loop.

  • Once valid number entered, loop ends.

  • Print confirmation.


Important Concepts

  • Use || (OR) for range checking: number must be inside boundaries.

  • Loop ensures user cannot proceed without valid input.


Practical Tips

  • Use clear messages to inform the user of valid input range.

  • Consider input type safety (handle non-integers).

  • Combine with try-catch for robust input handling.


Quick Quiz

  • What happens if user inputs 0?

  • How would you change this program to accept only even numbers between 2 and 20?

  • What is the difference between && and || in this context?


8️⃣ NumberRangeDoWhile — Range Validation with Do-While Loop


What This Program Does

  • Same as previous program but uses do-while.

  • Ensures the prompt appears at least once.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class NumberRangeDoWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number;

        do {
            System.out.print("Enter a number between 1-10: ");
            number = scanner.nextInt();
        } while (number < 1 || number > 10);  // Repeat if out of range

        System.out.println("You picked " + number);

        scanner.close();
    }
}

Line-by-Line Explanation

  • The do block runs first and prompts for input.

  • After input, the condition checks if number is invalid.

  • If invalid, loops again; else, proceeds.


Why Use do-while?

When you want the prompt to show before validation — guarantees prompt always shows.


Practical Tips

  • Use this pattern when initial user input is mandatory.

  • Helps reduce code duplication (vs. prompting outside and inside while).


Quick Quiz

  • Can this program accept zero?

  • How is this program behaviorally different from the while loop version?

  • What happens if the user inputs non-integer?

9️⃣ NumberGuessingGame — Interactive Number Guessing with Random Numbers & Feedback


What This Program Does

  • Generates a random number between 1 and 100.

  • Lets the user guess the number repeatedly.

  • Gives feedback whether guess is too low or too high.

  • Counts the number of attempts until the correct guess.

  • Congratulates the user on success.


Why This Program Is Important

This program combines:

  • Random number generation.

  • User input with validation.

  • Control flow using do-while loop.

  • Conditional feedback to guide user.

  • Counting attempts to track progress.

It's a classic beginner's project demonstrating many core programming concepts.


Detailed Code Explanation

javaCopyEditimport java.util.Random;
import java.util.Scanner;

public class NumberGuessingGame {
    public static void main(String[] args) {
        Random random = new Random();  // For generating random numbers
        Scanner scanner = new Scanner(System.in);

        int guess;
        int attempts = 0;
        int min = 1;
        int max = 100;

        int randomNumber = random.nextInt(min, max + 1);  // Generates 1 to 100 inclusive

        System.out.println("Welcome to the Number Guessing Game!");
        System.out.printf("Guess a number between %d - %d:\n", min, max);

        do {
            System.out.print("Enter a guess: ");
            guess = scanner.nextInt();
            attempts++;  // Increase attempt count

            if (guess < randomNumber) {
                System.out.println("Too low! Try again.");
            } else if (guess > randomNumber) {
                System.out.println("Too high! Try again.");
            } else {
                System.out.println("Correct!!! The number was " + randomNumber);
                System.out.println("Number of attempts: " + attempts);
            }
        } while (guess != randomNumber);

        System.out.println("Congratulations!!! You guessed the right number!!!");

        scanner.close();
    }
}

Line-by-Line Explanation

  • Random random = new Random(); sets up random number generator.

  • random.nextInt(min, max + 1) generates number between min and max inclusive.

  • attempts keeps track of user guesses.

  • do-while loop continues until guess matches random number.

  • Inside loop, user inputs guess, attempts increment, and feedback prints.

  • When correct, prints success message and number of tries.

  • Closes scanner to avoid resource leak.


Important Concepts

  • Random number generation with nextInt(int origin, int bound).

  • do-while loop for guaranteed initial input prompt.

  • Conditional checks (if-else) give helpful hints.

  • Tracking variables (attempts) enhance user experience.


Practical Tips

  • Handle invalid inputs (e.g., numbers out of range or non-integers) for better UX.

  • Add option to quit anytime or reveal the number after certain tries.

  • You could improve by making it multiplayer or time-limited.


Quick Quiz

  • Why use do-while instead of while here?

  • What happens if the user inputs 0 or 101?

  • How would you modify the program to allow hints like “within 10 of the number”?


🔟 ForLoopCounter — Counting with For Loop & User-Defined Range


What This Program Does

  • Asks the user for a number.

  • Counts from 1 up to that number.

  • Prints each number on a new line.


Why This Program Is Important

This is a simple but essential exercise to understand:

  • How for loops work.

  • Loop initialization, condition, and increment.

  • Taking user input to control loop behavior.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class ForLoopCounter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter how many times you want to loop: ");
        int max = scanner.nextInt();  // User input controls loop count

        for (int i = 1; i <= max; i++) {  // Loop from 1 to max
            System.out.println(i);
        }

        scanner.close();
    }
}

Line-by-Line Explanation

  • User inputs max for upper limit.

  • for loop starts with i = 1.

  • Continues looping as long as i <= max.

  • i++ increments i by 1 each iteration.

  • Prints i each loop.

  • When i exceeds max, loop ends.


Important Concepts

  • for loops combine initialization, condition, and update in one line.

  • Using user input in loops adds flexibility.

  • Counting from 1 is common; can be changed to 0 or any start.


Practical Tips

  • Validate user input to ensure max > 0.

  • You can change loop to count down by modifying init, condition, and update.

  • Use loops for repetitive tasks and generating sequences.


Quick Quiz

  • What happens if user inputs 0 or a negative number?

  • How to modify this to print only even numbers between 1 and max?

  • What if you want to print numbers backwards?


1️⃣1️⃣ CountdownTimer — For Loop with Delay and Countdown Display


What This Program Does

  • Asks user how many seconds to count down from.

  • Prints the countdown numbers one per second.

  • After reaching zero, prints a celebratory message.


Why This Program Is Important

This program teaches:

  • Using for loops to count backward.

  • Delaying program execution (Thread.sleep).

  • Exception handling with throws InterruptedException.

  • Combining user input with timing control.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class CountdownTimer {
    public static void main(String[] args) throws InterruptedException {
        Scanner scanner = new Scanner(System.in);

        System.out.print("How many seconds to countdown from?: ");
        int start = scanner.nextInt();

        // Loop counts down from start to 0
        for (int i = start; i >= 0; i--) {
            System.out.println(i);
            Thread.sleep(1000);  // Pause 1 second (1000 ms)
        }

        System.out.println("Happy New Year!!");

        scanner.close();
    }
}

Line-by-Line Explanation

  • throws InterruptedException needed because Thread.sleep() can be interrupted.

  • for loop starts at user input value and decrements i until zero.

  • Thread.sleep(1000) pauses execution for 1 second to simulate real-time countdown.

  • After loop ends, prints celebration message.


Important Concepts

  • Using loops to control timing events.

  • Handling checked exceptions (InterruptedException).

  • Real-world applications: timers, clocks, delays.


Practical Tips

  • Validate user input (non-negative seconds).

  • Use try-catch block for better exception handling.

  • Can be expanded to trigger events at zero.


Quick Quiz

  • What if the user inputs a negative number?

  • What happens if the program is interrupted during sleep?

  • How to change delay to half a second?


1️⃣2️⃣ BreakContinueDemo — Controlling Loop Flow with break and continue


What This Program Does

  • Demonstrates two important loop control statements: break and continue.

  • First loop stops printing numbers when it reaches 5 (break).

  • Second loop skips printing number 5 but continues the rest (continue).


Why This Program Is Important

Understanding break and continue lets you:

  • Exit loops early when a condition is met.

  • Skip specific iterations without exiting the loop.

  • Control loops with fine granularity.


Detailed Code Explanation

javaCopyEditpublic class BreakContinueDemo {
    public static void main(String[] args) {

        System.out.println("Using break:");
        for (int i = 0; i <= 10; i++) {
            if (i == 5) {
                break;  // Exit loop immediately when i is 5
            }
            System.out.print(i + " ");
        }
        System.out.println("\n");

        System.out.println("Using continue:");
        for (int j = 0; j <= 10; j++) {
            if (j == 5) {
                continue;  // Skip printing 5, continue next iteration
            }
            System.out.print(j + " ");
        }
    }
}

Line-by-Line Explanation

  • First loop: prints 0 to 4, then breaks at 5, ending loop early.

  • Second loop: skips printing 5 but prints all other numbers.

  • break completely exits the loop.

  • continue skips current iteration only.


Important Concepts

  • Use break to exit loops prematurely.

  • Use continue to skip specific iterations.

  • Helps avoid nested if-statements and improve readability.


Practical Tips

  • Use break carefully in nested loops.

  • Avoid infinite loops with proper break conditions.

  • continue is useful when filtering items in loops.


Quick Quiz

  • What happens if you remove break?

  • Can continue be used with while loops?

  • How would you skip all even numbers using continue?


1️⃣3️⃣ NestedLoopsDemo — Nested For Loops to Print Patterns


What This Program Does

  • Uses nested loops to print three rows.

  • Each row contains nine copies of the row number.

  • Resulting in a 3x9 block of numbers.


Why This Program Is Important

Nested loops are vital for:

  • Working with multi-dimensional data.

  • Printing tables, patterns, and grids.

  • Understanding loop control and scope.


Detailed Code Explanation

javaCopyEditpublic class NestedLoopsDemo {
    public static void main(String[] args) {

        for (int i = 1; i <= 3; i++) {         // Outer loop controls rows
            for (int j = 1; j <= 9; j++) {     // Inner loop controls columns
                System.out.print(i + " ");     // Print current row number
            }
            System.out.println();               // Newline after each row
        }
    }
}

Line-by-Line Explanation

  • Outer loop i runs 3 times (rows).

  • Inner loop j runs 9 times (columns) per outer iteration.

  • Prints i nine times per line.

  • After inner loop, prints newline to start next row.


Important Concepts

  • Inner loops complete fully for each iteration of outer loop.

  • Printing with spaces to format output.

  • Loop variables are local to their loops.


Practical Tips

  • Modify ranges to change grid size.

  • Print different characters for patterns.

  • Useful in GUI grids or matrix operations.


Quick Quiz

  • How would you print a multiplication table using nested loops?

  • What changes if you swap inner and outer loops?

  • How can nested loops be used to traverse 2D arrays?


1️⃣4️⃣ SymbolGridPrinter — User-Defined Grid of Symbols with Nested Loops


What This Program Does

  • Asks the user for number of rows, columns, and a symbol.

  • Prints a grid of that symbol with specified dimensions.


Why This Program Is Important

Combines:

  • User input.

  • Nested loops for rows and columns.

  • Printing characters multiple times.

A practical pattern-building program.


Detailed Code Explanation

javaCopyEditimport java.util.Scanner;

public class SymbolGridPrinter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of rows: ");
        int rows = scanner.nextInt();

        System.out.print("Enter the number of columns: ");
        int columns = scanner.nextInt();

        System.out.print("Enter the symbol: ");
        char symbol = scanner.next().charAt(0);  // Reads first char of user input

        for (int i = 1; i <= rows; i++) {       // Loop over rows
            for (int j = 1; j <= columns; j++) { // Loop over columns
                System.out.print(symbol);         // Print symbol without newline
            }
            System.out.println();                 // Newline after each row
        }

        scanner.close();
    }
}

Line-by-Line Explanation

  • Reads rows and columns as integers.

  • Reads a symbol character (char) from user input.

  • Outer loop runs rows times.

  • Inner loop prints columns times per row.

  • After each row, prints newline to move to next line.


Important Concepts

  • Nested loops for 2D printing.

  • Using scanner.next().charAt(0) to get a single character.

  • Input-driven dynamic patterns.


Practical Tips

  • Validate inputs for positive numbers.

  • Use different symbols to create patterns.

  • Can be extended to print different characters per row or column.


Quick Quiz

  • How to modify code to print row numbers instead of symbols?

  • How would you create a checkerboard pattern?

  • Can you print hollow rectangles using nested loops?


Summary of Today’s Concepts

  • Logical operators: combine multiple conditions for decision making.

  • Input validation: loops (while, do-while) ensure correct input.

  • Control flow modifiers: break and continue control loop execution.

  • Loops: for, while, do-while loops used for repetition.

  • Nested loops: create complex output patterns and grids.

  • User interaction: combine input with loops for interactive programs.

0
Subscribe to my newsletter

Read articles from Himanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Himanshi
Himanshi

Hi! I'm a curious and self-driven programmer currently pursuing my BCA 🎓 and diving deep into the world of Java ☕ from Day 1. I already have a foundation in programming, and now I'm expanding my skills one concept, one blog, and one project at a time. I’m learning Java through Bro Code’s YouTube tutorials, experimenting with code, and documenting everything I understand — from basic syntax to real-world applications — to help others who are just starting out too. I believe in learning in public, progress over perfection, and growing with community support. You’ll find beginner-friendly Java breakdowns, hands-on code snippets, and insights from my daily coding grind right here. 💡 Interests: Java, Web Dev, Frontend Experiments, AI-curiosity, Writing & Sharing Knowledge 🛠️ Tools: Java • HTML/CSS • JavaScript • Python (basics) • SQL 🎯 Goal: To become a confident Full Stack Developer & AI Explorer 📍 Based in India | Blogging my dev journey #JavaJourney #100DaysOfCode #CodeNewbie #LearnWithMe