For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Java's string arrays exhibit a rigid size structure, implying that direct removal of elements is not a straightforward process. The mechanism to eliminate an element necessitates the creation of a fresh array, deliberately excluding the targeted element, whilst mirroring the remaining constituents. An alternative option worth considering is the utilization of an ArrayList, which comes equipped with user-friendly methodologies for element elimination. This article serves as an exploration into the intricate world of string array in Java. Embark with us as we dissect and delve into its multifaceted aspects, encompassing declaration, initialization, and iteration. We will also traverse through the processes of element addition, searching, and sorting, along with conversion techniques to and from string arrays.
A string array is an ordered collection of strings where each element is assigned an index starting from 0. It typically has a fixed size, meaning that once you declare and initialize a string array, its length remains constant. However, you can modify the values of individual elements within the array. Let’s explore array in Java with examples.
1. One-Dimensional Array: This linear data structure contains elements of the same data type in a row or column. One index value accesses it. One-dimensional arrays cannot be dynamically resized after declaration.
2. Two-dimensional arrays are arrays of arrays. It's tabular data. Two indices—row and column access it. Two-dimensional arrays can include any data type, including additional arrays.
3. Multi-Dimensional Array: It is considered an array with more than two dimensions. It represents sophisticated data structures by extending the two-dimensional array to higher dimensions. Multiple indices, each representing a dimension, access it.
Java enables arrays of different data types, like objects and primitives. The data structure determines the array type. Java arrays store and retrieve data efficiently.
To declare a string array, you use the following syntax: `String[] arrayName;`. This line of code declares a string array named `arrayName` without specifying its size. It creates a variable that can hold a reference to a string array.
- How to Declare String Array in Java Without Size?
To declare a string array without specifying its size, you can use the following syntax: `String[] arrayName = new String[]{};`. This code initializes an empty string array named `arrayName`. This approach is useful when you want to dynamically allocate the size of the array later.
To initialize a string array with specific values, you can use the following syntax: `String[] arrayName = {"value1", "value2", "value3"};`. This line of code initializes a string array named `arrayName` with three elements: "value1", "value2", and "value3". You can assign any desired values to the array during initialization.
- How to Get First Element of String Array in Java?
To retrieve the first element of a string array, you can use the following syntax: `String firstElement = arrayName[0];`. This code assigns the value of the first element in `arrayName` to the variable `firstElement`. Array elements are accessed using their index, starting from 0.
Example:
Output:
Explanation:
In this example, we declare and initialize a string array named `arrayName` with three elements. We then retrieve the first element using `arrayName[0]` and assign it to the `firstElement` variable. Finally, we print the value of `firstElement`, which is "apple".
To iterate over the elements of a string array, you can use a for-each loop. This loop simplifies the process of accessing each element without worrying about the array's length.
Example:
Output:
Explanation:
In this example, we declare and initialize a string array named `arrayName` with three elements. We use a for-each loop to iterate over each element in the array and print its value. The loop automatically iterates over each element, eliminating the need for a separate index variable.
There are several approaches to adding elements to a string array in Java.
- Using Pre-Allocation of the Array:
If you know the number of elements in advance, you can pre-
allocate the array and assign values to each element using a loop.
Example:
Output:
No output, but the array `arrayName` is initialized with the values: ["value0", "value1", "value2"].
Explanation:
In this example, we declare an integer variable `size` and initialize it with the desired number of elements. We create a string array named `arrayName` with the specified size. Then, using a for loop, we assign values to each element based on the loop index.
- Using ArrayList:
You can use the ArrayList class to dynamically add elements and then convert it into a string array.
Example:
Output:
No output, but the array `arrayName` is initialized with the values: ["value1", "value2"].
Explanation:
In this example, we create an ArrayList named `list` and add elements to it using the `add()` method. Then, we convert the ArrayList to a string array using the `toArray()` method, which takes an empty string array as an argument.
- By Creating a New Array:
To add elements to an existing string array, you can create a new array with a larger size and copy the existing elements along with the new ones.
Example:
Output:
No output, but the array `arrayName` is modified to include the new value: ["value0", "value1", "value2", "newValue"].
Explanation:
In this example, we have an input string inputString with whitespace-separated values. We use the split() method with the regular expression pattern "\\s+" to split the string into an array of substrings. The pattern matches one or more whitespace characters, effectively separating the string into individual elements. Although there is no direct output, the array arrayName is initialized with the values: ["apple", "banana", "orange"]. This array can now be accessed and manipulated further in your Java program.
To search for a specific element in a string array, you can use a loop to iterate over each element and compare it with the desired value.
Example:
Output:
Explanation:
In this example, we have a string array named `arrayName` with three elements. We define the `targetValue` variable to store the element we want to search for, which is "banana" in this case. We use a for-each loop to iterate over each element in the array. Inside the loop, we compare each element with the `targetValue` using the `equals()` method. If a match is found, we set the `found` variable to true and break out of the loop. Finally, we check the value of `found` to determine if the `targetValue` was found in the array.
To sort the elements of a string array in alphabetical order, you can use the `Arrays.sort()` method.
Example:
```java
String[] arrayName = {"orange", "apple", "banana"};
Arrays.sort(arrayName);
for (String element : arrayName) {
System.out.println(element);
}
```
Output:
Explanation:
In this example, we have a string array named `arrayName` with three elements. We use the `Arrays.sort()` method to sort the array in ascending order. Then, we iterate over the sorted array using a for-each loop and print each element. As a result, the elements are displayed in alphabetical order.
There are multiple ways to convert a string array to a single string.
- Using the `toString()` Method:
You can use the `Arrays.toString()` method to convert a string array to a string representation.
Example:
```java
String[] arrayName = {"apple", "banana", "orange"};
String arrayAsString = Arrays.toString(arrayName);
System.out.println(arrayAsString);
```
Output:
Explanation:
In this example, we have a string array named `arrayName` with three elements. We use the `Arrays.toString()` method to convert the array to a string representation. The resulting string includes the elements of the array enclosed in square brackets, separated by commas.
- Using `StringBuilder.append()` Method:
You can iterate over the elements of a string array and append them to a StringBuilder object.
Example:
```java
String[] arrayName = {"apple", "banana", "orange"};
StringBuilder sb = new StringBuilder();
for (String element : arrayName) {
sb.append(element).append(" ");
}
String arrayAsString = sb.toString().trim();
System.out.println(arrayAsString);
```
Output:
Explanation:
In this example, we have a string array named `arrayName` with three elements. We create a StringBuilder object `sb` and iterate over each element of the array. For each element, we append it to the StringBuilder, along with a space. After iterating over all elements, we convert the StringBuilder to a string using the `toString()` method. Finally, we trim the resulting string to remove any leading or trailing whitespace.
- Using Join Operation:
You can use the `String.join()` method to concatenate the elements of a string array with a delimiter.
Example:
```java
String[] arrayName = {"apple", "banana", "orange"};
String arrayAsString = String.join(", ", arrayName);
System.out.println(arrayAsString);
```
Output:
No output, but the array `arrayName` is initialized with the values: ["value0", "value1", "value2"].
Explanation:
In this example, we have a string array named `arrayName` with three elements. We use the `String.join()` method to concatenate the elements of the array, using a comma followed by a space as the delimiter. The resulting string contains the elements of the array separated by the specified delimiter.
To convert a string to a string array, you can use the `split()` method or regular expression patterns.
- Using Split Operation:
You can split a string into an array of substrings based on a delimiter using the `split()` method.
Example:
```java
String inputString = "apple, banana, orange";
String[] arrayName = inputString.split(", ");
```
Output:
No output, but the array `arrayName` is initialized with the values: ["apple", "banana", "orange"].
Explanation:
In this example, we have an input string `inputString` containing comma-separated values. We use the `split()` method with `", "` as the delimiter to split the string into an array of substrings. The resulting array, `arrayName`, contains the individual elements.
- Using Regex Pattern:
You can split a string into an array of substrings based on a more complex pattern using regular expressions.
Example:
```java
String inputString = "apple banana orange";
String[] arrayName = inputString.split("\\s+");
```
Output:
No output, but the array `arrayName` is initialized with the values: ["apple", "banana", "orange"].
Explanation:
In this example, we have an input string `inputString` with whitespace-separated values. We use the `split()` method with the regular expression pattern `"\\s+"` to split the string into an array of substrings. The pattern matches one or more whitespace characters, effectively separating the string into individual elements.
1. How to print string array in Java using for loop: Iterate over each element of the string array using a for loop and print each element.
2. How to add values to a string array using a for loop?
Use a for loop to iterate over a set of values and assign them to elements of the string array.
3. How to add multiple values to a string array in Java?
Assign multiple values directly to the elements of the string array using the assignment operator or by initializing the array with the desired values.
Remember, these concepts provide a foundation for performing specific operations on string arrays in Java.
This article has discussed many characteristics of string arrays in Java. We looked at string array declaration and initialization, iterating through their elements, adding elements in various ways, searching for certain values, sorting the arrays, and converting string arrays to strings and vice versa. Understanding and using these concepts will allow you to work with string arrays more efficiently in your Java projects, making your code more versatile and effective.
Q1. How do I check if a string array is empty in Java?
You can check if a string array is empty by comparing its length to 0. If arrayName.length equals 0, the array is empty.
Q2. How can I remove an element from a string array in Java?
String arrays in Java have a fixed size; therefore, you cannot remove elements directly. To delete an element, create a new array sans the desired element and duplicate the remaining items. Consider using ArrayList, which has convenient methods for removing elements.
Q3. How do I convert a string array to lowercase in Java?
To convert all the elements of a string array to lowercase, you can use a loop to iterate over each element and apply the toLowerCase() method.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.