allizwell.jobsdoor360.in

Arrays and Strings

Java Programming Course › Module 03 › Arrays and Strings
JAVA PROGRAMMING COURSE / MODULE 03

Arrays and Strings

Learn how to store multiple values in a single variable using arrays and how to work with text using strings. Understand these important Java concepts through simple explanations, practical examples and placement-focused programs.

Beginner Level 12 Topics Placement Preparation Practical Examples

What Will You Learn in This Module?

In the previous module, you learned about variables, data types, operators, conditions and loops.

Now imagine that you want to store the marks of 50 students. Creating 50 separate variables would be difficult. Instead, Java provides arrays, which allow us to store multiple values of the same data type together.

You will also learn about strings, which are used to store and process text such as names, messages and sentences.

Learning Objectives

After completing this module, you will be able to:

  • Understand what arrays are and why they are useful.
  • Declare, initialize and access array elements.
  • Update and traverse array elements.
  • Find the sum, average, maximum and minimum values in an array.
  • Search for an element in an array.
  • Understand strings and their basic operations.
  • Use common String methods in Java.
  • Compare strings correctly.
  • Understand string immutability.
  • Use StringBuilder and StringBuffer.
TOPIC 01

1. Introduction to Arrays

What is an Array?

An array is a collection of multiple values of the same data type stored under a single variable name.

Think of an array as a row of boxes. Each box stores one value, and every box has a position number called an index.

Real-Life Example

Suppose a teacher wants to store the marks of five students. Instead of creating five separate variables, the teacher can store all five marks in one array.

Without Using an Array

Java Program
public class Main {
    public static void main(String[] args) {

        int mark1 = 80;
        int mark2 = 75;
        int mark3 = 90;
        int mark4 = 85;
        int mark5 = 70;

        System.out.println(mark1);
        System.out.println(mark2);
        System.out.println(mark3);
        System.out.println(mark4);
        System.out.println(mark5);
    }
}

This works, but storing many values using separate variables becomes difficult.

Using an Array

Java Program
public class Main {
    public static void main(String[] args) {

        int[] marks = {80, 75, 90, 85, 70};

        System.out.println(marks[0]);
        System.out.println(marks[1]);
        System.out.println(marks[2]);
        System.out.println(marks[3]);
        System.out.println(marks[4]);
    }
}
Output: 80 75 90 85 70

Understanding Array Indexes

Every array element has an index. In Java, array indexing always starts from 0.

Index Value
080
175
290
385
470
Remember: If an array contains 5 elements, its indexes are 0, 1, 2, 3 and 4. The last index is always array length minus 1.
TOPIC 02

2. Declaration and Initialization of Arrays

What is Array Declaration?

Declaration means creating an array variable by specifying its data type and name.

Java Syntax
int[] numbers;

Here, we have declared an array named numbers that can store integer values.

What is Array Initialization?

Initialization means creating the array and assigning values to its elements.

Java Syntax
int[] numbers = {10, 20, 30, 40, 50};

Creating an Array with a Fixed Size

We can also create an array by specifying its size. Java automatically assigns default values to its elements.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = new int[5];

        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;

        System.out.println(numbers[2]);
    }
}
Output: 30

Default Values in Arrays

When an array is created using new, Java automatically assigns default values to its elements.

Data Type Default Value
int0
double0.0
float0.0f
booleanfalse
charEmpty character (\u0000)
Reference typesnull
Important: Arrays have a fixed size after creation. You cannot directly increase or decrease the size of an existing array.
TOPIC 03

3. Accessing and Updating Array Elements

Accessing Array Elements

We can access an array element by using its index number.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println(numbers[0]);
        System.out.println(numbers[2]);
        System.out.println(numbers[4]);
    }
}
Output: 10 30 50

Updating Array Elements

We can change an existing array value by assigning a new value to its index.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        numbers[2] = 100;

        System.out.println(numbers[2]);
    }
}
Output: 100

Understanding Array Length

Java provides the length property to find the total number of elements in an array.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println(numbers.length);
    }
}
Output: 5
Remember: Use arrayName.length to get the number of elements. It is a property, not a method, so do not write numbers.length().
TOPIC 04

4. Traversing an Array Using Loops

What is Array Traversal?

Traversing an array means visiting each element of the array one by one.

Instead of printing every element separately, we can use loops to visit all elements automatically.

Using a for Loop

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}
Output: 10 20 30 40 50

Understanding the Loop

  • i = 0 starts from the first array index.
  • i less than numbers.length ensures every valid index is visited.
  • i++ moves to the next index.
  • numbers[i] accesses the current element.

Using an Enhanced for Loop

Java also provides an enhanced for loop, commonly called a for-each loop. It makes array traversal simpler when we only need to read each element.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        for (int number : numbers) {
            System.out.println(number);
        }
    }
}
Output: 10 20 30 40 50
Placement Tip: Understand both normal for loops and enhanced for loops. Normal loops are useful when you need the index, while enhanced for loops are convenient when you only need each element.
TOPIC 05

5. Finding Sum, Average, Maximum and Minimum in an Array

Finding the Sum of Array Elements

We can find the sum of all array elements by adding them one by one using a loop.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        int sum = 0;

        for (int i = 0; i < numbers.length; i++) {
            sum = sum + numbers[i];
        }

        System.out.println("Sum = " + sum);
    }
}
Output: Sum = 150

Finding the Average

Average means the total sum divided by the number of elements.

Formula:

Average Formula

Average = Sum of all elements / Total number of elements

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        int sum = 0;

        for (int number : numbers) {
            sum += number;
        }

        double average = (double) sum / numbers.length;

        System.out.println("Average = " + average);
    }
}
Output: Average = 30.0

Finding the Maximum Element

The maximum element is the largest value present in an array. We can start by assuming the first element is the largest and then compare it with the remaining elements.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {25, 10, 45, 5, 30};

        int max = numbers[0];

        for (int i = 1; i  max) {
                max = numbers[i];
            }
        }

        System.out.println("Maximum = " + max);
    }
}
Output: Maximum = 45

Finding the Minimum Element

The minimum element is the smallest value present in an array. We use a similar approach, but check whether an element is smaller than the current minimum.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {25, 10, 45, 5, 30};

        int min = numbers[0];

        for (int i = 1; i < numbers.length; i++) {

            if (numbers[i] < min) {
                min = numbers[i];
            }
        }

        System.out.println("Minimum = " + min);
    }
}
Output: Minimum = 5
Remember: These are some of the most useful basic array problems for placement preparation. Practice understanding the loop and comparison logic.
TOPIC 06

6. Searching Elements in an Array

What is Searching?

Searching means finding whether a particular value exists in an array. If it exists, we can also find its position.

Linear Search

Linear search checks array elements one by one from the beginning until the required value is found or the array ends.

Example

Suppose the array contains 10, 20, 30, 40 and 50. If we want to find 30, we first check 10, then 20, and finally 30. We have found the element at index 2.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        int target = 30;
        int position = -1;

        for (int i = 0; i < numbers.length; i++) {

            if (numbers[i] == target) {
                position = i;
                break;
            }
        }

        if (position != -1) {
            System.out.println("Element found at index " + position);
        } else {
            System.out.println("Element not found");
        }
    }
}
Output: Element found at index 2

Understanding the Program

  • target stores the value we want to search for.
  • position is initially -1, meaning the element has not been found.
  • The loop checks every array element.
  • If a match is found, we store its index and stop the loop using break.
  • Finally, we print whether the element was found.

Time Complexity of Linear Search

In the worst case, linear search may need to check every element. Therefore, its time complexity is O(n), where n is the number of elements.

Placement Tip: Linear search is a basic but important searching technique. You will study binary search and other searching algorithms in the Data Structures and Algorithms course.
TOPIC 07

7. Introduction to Strings in Java

What is a String?

A String is a sequence of characters used to store text. Examples include names, city names, messages and sentences.

In Java, String is a class, not a primitive data type.

Real-Life Example

When you enter your name while creating an online account, the application stores that name as text. In Java, we can use a String variable to store it.

Creating a String

We can create a String using double quotation marks.

Java Program
public class Main {
    public static void main(String[] args) {

        String name = "Rahul";

        System.out.println(name);
    }
}
Output: Rahul

Another Way to Create a String

We can also create a String using the new keyword.

Java Program
public class Main {
    public static void main(String[] args) {

        String name = new String("Rahul");

        System.out.println(name);
    }
}
Output: Rahul

Combining Strings

We can combine two or more strings using the + operator. This is called string concatenation.

Java Program
public class Main {
    public static void main(String[] args) {

        String firstName = "Rahul";
        String lastName = "Sharma";

        String fullName = firstName + " " + lastName;

        System.out.println(fullName);
    }
}
Output: Rahul Sharma
Remember: String values are written inside double quotation marks. A single character stored in a char variable uses single quotation marks.
TOPIC 08

8. Common String Methods

What are String Methods?

String methods are built-in operations provided by Java to work with text. They help us find the length of a string, change its case, search for characters and perform other tasks.

Important String Methods

Method Purpose Example
length() Returns the number of characters name.length()
charAt() Returns the character at an index name.charAt(0)
toUpperCase() Converts text to uppercase name.toUpperCase()
toLowerCase() Converts text to lowercase name.toLowerCase()
substring() Extracts part of a string name.substring(1, 4)
contains() Checks whether text exists name.contains("Rah")
indexOf() Returns the first matching index name.indexOf('a')
trim() Removes leading and trailing spaces name.trim()
replace() Replaces characters or text name.replace('a', 'o')
equals() Compares string contents name.equals("Rahul")

Example: Using String Methods

Java Program
public class Main {
    public static void main(String[] args) {

        String name = "Rahul";

        System.out.println(name.length());
        System.out.println(name.toUpperCase());
        System.out.println(name.toLowerCase());
        System.out.println(name.charAt(0));
        System.out.println(name.contains("ah"));
    }
}
Output: 5 RAHUL rahul R true

Understanding substring()

substring() is used to extract a portion of a string. The starting index is included, but the ending index is excluded.

Java Program
public class Main {
    public static void main(String[] args) {

        String name = "Programming";

        System.out.println(name.substring(0, 4));
    }
}
Output: Prog
Remember: String indexes start from 0. The substring starting index is included, while the ending index is excluded.
TOPIC 09

9. String Comparison

Why Do We Need to Compare Strings?

Sometimes we need to check whether two strings contain the same text. For example, we may want to compare a username entered by a user with a stored username.

Using the == Operator

The == operator compares whether two reference variables refer to the same object. It does not reliably compare the actual text stored in two different String objects.

Using equals()

The equals() method compares the actual contents of two strings. It is the usual method for checking whether two strings contain the same text.

Java Program
public class Main {
    public static void main(String[] args) {

        String a = new String("Java");
        String b = new String("Java");

        System.out.println(a == b);
        System.out.println(a.equals(b));
    }
}
Output: false true

Using equalsIgnoreCase()

equalsIgnoreCase() compares two strings without considering uppercase and lowercase differences.

Java Program
public class Main {
    public static void main(String[] args) {

        String a = "Java";
        String b = "JAVA";

        System.out.println(a.equals(b));
        System.out.println(a.equalsIgnoreCase(b));
    }
}
Output: false true
Placement Tip: Remember the difference between == and equals(). This is a common Java interview and output-based question.
TOPIC 10

10. String Immutability

What Does Immutable Mean?

Immutable means something that cannot be changed after it has been created.

In Java, String objects are immutable. This means that once a String object is created, its original content cannot be modified.

Example

Java Program
public class Main {
    public static void main(String[] args) {

        String name = "Java";

        name.concat(" Programming");

        System.out.println(name);
    }
}
Output: Java

Why is the output still Java? Because concat() creates a new String instead of changing the original String. We did not store that new String anywhere.

Storing the New String

Java Program
public class Main {
    public static void main(String[] args) {

        String name = "Java";

        name = name.concat(" Programming");

        System.out.println(name);
    }
}
Output: Java Programming
Remember: String methods generally return a new String rather than modifying the original String object.
TOPIC 11

11. StringBuilder and StringBuffer

Why Do We Need StringBuilder?

We learned that String objects are immutable. Every time we modify a String, a new String object may be created.

If we need to modify text many times, this can create unnecessary objects. Java provides StringBuilder and StringBuffer for working with modifiable text.

What is StringBuilder?

StringBuilder is a Java class that allows us to modify text without creating a new String object for every change.

Example: Using StringBuilder

Java Program
public class Main {
    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder("Java");

        sb.append(" Programming");

        System.out.println(sb);
    }
}
Output: Java Programming

Common StringBuilder Methods

Method Purpose
append() Adds text at the end.
insert() Inserts text at a specified position.
delete() Deletes characters from a specified range.
reverse() Reverses the sequence of characters.
length() Returns the number of characters.
toString() Converts the StringBuilder into a String.

Example: Reversing a String

Java Program
public class Main {
    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder("Java");

        sb.reverse();

        System.out.println(sb);
    }
}
Output: avaJ

What is StringBuffer?

StringBuffer is another Java class used to create and modify text. Like StringBuilder, it is mutable.

The main difference is that StringBuffer provides synchronized methods, making its individual operations thread-safe. StringBuilder is generally preferred when thread safety is not required because it usually has less overhead.

Difference Between String, StringBuilder and StringBuffer

Feature String StringBuilder StringBuffer
Mutable No Yes Yes
Thread-safe Immutable No Yes, for synchronized methods
Modification Creates new String objects Modifies the same object Modifies the same object
Common Use Text that does not need modification Frequent text modifications in single-threaded code Shared text modifications requiring synchronization
Placement Tip: Be ready to explain why String is immutable and how StringBuilder differs from StringBuffer.
TOPIC 12

12. Basic Array and String Programming Questions

Program 1: Reverse an Array

Reversing an array means displaying its elements from the last position to the first position.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        for (int i = numbers.length - 1; i >= 0; i--) {
            System.out.println(numbers[i]);
        }
    }
}
Output: 50 40 30 20 10

Program 2: Count Even and Odd Numbers in an Array

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 15, 20, 25, 30};

        int even = 0;
        int odd = 0;

        for (int number : numbers) {

            if (number % 2 == 0) {
                even++;
            } else {
                odd++;
            }
        }

        System.out.println("Even = " + even);
        System.out.println("Odd = " + odd);
    }
}
Output: Even = 3 Odd = 2

Program 3: Reverse a String

We can reverse a String by reading its characters from the last index to the first index.

Java Program
public class Main {
    public static void main(String[] args) {

        String text = "Java";

        for (int i = text.length() - 1; i >= 0; i--) {
            System.out.print(text.charAt(i));
        }
    }
}
Output: avaJ

Program 4: Check Whether a String is a Palindrome

A palindrome is a word that reads the same forward and backward. For example, madam and level are palindromes.

Java Program
public class Main {
    public static void main(String[] args) {

        String text = "madam";

        String reversed = "";

        for (int i = text.length() - 1; i >= 0; i--) {
            reversed += text.charAt(i);
        }

        if (text.equals(reversed)) {
            System.out.println("Palindrome");
        } else {
            System.out.println("Not Palindrome");
        }
    }
}
Output: Palindrome

Program 5: Count Vowels in a String

Vowels are a, e, i, o and u. We can count them by checking each character of the String.

Java Program
public class Main {
    public static void main(String[] args) {

        String text = "education";

        int count = 0;

        for (int i = 0; i < text.length(); i++) {

            char ch = Character.toLowerCase(text.charAt(i));

            if (ch == 'a' || ch == 'e' || ch == 'i'
                || ch == 'o' || ch == 'u') {

                count++;
            }
        }

        System.out.println("Vowels = " + count);
    }
}
Output: Vowels = 5

Program 6: Find the Second Largest Distinct Element in an Array

This program finds the second largest distinct value. For example, in the array 10, 30, 20, 40, 40, the second largest distinct value is 30.

Java Program
public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 30, 20, 40, 40};

        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;

        for (int number : numbers) {

            if (number > largest) {

                secondLargest = largest;
                largest = number;

            } else if (number > secondLargest
                    && number < largest) {

                secondLargest = number;
            }
        }

        if (secondLargest == Integer.MIN_VALUE) {
            System.out.println("Second largest distinct element not found");
        } else {
            System.out.println("Second largest = " + secondLargest);
        }
    }
}
Output: Second largest = 30
Important: These programs are useful for practicing array traversal, comparisons, loops and String methods. Try writing them yourself without looking at the solutions.

Module 3 Summary – Arrays and Strings

In this module, you learned:

  • Arrays: Store multiple values of the same data type.
  • Array Declaration: Create an array variable.
  • Array Initialization: Assign values to array elements.
  • Array Indexing: Access elements using indexes starting from 0.
  • Array Traversal: Visit elements using loops.
  • Array Operations: Calculate sum, average, maximum and minimum.
  • Searching: Find an element using linear search.
  • Strings: Store and process text.
  • String Methods: Work with text using built-in methods.
  • String Comparison: Compare text using equals() and related methods.
  • String Immutability: Understand why String objects cannot be modified.
  • StringBuilder and StringBuffer: Work with mutable text.

Arrays and Strings are extremely important in Java programming and placement interviews. Practice the programs in this module until you can write them independently.

Practice Questions

Try solving these questions on your own:

  1. Create an array of 10 integers and print all its elements.
  2. Take 5 numbers from the user and store them in an array.
  3. Find the sum and average of all array elements.
  4. Find the largest and smallest element in an array.
  5. Count the even and odd numbers in an array.
  6. Search for a given number using linear search.
  7. Print all array elements in reverse order.
  8. Find the second largest distinct element in an array.
  9. Find how many times a particular number appears in an array.
  10. Create a String containing your name and print its length.
  11. Convert a String into uppercase and lowercase.
  12. Reverse a String without using reverse().
  13. Check whether a given String is a palindrome.
  14. Count the vowels and consonants in a String.
  15. Count the number of words in a sentence.
  16. Compare two strings using equals().
  17. Remove leading and trailing spaces using trim().
  18. Use StringBuilder to reverse a String.

Java Arrays and Strings – Interview Questions

1. What is an array in Java?

An array is a collection of elements of the same data type stored under one variable name. Each element can be accessed using its index.

2. Does array indexing start from 0 or 1?

Array indexing in Java starts from 0. The first element has index 0, and the last element has index length - 1.

3. How do you find the length of an array?

We use the length property, for example numbers.length.

4. Can we change the size of an array after creating it?

No. A Java array has a fixed size after it is created. We can create another array or use a collection such as ArrayList when a resizable structure is required.

5. What is array traversal?

Array traversal means visiting each element of an array one by one, usually using a loop.

6. What is linear search?

Linear search checks each element one by one until the required element is found or the array ends.

7. What is a String in Java?

A String is an object that represents a sequence of characters and is used to store text.

8. Is String a primitive data type?

No. String is a class in Java, not a primitive data type.

9. What is the difference between == and equals() for Strings?

== checks whether two references point to the same object, while equals() compares the actual String contents.

10. Why is String immutable in Java?

String objects cannot be changed after creation. This helps with safe sharing, predictable behaviour and reuse of String objects.

11. What is the difference between StringBuilder and StringBuffer?

Both are mutable. StringBuilder is generally faster when synchronization is not needed, while StringBuffer provides synchronized methods for thread-safe operations.

12. What is the use of charAt()?

charAt() returns the character present at a specified index in a String.

Congratulations! Module 3 Completed

You have learned how to work with arrays and strings in Java. These concepts are used frequently in programming and placement interviews.

Practice the array and string programs until you can solve them independently.

In the next module, you will learn about Methods and Recursion.

Scroll to Top