Java Programming Day 6

HimanshiHimanshi
7 min read

Exploring Java Arrays, User Input, Searching, and Varargs Methods

Today, I deepened my understanding of Java by working on arrays, user input, searching algorithms, and flexible method arguments using varargs. These concepts are fundamental for writing efficient and scalable Java programs. I practiced manipulating arrays, taking dynamic inputs, searching elements, and creating reusable methods. Below is a detailed summary of my learnings, code examples, and explanations.


1. Working with Arrays: Basic 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"};

        // Change the first fruit
        fruits[0] = "pineapple";

        // Get the length of the array
        int numOfFruits = fruits.length;

        // Print the last fruit in the array
        System.out.println("Last fruit: " + fruits[3]);

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

        // Sort the array alphabetically
        Arrays.sort(fruits);

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

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

Notes and Explanation:

  • Arrays store multiple values of the same type.

  • You can modify elements using their index, starting from 0.

  • .length gives the size of the array.

  • Arrays.sort() sorts the array alphabetically.

  • Looping through arrays can be done with both traditional for loops (using indices) and enhanced for loops (for-each).

  • The enhanced for loop is simpler and more readable when you only need the element, not the index.


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 for the size of the foods array
        System.out.print("How many foods do you want to enter? ");
        int size = scanner.nextInt();
        scanner.nextLine();  // Clear the newline

        String[] foods = new String[size];

        // Take user 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 food items entered by the user
        System.out.println("Your favorite foods are:");
        for (String food : foods) {
            System.out.println(food);
        }

        scanner.close();
    }
}

Notes and Explanation:

  • Here, the array size is not fixed; it depends on user input.

  • This allows flexibility in handling varying amounts of data.

  • Always remember to clear the scanner buffer with scanner.nextLine() after numeric input.

  • This program demonstrates reading strings from the console and storing them in an array.


3. Searching for a Number in an Integer Array

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};

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

        boolean isFound = false;
        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 once found
            }
        }

        if (!isFound) {
            System.out.println("Element not found in the array.");
        }

        scanner.close();
    }
}

Notes and Explanation:

  • This program demonstrates a simple linear search algorithm.

  • We loop through the array and compare each element with the target number.

  • If found, we print the index and stop searching.

  • If not found after checking all elements, a message is displayed.

  • Understanding searching algorithms is key for data handling.


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"};

        System.out.print("Enter the fruit to search: ");
        String target = scanner.nextLine().trim().toLowerCase();

        boolean isFound = false;
        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 (!isFound) {
            System.out.println("Fruit not found in the array.");
        }

        scanner.close();
    }
}

Notes and Explanation:

  • This is a string search that ignores case (equalsIgnoreCase()).

  • trim() removes unnecessary spaces from user input.

  • Good practice when searching strings because user input might vary in case or spaces.

  • Helps build user-friendly programs that can handle diverse inputs.


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 stack is empty initially
        System.out.println("Is the stack empty? " + gameStack.empty());

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

        // Print the entire stack
        System.out.println("Stack: " + gameStack);

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

        // Search for an element's position from the top
        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 elements from the stack (LIFO)
        gameStack.pop();
        gameStack.pop();
        System.out.println("Stack after popping two elements: " + gameStack);

        // Pop remaining elements
        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);
    }
}

Notes and Explanation:

  • Stack follows LIFO (Last In, First Out) principle.

  • push() adds elements to the top.

  • pop() removes and returns the top element.

  • peek() views the top element without removing it.

  • search() returns the position of an element counting from the top (1-based index).

  • Stacks are useful for undo features, expression evaluation, parsing, and backtracking.


6. Using Varargs to Add Multiple Numbers

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

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

        // Sum all the numbers passed
        for (int number : numbers) {
            sum += number;
        }

        return sum;
    }
}

Notes and Explanation:

  • Varargs (int... numbers) allow passing a variable number of arguments.

  • Simplifies method calls when the number of parameters varies.

  • Here, it sums all passed integers regardless of how many.


7. Varargs to Calculate Average of Double Values

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

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

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

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

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

Notes and Explanation:

  • This method calculates average of a flexible number of double values.

  • Handles empty input gracefully by returning 0.

  • Useful for mathematical calculations where input count can vary.


Summary and Reflection

Day 6 was an intense and productive day of Java programming focused on mastering arrays, input handling, searching algorithms, stacks, and advanced method arguments using varargs.

What I Learned Today:

  • How to declare, initialize, and manipulate arrays in Java.

  • Taking user input to create arrays of dynamic size.

  • Searching through arrays using loops and comparing values.

  • Working with case-insensitive string comparisons.

  • Understanding stack data structure and its common operations.

  • Writing flexible methods using varargs to accept variable numbers of arguments.

  • Handling edge cases, like empty inputs in calculations.

By combining these concepts, I am now better equipped to write programs that are efficient, flexible, and user-friendly. These foundational skills will help me build more complex applications in the future.

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