A String Array in Java is an array that stores string values. The string is nothing but an object representing a sequence of char values. Strings are immutable in Java, this means their values cannot be modified once created.
When we create an array of type String in Java, it is called a String Array in Java. In this article, we will learn the concepts of String Arrays in Java including declaration, initialization, iteration, searching, sorting, and converting a String Array to a single string.
To use a String array, first, we need to declare and initialize it. There are more than one way available to do so.
Declaration of String Arrays
A String array can be declared with or without specifying its size. Below is the example:
String[] str0; // declaration without size String[] str1 = new String[4]; //declaration with size
In the above example,
- str0 is declared without specifying its size.
str1
is declared with a size of 4.
We can use both of these ways to declare String array in Java.
Initialization of String Arrays
Declaring and Initializing Together
In this method, we are declaring the values at the same line.
String[] arr0 = new String[]{"Apple", "Banana", "Orange"};
This method is the short form of the first method i.e. initialize the array at the time of declaration.
String[] arr1={"Apple","Banana","Orange"};
Declaring First, Initializing Later
In this method, we are declaring the String array with size first and after that we are storing data into it.
String[] arr2=new String[3];
arr2[0]="Apple";
arr2[1]="Banana";
arr2[2]="Orange";
Iterating Over String Arrays
To iterate through a String array we can use a looping statement. So generally we have three ways to iterate over a string array.
Example:
Java
// Java program to demonstrate various
// methods to iterate over a string array
public class GFG {
public static void main(String[] args) {
String[] arr = { "Apple", "Banana", "Orange" };
// First method
for (String i : arr) {
System.out.print(i + " ");
}
System.out.println();
// Second method
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
// Third method
int i = 0;
while (i < arr.length) {
System.out.print(arr[i] + " ");
i++;
}
System.out.println();
}
}
OutputApple Banana Orange
Apple Banana Orange
Apple Banana Orange
Searching in a String Array
To find an element from the String Array we can use a simple linear search algorithm.
Example:
Java
// Java program to perform the searching
// operation on a string array
public class GFG {
public static void main(String[] args) {
// Initialize a String array with some elements
String[] arr = { "Apple", "Banana", "Orange" };
// Key to search in the array
String k = "Banana";
// Flag to track if the key is found
boolean f = false;
// Iterate over the array to search for the key
for (int i = 0; i < arr.length; i++) {
// Check if the current element matches the key
if (arr[i] == k) {
// If found, print the index and set the flag to true
System.out.println("Available at index " + i);
f = true;
}
}
// If the key is not found, print "Not found"
if (f == false) {
System.out.println("Not found");
}
}
}
OutputAvailable at index 1
Sorting a String Array
Sorting a String array means to sort the elements in lexicographical (dictionary) order. We can use the built-in sort() method to do so and we can also write our own sorting algorithm from scratch.
Java
// Java program to perform the sorting
// operation on a string array
import java.util.Arrays;
class GFG {
public static void main(String[] args) {
String[] arr = { "Apple", "Cat", "Ball",
"Cartoon", "Banana", "Avocado" };
// sorting the String array
Arrays.sort(arr);
for (String i : arr) {
System.out.print(i + " ");
}
}
}
OutputApple Avocado Ball Banana Cartoon Cat
Converting String Array to String
Using Arrays.toString()
To convert from String array to String, we can use a Arrays.toString() method or a custom approach.
Example:
Java
// Java program to demonstrate the
// conversion of String array to String
import java.util.Arrays;
class GFG {
public static void main(String[] args) {
String[] arr
= { "She", "is", "a", "good", "girl" };
// converting to string
String s = Arrays.toString(arr);
System.out.println(s);
}
}
Output[She, is, a, good, girl]
Explanation: Here, the String array is converted into a string, but one thing to note here is that comma(,) and brackets are also present in the string.
Custom Conversion Without Brackets and Commas
To create a string from a string array without comma(,) and brackets , we can use the below code snippet.
Java
// Java program to demonstrate the
// conversion of String array to String
public class GFG {
public static void main(String[] args) {
// Initialize a String array with some elements
String[] arr = { "She", "is", "a", "good", "girl" };
// Create a StringBuilder to build the resulting string
StringBuilder sb = new StringBuilder();
// Append the first element of the array to the StringBuilder
sb.append(arr[0]);
// Loop through the remaining elements in the array
for (int i = 1; i < arr.length; i++) {
// Append each element with a space in between
sb.append(" " + arr[i]);
}
// Convert the StringBuilder content into a String
String s = sb.toString();
System.out.println(s);
}
}
Similar Reads
String Class in Java
A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
7 min read
Arrays.toString() in Java with Examples
The Arrays.toString() method belongs to the Arrays class in Java. It converts an array into its string representation consisting of a list of the array's elements. In the case of an Object Array, if the array contains other arrays as elements, their string representation shows memory addresses inste
3 min read
StringBuffer Class in Java
The StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters.Features of StringBuffer ClassThe key features of StringBuffer c
11 min read
Compare two Strings in Java
String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.Example:To compare two strings in
4 min read
String to int in Java
Converting a String to an int in Java can be done using methods provided in the Integer class, such as Integer.parseInt() or Integer.valueOf() methods. Example:The most common method to convert a string to a primitive int is Integer.parseInt(). It throws a NumberFormatException if the string contain
2 min read
String in Switch Case in Java
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated
3 min read
Java Strings
In Java, a String is the type of object that can store a sequence of characters enclosed by double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowi
9 min read
Integer toString() in Java
The java.lang.Integer.toString() is an inbuilt method in Java which is used to return the String object representing this Integer's value. Syntax : public static String toString() Parameters: The method does not accept any parameters. Return Value:The method returns the string object of the particul
5 min read
String Constant Pool in Java
In Java, Strings are the type of objects that can store the character of values. A string acts the same as an array of characters in Java. Memory allocation is not possible without String Constant Pool. In this article, we will learn about Java String Constant Pool.What is Java String Pool?A Java St
5 min read
Java String charAt() Method
String charAt() method in Java returns the character at the specified index in a string. The Index of the first character in a string is 0, the second character is 1, and so on. The index value should lie between 0 and length() - 1.If the index value is greater than or equal to the string length or
2 min read