Java Programming Day 5

HimanshiHimanshi
7 min read

Day 5: My Journey with Java Methods, Overloading, Variable Scope & Simple Projects

Today, I explored Java methods in detail, including writing reusable methods, method overloading for flexible function signatures, understanding variable scope and shadowing, and applying these concepts by building two beginner-friendly projects: a simple banking app and a dice roller with ASCII art.


1️⃣ Utility Methods Demo: Square, Cube, Full Name, and Age Check

Explanation:
This program demonstrates how to write simple reusable methods with different return types (double, String, boolean). The goal is to see how to structure code into small, focused methods that perform a single task β€” like calculating squares or cubes, concatenating names, or checking age eligibility.

javaCopyEdit/*
  Program: Utility Methods Demonstration
  Concept: Writing methods with different return types in Java
*/

public class UtilityMethodsDemo {

    public static void main(String[] args) {

        // Call square method and print the result
        double result = square(6);
        System.out.println("πŸ“ The square of 6 is: " + result);

        // Call cube method and print directly
        System.out.println("πŸ“¦ The cube of 6 is: " + cube(6));

        // Combine first and last name and print full name
        System.out.println("πŸ‘€ Full name is: " + getFullName("Bro", "Code"));

        // Check if age 4 is adult and print boolean result
        System.out.println("πŸ” Is a 4-year-old an adult? " + ageCheck(4));
    }

    // Method to calculate square of a number
    static double square(double number) {
        return number * number;
    }

    // Method to calculate cube of a number
    static double cube(double number) {
        return number * number * number;
    }

    // Method to concatenate first and last names with space
    static String getFullName(String firstName, String lastName) {
        return firstName + " " + lastName;
    }

    // Method to check if age qualifies as adult (18+)
    static boolean ageCheck(int age) {
        return age >= 18;
    }
}

Notes and Key Takeaways:

  • Methods break down complex programs into reusable units.

  • Different methods can return different types (double, String, boolean).

  • Writing small methods improves code readability and maintenance.

  • Practice helps solidify understanding of method signatures and return statements.


2️⃣ Playing with Method Overloading β€” Adding Numbers

Explanation:
This program shows method overloading, where multiple methods share the same name but differ by the number or types of parameters. It simplifies your code by allowing the same operation (adding numbers) for varying counts of inputs.

javaCopyEditpublic class Adder {

    public static void main(String[] args) {
        System.out.println("Sum of 1 and 2: " + add(1, 2));
        System.out.println("Sum of 1, 2 and 3: " + add(1, 2, 3));
        System.out.println("Sum of 1, 2, 3 and 4: " + add(1, 2, 3, 4));
    }

    // Add two numbers
    static double add(double a, double b) {
        return a + b;
    }

    // Add three numbers
    static double add(double a, double b, double c) {
        return a + b + c;
    }

    // Add four numbers
    static double add(double a, double b, double c, double d) {
        return a + b + c + d;
    }
}

Notes and Key Takeaways:

  • Method overloading lets you reuse the same method name with different parameters.

  • Java determines the right method to call by matching arguments.

  • Overloading improves code clarity when performing similar actions with different inputs.


3️⃣ Making Pizza with Overloaded Methods

Explanation:
This is a practical example of method overloading. Based on how many ingredients you provide, the program builds a pizza description using different overloaded methods.

javaCopyEditpublic class PizzaBuilder {

    public static void main(String[] args) {
        System.out.println(makePizza("flat bread"));
        System.out.println(makePizza("thin crust", "cheddar"));
        System.out.println(makePizza("flat bread", "mozzarella", "pepperoni"));
    }

    // Pizza with only bread
    static String makePizza(String bread) {
        return bread + " pizza";
    }

    // Pizza with bread and cheese
    static String makePizza(String bread, String cheese) {
        return cheese + " " + bread + " pizza";
    }

    // Pizza with bread, cheese, and toppings
    static String makePizza(String bread, String cheese, String toppings) {
        return toppings + " " + cheese + " " + bread + " pizza";
    }
}

Notes and Key Takeaways:

  • This example shows real-world usefulness of method overloading.

  • You can design β€œrecipes” where input parameters vary but function names stay consistent.

  • Improves code modularity and user interface design.


4️⃣ Understanding Variable Scope by Shadowing Variables

Explanation:
This program explains variable scope and shadowing β€” how variables with the same name coexist at different levels (class, method), and how Java picks the closest in scope.

javaCopyEditpublic class VariableScopeDemo {

    static int x = 3; // Class-level variable

    public static void main(String[] args) {
        int x = 1; // Local variable in main shadows class variable
        System.out.println("main-local x = " + x); // Prints 1

        doSomething();

        // Access class-level variable explicitly
        System.out.println("class-static x = " + VariableScopeDemo.x); // Prints 3
    }

    static void doSomething() {
        int x = 2; // Local to doSomething, shadows class variable
        System.out.println("doSomething-local x = " + x); // Prints 2
    }
}

Notes and Key Takeaways:

  • Variables declared inside methods shadow class-level variables with the same name.

  • Java always uses the closest scope variable.

  • Understanding scope avoids bugs caused by accidental variable overwrites.

  • Explicit class reference (like ClassName.variable) accesses class variables when shadowed.


5️⃣ Building a Simple Banking Application

Explanation:
A simple interactive banking system that allows users to view balance, deposit money, withdraw funds (with validation), and exit. It uses methods for modular tasks and validates user input to keep the balance consistent.

javaCopyEditimport java.util.Scanner;

public class SimpleBankApp {
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        double balance = 0;
        boolean isRunning = true;

        while (isRunning) {
            System.out.println("\n***************");
            System.out.println("BANKING PROGRAM");
            System.out.println("***************");
            System.out.println("1. Show Balance");
            System.out.println("2. Deposit");
            System.out.println("3. Withdraw");
            System.out.println("4. Exit");
            System.out.println("***************");

            System.out.print("Enter your choice (1-4): ");
            int choice = scanner.nextInt();

            switch (choice) {
                case 1 -> showBalance(balance);
                case 2 -> balance += deposit();
                case 3 -> balance -= withdraw(balance);
                case 4 -> isRunning = false;
                default -> System.out.println("INVALID CHOICE");
            }
        }

        System.out.println("****************************");
        System.out.println("Thank You! Have a nice day!!");
        System.out.println("****************************");

        scanner.close();
    }

    // Show current balance formatted
    static void showBalance(double balance) {
        System.out.printf("Your current balance is: $%.2f\n", balance);
    }

    // Deposit money with validation for negative amounts
    static double deposit() {
        System.out.print("Enter an amount to be deposited: ");
        double amount = scanner.nextDouble();
        if (amount < 0) {
            System.out.println("Amount can't be negative");
            return 0;
        }
        return amount;
    }

    // Withdraw money with validation for insufficient balance and negative amounts
    static double withdraw(double balance) {
        System.out.print("Enter the amount to be withdrawn: ");
        double amount = scanner.nextDouble();
        if (amount > balance) {
            System.out.println("Insufficient funds");
            return 0;
        } else if (amount < 0) {
            System.out.println("Amount can't be negative");
            return 0;
        }
        return amount;
    }
}

Notes and Key Takeaways:

  • Interactive menus improve user experience.

  • Methods keep code organized and focused.

  • Input validation prevents logical errors like negative deposits or overdrafts.

  • Using switch statements (or expressions) makes the menu flow clear and maintainable.


6️⃣ Dice Roller Program with Cool ASCII Art

Explanation:
A fun dice roller that asks how many dice to roll, generates random rolls, prints ASCII art representing each die face, and sums total rolled values.

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

public class DiceRoller {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        // Ask user number of dice to roll
        System.out.print("Enter the number of Dice to roll: ");
        int numOfDice = scanner.nextInt();

        if (numOfDice > 0) {
            int total = 0;

            // Roll dice, print ASCII art, show roll, and add to total
            for (int i = 0; i < numOfDice; i++) {
                int roll = random.nextInt(1, 7);  // Random 1-6
                printDie(roll);
                System.out.println("You Rolled " + roll);
                total += roll;
            }

            System.out.println("Total : " + total);
        } else {
            System.out.println("Number of dice must be greater than 0.");
        }

        scanner.close();
    }

    // Print ASCII art of dice face based on roll
    static void printDie(int roll) {
        String dice1 = """
               ---------
              |         |
              |    ●    |
              |         |
               ---------
              """;
        String dice2 = """
               ---------
              | ●       |
              |         |
              |       ● |
               ---------
              """;
        String dice3 = """
               ---------
              | ●       |
              |    ●    |
              |       ● |
               ---------
              """;
        String dice4 = """
               ---------
              | ●     ● |
              |         |
              | ●     ● |
               ---------
              """;
        String dice5 = """
               ---------
              | ●     ● |
              |    ●    |
              | ●     ● |
               ---------
              """;
        String dice6 = """
               ---------
              |  ●   ●  |
              |  ●   ●  |
              |  ●   ●  |
               ---------
              """;

        switch (roll) {
            case 1 -> System.out.println(dice1);
            case 2 -> System.out.println(dice2);
            case 3 -> System.out.println(dice3);
            case 4 -> System.out.println(dice4);
            case 5 -> System.out.println(dice5);
            case 6 -> System.out.println(dice6);
            default -> System.out.println("Invalid roll");
        }
    }
}

Notes and Key Takeaways:

  • Using Random class to simulate dice rolls.

  • ASCII art adds fun and visualization to console apps.

  • Validates user input (dice count > 0).

  • Combining loops, conditionals, and I/O creates interactive and engaging programs.


Final Reflection

Day 5 was super valuable for mastering methods and their nuances: overloading, scope, and applying them in real projects. These skills form the backbone of writing clean, reusable, and modular Java code. I also got practical experience with user input, validation, loops, and console output formatting.

Next, I’m eager to learn about Java classes and objects to build even more powerful and maintainable applications.

1
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