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.
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.
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
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
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]);
}
}
Understanding Array Indexes
Every array element has an index. In Java, array indexing always starts from 0.
| Index | Value |
|---|---|
| 0 | 80 |
| 1 | 75 |
| 2 | 90 |
| 3 | 85 |
| 4 | 70 |
2. Declaration and Initialization of Arrays
What is Array Declaration?
Declaration means creating an array variable by specifying its data type and name.
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.
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.
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]);
}
}
Default Values in Arrays
When an array is created using new, Java automatically assigns default values to its elements.
| Data Type | Default Value |
|---|---|
| int | 0 |
| double | 0.0 |
| float | 0.0f |
| boolean | false |
| char | Empty character (\u0000) |
| Reference types | null |
3. Accessing and Updating Array Elements
Accessing Array Elements
We can access an array element by using its index number.
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]);
}
}
Updating Array Elements
We can change an existing array value by assigning a new value to its index.
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
numbers[2] = 100;
System.out.println(numbers[2]);
}
}
Understanding Array Length
Java provides the length property to find the total number of elements in an array.
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers.length);
}
}
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
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]);
}
}
}
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.
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number);
}
}
}
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.
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);
}
}
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
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);
}
}
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.
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);
}
}
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.
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);
}
}
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.
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");
}
}
}
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.
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.
public class Main {
public static void main(String[] args) {
String name = "Rahul";
System.out.println(name);
}
}
Another Way to Create a String
We can also create a String using the new keyword.
public class Main {
public static void main(String[] args) {
String name = new String("Rahul");
System.out.println(name);
}
}
Combining Strings
We can combine two or more strings using the + operator. This is called string concatenation.
public class Main {
public static void main(String[] args) {
String firstName = "Rahul";
String lastName = "Sharma";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
}
}
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
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"));
}
}
Understanding substring()
substring() is used to extract a portion of a string. The starting index is included, but the ending index is excluded.
public class Main {
public static void main(String[] args) {
String name = "Programming";
System.out.println(name.substring(0, 4));
}
}
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.
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));
}
}
Using equalsIgnoreCase()
equalsIgnoreCase() compares two strings without considering uppercase and lowercase differences.
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));
}
}
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
public class Main {
public static void main(String[] args) {
String name = "Java";
name.concat(" Programming");
System.out.println(name);
}
}
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
public class Main {
public static void main(String[] args) {
String name = "Java";
name = name.concat(" Programming");
System.out.println(name);
}
}
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
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
System.out.println(sb);
}
}
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
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.reverse();
System.out.println(sb);
}
}
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 |
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.
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]);
}
}
}
Program 2: Count Even and Odd Numbers in an Array
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);
}
}
Program 3: Reverse a String
We can reverse a String by reading its characters from the last index to the first index.
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));
}
}
}
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.
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");
}
}
}
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.
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);
}
}
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.
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);
}
}
}
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:
- Create an array of 10 integers and print all its elements.
- Take 5 numbers from the user and store them in an array.
- Find the sum and average of all array elements.
- Find the largest and smallest element in an array.
- Count the even and odd numbers in an array.
- Search for a given number using linear search.
- Print all array elements in reverse order.
- Find the second largest distinct element in an array.
- Find how many times a particular number appears in an array.
- Create a String containing your name and print its length.
- Convert a String into uppercase and lowercase.
- Reverse a String without using reverse().
- Check whether a given String is a palindrome.
- Count the vowels and consonants in a String.
- Count the number of words in a sentence.
- Compare two strings using equals().
- Remove leading and trailing spaces using trim().
- 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.