In Java, the Array stands out as a fundamental and widely utilized data structure. It is highly favored among programmers for its efficiency and effectiveness. Essentially, an Array is a grouping of elements of the same data type, stored in a contiguous memory location.
What is a String Array?
A String Array is a collection of a specific quantity of String elements. A String represents a series of characters. Typically, a string is a fixed object, indicating that its content cannot be altered. The behavior of a String Array is akin to that of other Array data types.
Just like arrays, a string array can store a predetermined set of elements. This data structure is indexed, beginning from position 0. The initial element is stored in Index 0, the second element in Index 1, and the pattern continues accordingly.
The primary function {Public static void main[ String args]; } in Java is also a 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:
There are two types of Array declaration - one where the size is specified, and the other where the size is not specified. To declare a String Array, we can use the following syntax:
String[] stringArray1 //Declaration of the String Array without specifying the size
String[] stringArray2 = new String[2]; //Declarartion by specifying the size
An alternative method for declaring an array is by using the syntax String strArray, but it is advised to use the previously mentioned approaches as they are more efficient and preferred.
Initialization:
Initializing a String Array is a straightforward process. The following code snippet demonstrates how to initialize a 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";
The initialization of a String Array can be achieved using any of the three methods mentioned above, resulting in the array having identical values.
The third approach is the fixed-size method. With this technique, the index value can be determined by using the formula (arraylength - 1) when accessing elements beyond index 2 in the Array mentioned earlier. If attempted, it will result in the Java.lang.ArrayIndexOutOfBoundsException exception being thrown.
Let's examine a demonstration of a String Array to illustrate its functionality:
Iteration of String Array
Iterating through a String Array can be achieved using both the for loop and the foreach loop. Below is an example demonstrating this concept:
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 approach, we begin with an Array that is larger in size. For instance, if we need to accommodate 10 elements, we would initialize an Array with a size of 20. This method simplifies the process of expanding the Array elements.
Take a look at the following example demonstrating how to insert elements into an array that has been pre-allocated.
// 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]
In the example provided, two items have been inserted into an Array that was allocated in advance.
Using ArrayList:
The ArrayList is an intriguing data structure found within the Java collection framework. It provides a convenient way to append elements to a String Array by utilizing an ArrayList as a temporary intermediary structure.
Let's examine the following example to learn how to append elements to a String Array using an 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 technique, we are going to generate a fresh Array that has a greater capacity compared to the original Array to hold the elements. All the elements will be transferred to this newly created Array. Let's look at an illustration:
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]
The following demonstrates the process of appending items to a String Array. Now, let's delve into the techniques for searching and arranging elements within a String Array.
Searching in String Array
To search for a specific string within an array of strings, a for loop can be employed. Let's illustrate this with an example below:
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 previous instance, a boolean variable x was set to false, along with an index variable for string iteration. Additionally, a local variable named s of type String was declared for the search operation. The loop will terminate immediately upon finding the specified string by utilizing the break keyword.
Sorting in String Array
Arranging elements in a String array is a straightforward process, similar to sorting a regular array. The sorting operation involves utilizing the sort method to arrange the elements within the array. When compared to searching, sorting is a simpler task.
Take a look at the following example demonstrating how to sort an array of strings:
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]
In the example provided, we observe that the elements of a String Array are arranged in ascending order by utilizing the sort method.
It is also possible to transform a String Array into various data structures like List, integer Array, ArrayList, and others, as well as converting them back and forth.
Manipulating String Arrays
Arrays of strings offer a range of functions for manipulation, like inserting, deleting, and changing elements. It's crucial to bear in mind that in Java, arrays have a set size upon creation. Consequently, if you require dynamic functionalities such as adding or removing elements, alternative data structures like ArrayList should be considered.
Common Use Cases
String arrays find application in numerous scenarios across Java programming. Some common use cases include:
- Storing and Processing Data: String arrays are often used to store and process lists of strings, such as names, addresses, or any textual data.
- Command-Line Arguments: In Java applications, string arrays are employed to handle command-line arguments passed to the main method.
- Data Structures: String arrays serve as building blocks for implementing more complex data structures like stacks, queues, and hash tables.
Conclusion
To summarize, in Java, string arrays provide a flexible way to handle sets of text data. Familiarity with their structure, setup, handling, and typical applications is essential for Java programmers. Armed with this information, you are ready to leverage the capabilities of string arrays in Java assignments, boosting effectiveness and output in your coding pursuits.
String Array in Java MCQ
- Which of the following is a true statement about initializing a String Array in Java?
- String arrays can only be initialized at the time of declaration.
- String arrays cannot be resized once they are created.
- String arrays can store both primitive and object types.
- String arrays can be declared and initialized without specifying the size.
Explanation: String arrays in Java can be initialized inline without specifying the size, as shown in String strAr2 = {"Ani", "Sam", "Joe"};. Unlike primitive types, String arrays can only store objects of the String class.
- Which method is used to convert a String array to an ArrayList in Java?
- Arrays.toList
- Arrays.asList
- ArrayList.toArray
- List.asArray
The Arrays.asList function is employed to transform a String array into a List, particularly an ArrayList. This function accepts an array and produces a list of a constant size that is supported by the given array.
What will the code snippet output?
String[] strArray = {"Ani", "Sam", "Joe"};
System.out.println(Arrays.toString(strArray));
- Ani, Sam, Joe
- [Ani, Sam, Joe]
- {Ani, Sam, Joe}
- (Ani, Sam, Joe)
Explanation: The Arrays.toString method returns a string representation of the array, with elements enclosed in square brackets and separated by commas. Therefore, the output is [Ani, Sam, Joe].
- When using the Arrays.sort method on a String array, how are the elements sorted by default?
- In reverse lexicographical order
- By their length
- In lexicographical (alphabetical) order
- By their hash code values
Explanation: The Arrays.sort method sorts String array elements in lexicographical (alphabetical) order by default. This means the strings are sorted based on the Unicode values of their characters.
- Which of the following statements is true regarding the searching of elements in a String array?
- The Arrays.binarySearch method can be used on any String array without sorting it first.
- Searching in an unsorted String array using Arrays.binarySearch will return a correct index.
- The for loop must be used to search for an element in an unsorted String array.
- String arrays cannot be searched once initialized.
The Arrays.binarySearch function necessitates the array to be in sorted order for accurate index retrieval. In cases of unsorted arrays, a common approach involves utilizing a for loop to manually search for an element by iterating over the array.