Java Programming Day 6

HimanshiHimanshi
6 min read

🚀 Java Day 6 – Exploring Arrays, User Input, Searching, and Varargs Methods


Today, I focused on deepening my understanding of core Java concepts like arrays, dynamic user input, searching techniques, stacks, and varargs methods for flexible arguments. These building blocks are essential for writing clean, efficient, and reusable code. Here’s what I coded and learned, with detailed explanations and commented code!


1️⃣ Working with Arrays: Declaration, Initialization, and Looping

javaCopyEditimport java.util.Arrays;

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

        // Declare and initialize an array of fruits
        String[] fruits = {"apple", "coconut", "banana", "mango"};

        // Modify the first element (index 0)
        fruits[0] = "pineapple";

        // Get the length (number of elements) in the array
        int numOfFruits = fruits.length;

        // Print the last fruit by accessing the last index directly
        System.out.println("Last fruit: " + fruits[3]);

        // Print total number of fruits
        System.out.println("Number of fruits: " + numOfFruits);

        // Sort the fruits array alphabetically using built-in Arrays method
        Arrays.sort(fruits);

        // Print fruits using a traditional for loop (using indices)
        System.out.println("Fruits (using for loop):");
        for (int i = 0; i < fruits.length; i++) {
            System.out.println(fruits[i]);
        }

        // Print fruits using enhanced for loop (for-each)
        System.out.println("Fruits (using enhanced for loop):");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Key Notes:

  • Arrays hold multiple values of the same type.

  • You can access elements via zero-based indices.

  • .length gives array size.

  • Arrays.sort() sorts arrays easily.

  • Two loop styles: traditional index loop and enhanced for-each loop.


2️⃣ Creating and Taking User Input for Arrays Dynamically

javaCopyEditimport java.util.Scanner;

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

        // Ask user how many foods they want to enter
        System.out.print("How many foods do you want to enter? ");
        int size = scanner.nextInt();
        scanner.nextLine();  // Consume leftover newline after nextInt()

        // Create array of that size
        String[] foods = new String[size];

        // Take input for each food item
        for (int i = 0; i < foods.length; i++) {
            System.out.print("Enter food item " + (i + 1) + ": ");
            foods[i] = scanner.nextLine();
        }

        // Print all foods entered by user
        System.out.println("Your favorite foods are:");
        for (String food : foods) {
            System.out.println(food);
        }

        scanner.close();
    }
}

Key Notes:

  • Array size is dynamic based on user input.

  • Always clear the buffer after numeric input using scanner.nextLine().

  • Perfect for collecting variable-length data from users.


javaCopyEditimport java.util.Scanner;

public class NumberSearch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] numbers = {1, 2, 3, 4, 5, 6};

        // Ask user for the number to search
        System.out.print("Enter the number to find in the array: ");
        int target = scanner.nextInt();

        boolean isFound = false;  // Flag to track if found

        // Loop through array elements to find target
        for (int i = 0; i < numbers.length; i++) {
            if (target == numbers[i]) {
                System.out.println("Element found at index: " + i);
                isFound = true;
                break;  // Exit loop early once found
            }
        }

        // If not found after full loop
        if (!isFound) {
            System.out.println("Element not found in the array.");
        }

        scanner.close();
    }
}

Key Notes:

  • Demonstrates linear search: checking elements one by one.

  • break statement stops search when found.

  • Basic but crucial searching algorithm.


4️⃣ Searching for a Fruit in a String Array (Case-Insensitive)

javaCopyEditimport java.util.Scanner;

public class FruitSearch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] fruits = {"apple", "coconut", "banana", "mango"};

        // Ask user to enter fruit name (case insensitive)
        System.out.print("Enter the fruit to search: ");
        String target = scanner.nextLine().trim().toLowerCase();

        boolean isFound = false;

        // Loop through fruits and compare ignoring case
        for (int i = 0; i < fruits.length; i++) {
            if (fruits[i].equalsIgnoreCase(target)) {
                System.out.println("Fruit found at index: " + i);
                isFound = true;
                break;
            }
        }

        // If fruit not found
        if (!isFound) {
            System.out.println("Fruit not found in the array.");
        }

        scanner.close();
    }
}

Key Notes:

  • Uses equalsIgnoreCase() to match strings regardless of case.

  • trim() removes extra spaces from user input.

  • Improves user-friendliness by allowing flexible input.


5️⃣ Understanding Java Stacks with the Stack Class

javaCopyEditimport java.util.Stack;

public class GameStackDemo {
    public static void main(String[] args) {
        // Create a Stack to store game titles
        Stack<String> gameStack = new Stack<>();

        // Check if the stack is empty at the start
        System.out.println("Is the stack empty? " + gameStack.empty());

        // Add games to the stack (push operation)
        gameStack.push("Minecraft");
        gameStack.push("Skyrim");
        gameStack.push("DOOM");
        gameStack.push("Borderlands");
        gameStack.push("FFVII");

        // Display entire stack content
        System.out.println("Stack: " + gameStack);

        // Peek at the top element without removing
        System.out.println("Top element: " + gameStack.peek());

        // Search for "Minecraft" in the stack (returns position from top, 1-based)
        System.out.println("Position of 'Minecraft': " + gameStack.search("Minecraft"));

        // Check if stack is empty after pushes
        System.out.println("Is the stack empty? " + gameStack.empty());

        // Remove top two elements (pop operation)
        gameStack.pop();
        gameStack.pop();
        System.out.println("Stack after popping two elements: " + gameStack);

        // Pop remaining elements one by one
        gameStack.pop();
        gameStack.pop();
        String favoriteGame = gameStack.pop();

        // Check if stack is empty after all pops
        System.out.println("Is the stack empty? " + gameStack.empty());
        System.out.println("My favorite game was: " + favoriteGame);
    }
}

Key Notes:

  • Stack is LIFO (Last In, First Out).

  • push() adds items to the top.

  • pop() removes and returns the top item.

  • peek() shows the top item without removal.

  • search() gives the 1-based position from the top.

  • Useful in undo/redo, expression parsing, backtracking.


6️⃣ Using Varargs to Add Multiple Numbers

javaCopyEditpublic class VarArgsAddition {
    public static void main(String[] args) {
        // Call varargs method with 4 numbers
        int result = add(1, 2, 3, 4);
        System.out.println("Sum: " + result);
    }

    // Varargs method accepts any number of int arguments
    static int add(int... numbers) {
        int sum = 0;

        // Loop through all numbers and add to sum
        for (int number : numbers) {
            sum += number;
        }

        return sum;  // Return total sum
    }
}

Key Notes:

  • Varargs (int...) allow methods to accept variable number of arguments.

  • Helpful when you don’t know the count of parameters beforehand.

  • Simplifies method calls.


7️⃣ Varargs to Calculate Average of Double Values

javaCopyEditpublic class VarArgsAverage {
    public static void main(String[] args) {
        // Calculate average of given numbers
        double result = avg(22, 33, 44, 55);
        System.out.println("Average: " + result);

        // Handle no arguments gracefully
        System.out.println("Average with no numbers: " + avg());
    }

    // Varargs method to compute average of any count of doubles
    static double avg(double... numbers) {
        double sum = 0;

        // If no numbers provided, return 0 to avoid division by zero
        if (numbers.length == 0) {
            return 0;
        }

        // Add all numbers
        for (double number : numbers) {
            sum += number;
        }

        // Calculate average by dividing sum by count of numbers
        return sum / numbers.length;
    }
}

Key Notes:

  • Works with floating-point numbers (double).

  • Safely handles empty input (returns 0).

  • Very useful for flexible numeric computations.


📚 Summary of Day 6 Learning

TopicWhat I Learned
ArraysDeclaration, modification, sorting, looping
User InputDynamic array size, scanner usage, clearing input buffers
SearchingLinear search for numbers and strings (case insensitive)
Stack Data StructureLIFO principle, push/pop/peek/search methods
Varargs MethodsFlexible method arguments, adding and averaging numbers
Good PracticesInput validation, handling edge cases (empty input), readability

✨ Final Thoughts

Today was all about strengthening my basics and learning how to write flexible and reusable Java code. From searching elements to managing stacks and creating methods that accept variable inputs — it’s all helping me write cleaner, more dynamic programs.

These fundamentals will definitely make building bigger projects easier and more efficient. Onward and upward! 🚀

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