Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
Now Reading
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
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.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...