Declaration
To use a string array in Java, we first need to declare it. The declaration of a string array involves specifying the data type (String) followed by square brackets [] & the name of the array.
The general syntax for declaring a string array is:
String[] arrayName;
For example, let's declare a string array called "fruits":
String[] fruits;
This declaration creates a reference variable named "fruits" that can hold an array of strings. At this point, the array is not initialized & does not have any memory allocated to it.
We can also declare a string array & initialize it in a single line.
For example:
String[] cars = new String[5];
In this case, we declare a string array named "cars" and initialize it with a size of 5. The "new" keyword allocates memory for the array, and the number inside the square brackets specifies the number of elements it can hold.
It's important to note that the size of an array is fixed & cannot be changed once it is declared. If you need a more dynamic structure that can grow or shrink in size, consider using other data structures like ArrayList.
When declaring a string array, it's crucial to choose a meaningful and descriptive name that reflects its purpose or content. This enhances code readability and makes it easier to understand the array's role in the program.
Initialization
After declaring a string array, the next step is to initialize it with values. There are different ways to initialize a string array in Java. Let's discuss a few common approaches.
1. Initialization with explicit values: You can initialize a string array by explicitly specifying the values at the time of declaration. For example:
String[] colors = {"Red", "Green", "Blue", "Yellow"};
In this case, we declare a string array named "colors" & initialize it with four string values: "Red", "Green", "Blue", & "Yellow". The values are enclosed in curly braces {} & separated by commas.
2. Initialization with default values: When you declare a string array without explicitly initializing it, Java automatically initializes all elements to their default value, which is null for string arrays. For example:
String[] names = new String[3];
In this case, we declare a string array named "names" with a size of 3. Since we haven't explicitly initialized it, all elements of the array will be set to null.
3. Initialization with user input: You can initialize a string array by taking input from the user at runtime. For example:
Scanner scanner = new Scanner(System.in);
String[] fruits = new String[3];
for (int i = 0; i < fruits.length; i++) {
System.out.print("Enter fruit " + (i + 1) + ": ");
fruits[i] = scanner.nextLine();
}
In this example, we declare a string array named "fruits" with a size of 3. We then use a for loop to iterate over the array & prompt the user to enter a fruit name for each element. The user input is stored in the corresponding array element using the scanner.nextLine() method.
Note: Proper initialization of a string array is crucial to ensure that it holds the desired values before using it in your program. Depending on your requirements, you can choose the most suitable initialization approach.
Iteration of String Array
Once a string array is initialized, you can access and manipulate its elements through iteration. Iteration allows you to traverse through each array element and perform operations on them. Let's take a look at different ways to iterate over a string array in Java.
1. Using a for loop: The most common way to iterate over a string array is by using a for loop. For example:
public class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange", "Mango"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Apple
Banana
Orange
Mango
In this example, we have a string array named "fruits" containing four elements. We use a for loop to iterate over the array. The loop starts from index 0 and continues until the last index (fruits.length-1). Inside the loop, we can access each element using index i and perform desired operations, such as printing the element.
2. Using an enhanced for loop (for-each loop): Java provides an enhanced version of the for loop, also known as the for-each loop, which simplifies the iteration process. For example:
public class Main {
public static void main(String[] args) {
String[] cars = {"Ferrari", "Lamborghini", "Porsche", "BMW"};
for (String car : cars) {
System.out.println(car);
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Ferrari
Lamborghini
Porsche
BMW
In this case, we have a string array named "cars." We use the enhanced for loop to iterate over the array. The loop automatically traverses through each element of the array, and in each iteration, the current element is assigned to the variable "car." We can directly use the variable to access the element within the loop body.
3. Using the Arrays.toString() method: If you want to print the entire contents of a string array, you can use the Arrays.toString() method from the java.util.Arrays class. For example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = {"Rahul", "Nikunj", "Harsh", "Vicky"};
System.out.println(Arrays.toString(names));
}
}

You can also try this code with Online Java Compiler
Run Code
This code will output:
[Rahul, Nikunj, Harsh, Vicky]
The Arrays.toString() method returns a string representation of the array, enclosing the elements in square brackets & separating them with commas.
Note: Iterating over a string array helps you process each element individually, perform operations, or extract specific information from the array.
Adding Elements to a String Array
Once a string array is created, you may need to add new elements to it. However, it's important to note that arrays in Java have a fixed size, which means you cannot directly add elements to an existing array. Instead, you have a few options to achieve this:
1. Using Pre-Allocation of the Array: If you know the maximum number of elements you'll need in the array, you can pre-allocate the array with that size and then add elements to it. For example:
public class Main {
public static void main(String[] args) {
String[] fruits = new String[5];
int count = 0;
fruits[count++] = "Apple";
fruits[count++] = "Banana";
fruits[count++] = "Orange";
// Print the array elements
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Apple
Banana
Orange
null
null
In this approach, we declare a string array named "fruits" with a size of 5. We also create a variable "count" to keep track of the number of elements added to the array. We can then add elements to the array using the index and increment the count accordingly.
2. Using the ArrayList: If you don't know the exact number of elements in advance or if you need a more dynamic structure, you can use the ArrayList class from the java.util package. ArrayList provides a resizable array-like data structure. For example:
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
In this case, we create an ArrayList named "colors" to store strings. We can add elements to the ArrayList using the add() method. The ArrayList automatically resizes itself as needed to accommodate new elements.
3. Creating a New Array: If you need to add elements to an existing array and create a new array with the combined elements, you can do so by creating a new array and copying the elements from the original array. For example:
String[] originalArray = {"Apple", "Banana"};
String[] newArray = new String[4];
// Copy elements from original array to new array
System.arraycopy(originalArray, 0, newArray, 0, originalArray.length);
// Add new elements to the new array
newArray[2] = "Orange";
newArray[3] = "Mango";
In this approach, we have an existing string array named "originalArray" with two elements. We create a new string array named "newArray" with a size of 4. We use the System.arraycopy() method to copy the elements from the original array to the new array. Then, we can add new elements to the new array using the appropriate indices.
Sorting in String Array
Sorting is a common operation performed on arrays, including string arrays. Java provides built-in methods to sort arrays in ascending or descending order. Let's discuss how to sort a string array in Java:
1. Using the Arrays.sort() method: Java's Arrays class offers a convenient method called sort() that sorts the elements of an array in ascending order. For example :
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] fruits = {"Banana", "Orange", "Apple", "Mango"};
Arrays.sort(fruits);
System.out.println(Arrays.toString(fruits));
}
}

You can also try this code with Online Java Compiler
Run Code
Output
[Apple, Banana, Mango, Orange]
In this code snippet, we have a string array named "fruits" with four elements. We use the Arrays.sort() method to sort the array in ascending order. The sort() method modifies the original array itself. Finally, we print the sorted array using Arrays.toString().
2. Sorting in descending order: To sort a string array in descending order, you can use the Arrays.sort() method in combination with a custom comparator. For example :
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
String[] cars = {"Ferrari", "Lamborghini", "Porsche", "BMW"};
Arrays.sort(cars, Collections.reverseOrder());
System.out.println(Arrays.toString(cars));
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
[Porsche, Lamborghini, Ferrari, BMW]
In this case, we have a string array named "cars". We use the Arrays.sort() method along with the Collections.reverseOrder() comparator to sort the array in descending order. The reverseOrder() comparator reverses the natural ordering of the elements.
3. Sorting a portion of the array: If you want to sort only a specific portion of the string array, you can use the Arrays.sort() method with the starting and ending indices. For example :
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = {"Rahul", "Gaurav", "Sinki", "Mehak", "Nikunj"};
Arrays.sort(names, 1, 4);
System.out.println(Arrays.toString(names));
}
}

You can also try this code with Online Java Compiler
Run Code
Output
[Rahul, Gaurav, Sinki, Mehak, Nikunj]
In this example, we have a string array named "names". We use the Arrays.sort() method with the starting index (1) and the ending index (4) to sort only the subarray from index 1 to 3 (inclusive). The rest of the array remains unchanged.
When to use this: Sorting a string array can be useful when you need to process the elements in a specific order or when you want to perform operations that require sorted data. Java's built-in sorting methods make it easy to sort string arrays efficiently.
Manipulating String Arrays
String arrays provide various methods and techniques to manipulate and modify the elements within the array. Let's discuss some common operations you can perform on string arrays.
1. Accessing elements: You can access individual elements of a string array using the index. The index starts from 0 for the first element and goes up to (array length - 1) for the last element. For example:
public class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange"};
String firstFruit = fruits[0];
String secondFruit = fruits[1];
System.out.println(firstFruit);
System.out.println(secondFruit);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Apple
Banana
2. Modifying elements: You can modify the value of an element in a string array by assigning a new value to the specific index. For example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] colors = {"Red", "Green", "Blue"};
colors[1] = "Yellow";
System.out.println(Arrays.toString(colors));
}
}

You can also try this code with Online Java Compiler
Run Code
Output
[Red, Yellow, Blue]
3. Finding the length of the array: To determine the number of elements in a string array, you can use the length property. For example:
public class Main {
public static void main(String[] args) {
String[] names = {"Sinki", "Mehak", "Vaibhav"};
int length = names.length;
System.out.println(length);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
3
4. Copying arrays: You can create a copy of a string array using the Arrays.copyOf() method. For example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] originalArray = {"A", "B", "C"};
String[] copiedArray = Arrays.copyOf(originalArray, originalArray.length);
System.out.println(Arrays.toString(copiedArray));
}
}

You can also try this code with Online Java Compiler
Run Code
Output
[A, B, C]
5. Converting array to string: If you want to convert a string array to a single string, you can use the Arrays.toString() method. For example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] words = {"Hello", "World"};
String arrayString = Arrays.toString(words);
System.out.println(arrayString);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
[Hello, World]
6. Checking for equality: To compare two string arrays for equality, you can use the Arrays.equals() method. For example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] array1 = {"A", "B", "C"};
String[] array2 = {"A", "B", "C"};
boolean isEqual = Arrays.equals(array1, array2);
System.out.println(isEqual);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
true
Common Use Cases
String arrays have various practical applications in Java programming. Some of the common use cases where string arrays can be useful are:
1. Storing and processing a list of names: String arrays are commonly used to store and manipulate a list of names. For example, you might have an array of student names in a school management system or an array of employee names in a company database. For example :
public class Main {
public static void main(String[] args) {
String[] students = {"Rinki", "Pallavi", "Gaurav", "Harsh"};
// Process student names
for (String student : students) {
System.out.println("Student: " + student);
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Student: Rinki
Student: Pallavi
Student: Gaurav
Student: Harsh
2. Handling user input: String arrays can be used to store and process user input. For instance, you might prompt the user to enter multiple values and store them in a string array for further processing. For example :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] inputs = new String[3];
for (int i = 0; i < inputs.length; i++) {
System.out.print("Enter value " + (i + 1) + ": ");
inputs[i] = scanner.nextLine();
}
// Process user inputs
for (String input : inputs) {
System.out.println("Input: " + input);
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Enter value 1: Hello
Enter value 2: World
Enter value 3: Java
Input: Hello
Input: World
Input: Java
3. Storing configuration or settings: String arrays can be used to store configuration or settings for an application. For example, you might have an array of database connection strings or an array of file paths. For example :
public class Main {
public static void main(String[] args) {
String[] configSettings = {
"database.url=jdbc:mysql://localhost:3306/mydb",
"database.username=admin",
"database.password=password123"
};
// Process configuration settings
for (String setting : configSettings) {
String[] parts = setting.split("=");
String key = parts[0];
String value = parts[1];
System.out.println(key + ": " + value);
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
database.url: jdbc:mysql://localhost:3306/mydb
database.username: admin
database.password: password123
4. Implementing command-line arguments: String arrays are often used to handle command-line arguments passed to a Java program. The main method of a Java program receives an array of strings representing the command-line arguments. For example :
public class Main {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Command-line arguments:");
for (String arg : args) {
System.out.println(arg);
}
} else {
System.out.println("No command-line arguments provided.");
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
java Main Hello World 123
Frequently Asked Questions
Can I change the size of a string array after it is declared?
No, the size of an array in Java is fixed and cannot be changed once it is declared. If you need a resizable array-like structure, you can use the ArrayList class.
How do I convert a string array to a string in Java?
You can use the Arrays.toString() method to convert a string array to a string representation. For example: String arrayString = Arrays.toString(myArray);
Can I sort a string array in descending order?
Yes, you can sort a string array in descending order using the Arrays.sort() method in combination with the Collections.reverseOrder() comparator. For example: Arrays.sort(myArray, Collections.reverseOrder());
Conclusion
In this article, we have discussed the fundamentals of string arrays in Java. We learned how to declare, initialize, and iterate over string arrays. We also explained techniques for adding elements to string arrays, sorting them, and manipulating their contents. Moreover, we discussed common use cases where string arrays prove valuable.
You can also check out our other blogs on Code360.