An Array is an essential and most used data structure in Java. It is one of the most used data structure by programmers due to its efficient and productive nature; The Array is a collection of similar data type elements. It uses a contiguous memory location to store the elements.
What is a String Array?
A String Array is an Array of a fixed number of String values. A String is a sequence of characters. Generally, a string is an immutable object, which means the value of the string can not be changed. The String Array works similarly to other data types of Array.
Similar to arrays, in string array only a fixed set of elements can be stored. It is an index-based data structure, which starts from the 0th position. The first element will take place in Index 0, and the 2nd element will take place in Index 1, and so on.
The main method {Public static void main[ String [] args]; } in Java is also an String Array.
Consider the below points about the String Array:
- It is an object of the Array.
- It can be declared by the two methods; by specifying the size or without specifying the size.
- It can be initialized either at the time of declaration or by populating the values after the declaration.
- The elements can be added to a String Array after declaring it.
- The String Array can be iterated using the for loop.
- The searching and sorting operation can be performed on the String Array.
Declaration:
The Array declaration is of two types, either we can specify the size of the Array or without specifying the size of the Array. A String Array can be declared as follows:
- String[] stringArray1 //Declaration of the String Array without specifying the size
- String[] stringArray2 = new String[2]; //Declarartion by specifying the size
Another way of declaring the Array is String strArray[], but the above-specified methods are more efficient and recommended.
Initialization:
The String Array can be initialized easily. Below is the initialization of the String Array:
- 1. String[] strAr1=new String[] {“Ani”, “Sam”, “Joe”}; //inline initialization
- 2. String[] strAr2 = {“Ani”, “Sam”, ” Joe”};
- 3. String[] strAr3= new String[3]; //Initialization after declaration with specific size
- strAr3[0]= “Ani”;
- strAr3[1]= “Sam”;
- strAr3[2]= “Joe”;
All of the above three ways are used to initialize the String Array and have the same value.
The 3rd method is a specific size method. In this, the value of the index can be found using the ( arraylength – 1) formula if we want to access the elements more than the index 2 in the above Array. It will throw the Java.lang.ArrayIndexOutOfBoundsException exception.
Let’s see an example of String Array to demonstrate it’s behavior:
Iteration of String Array
The String Array can be iterated using the for and foreach loop. Consider the below code:
- String[] strAr = {“Ani”, “Sam”, “Joe”};
- for (int i=0; i<StrAr.length; i++)
- {
- System.out.println(strAr[i]);
- }
- for ( String str: strAr)
- {
- Sytem.out.println(str);
- }
Adding Elements to a String Array
We can easily add the elements to the String Array just like other data types. It can be done using the following three methods:
- Using Pre-Allocation of the Array
- Using the Array List
- By creating a new Array
let’s understand the above methods:
Using Pre-Allocation of the Array:
In this method, we already have an Array of larger size. For example, if we require to store the 10 elements, then we will create an Array of size 20. It is the easiest way to expand the Array elements.
Consider the below example to add elements in a pre-allocated array.
- // Java Program to add elements in a pre-allocated Array
- import java.util.Arrays;
- public class StringArrayDemo {
- public static void main(String[] args) {
- String[] sa = new String[7]; // Creating a new Array of Size 7
- sa[0] = “A”; // Adding Array elements
- sa[1] = “B”;
- sa[2] = “C”;
- sa[3] = “D”;
- sa[4] = “E”;
- System.out.println(“Original Array Elements:” + Arrays.toString(sa));
- int numberOfItems = 5;
- String newItem = “F”; // Expanding Array Elements Later
- String newItem2 =”G”;
- sa[numberOfItems++] = newItem;
- sa[numberOfItems++] = newItem2;
- System.out.println(“Array after adding two elements:” +
- Arrays.toString(sa));
- }
- }
Output:
Original Array Elements:[A, B, C, D, E, null, null]
Array after adding two elements:[A, B, C, D, E, F, G]
From the above example, we have added two elements in a pre-allocated Array.
Using ArrayList:
The ArrayList is a fascinating data structure of the Java collection framework. We can easily add elements to a String Array using an ArrayList as an intermediate data structure.
Consider the below example to understand how to add elements to a String Array using ArrayList:
File Name: StringArrayDemo1.java
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- public class StringArrayDemo1 {
- public static void main(String[] args)
- {
- // Defining a String Array
- String sa[] = { “A”, “B”, “C”, “D”, “E”, “F” };
- //
- System.out.println(“Initial Array:\n”
- + Arrays.toString(sa));
- String ne = “G”; // Define new element to add
- List<String>l = new ArrayList<String>(
- Arrays.asList(sa)); // Convert Array to ArrayList
- l.add(ne); // Add new element in ArrayList l
- sa = l.toArray(sa); // Revert Conversion from ArrayList to Array
- // printing the new Array
- System.out.println(“Array with added Value: \n”
- + Arrays.toString(sa)) ;
- }
- }
Output:
Initial Array:
[A, B, C, D, E, F]
Array with added value:
[A, B, C, D, E, F, G]
By Creating a New Array:
In this method, we will create a new Array with a larger size than the initial Array and accommodate the elements in it. We will copy all the elements to the newly added Array. Consider the following example:
File Name: StringArrayDemo2.java
- // Java Program to add elements in a String Array by creating a new Array
- import java.util.Arrays;
- public class StringArrayDemo2 {
- public static void main(String[] args) {
- //Declaring Initial Array
- String[] sa = {“A”, “B”, “C” };
- // Printing the Original Array
- System.out.println(“Initial Array: ” + Arrays.toString(sa));
- int length_Var = sa.length; //Defining the array length variable
- String newElement = “D”; // Defining new element to add
- //define new array with extended length
- String[] newArray = new String[ length_Var + 1 ];
- //Adding all the elements to initial Array
- for (int i=0; i <sa.length; i++)
- {
- newArray[i] = sa [i];
- }
- //Specifying the position of the added elements ( Last)
- newArray[newArray.length- 1] = newElement;
- //make it original and print
- sa = newArray;
- System.out.println(“updated Array: ” + Arrays.toString(sa));
- }
- }
Output:
Initial Array: [A, B, C]
updated Array: [A, B, C, D]
This is how we can add elements to a String Array. Let’s understand how to search and sort elements in String Array.
Searching in String Array
For searching a String from the String Array, for loop is used. Consider the below example:
StringArrayExample.java
- public class StringArrayExample {
- public static void main(String[] args) {
- String[] strArray = { “Ani”, “Sam”, “Joe” };
- boolean x = false; //initializing x to false
- int in = 0; //declaration of index variable
- String s = “Sam”; // String to be searched
- // Iteration of the String Array
- for (int i = 0; i < strArray.length; i++) {
- if(s.equals(strArray[i])) {
- in = i; x = true; break;
- }
- }
- if(x)
- System.out.println(s +” String is found at index “+in);
- else
- System.out.println(s +” String is not found in the array”);
- }
- }
Output:
Sam String is found at index 1
In the above example, we have initialized a boolean variable x to false and an index variable to iterate through the string. Also, we have declared a local variable String variable s to be searched. Here, the break keyword will exit the loop as soon as the string is found.
Sorting in String Array
The sorting in the String array is quite easy. It is performed like in a traditional array. We use a sort() method to sort the Array elements. Sorting is easier than searching.
Consider the below example to sort a String Array:
File Name: StringArraySorting.java
- //Java Program to sort elements in a String Array
- import java.util.Arrays;
- public class StringArraySorting {
- public static void main(String[] args)
- {
- // Adding String values
- String[] colors = {“Cricket”,”Basketball”,”Football”,”Badminton”,”Tennis”};
- // Print Original values
- System.out.println(“Entered Sports: “+Arrays.toString(colors));
- Arrays.sort(colors); // Sorting Elements
- // Print Sorted Values
- System.out.println(“Sorted Sports: “+Arrays.toString(colors));
- }
- }
Output:
Entered Sports: [Cricket, Basketball, Football, Badminton, Tennis]
Sorted Sports: [Badminton, Basketball, Cricket, Football, Tennis]
From the above example, we can see the elements from a String Array is sorted using the sort() method.
We can also convert String Array to other data structures such as List, int Array, ArrayList, and more and vice-versa.
Manipulating String Arrays
String arrays support various operations for manipulation, including adding, removing, and modifying elements. However, it’s essential to remember that arrays in Java have a fixed size once initialized. Therefore, to perform dynamic operations, such as adding or removing elements, you may need to resort to other data structures like ArrayList.
Leave a Reply