Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is String Array in Java and How it Works?

Last updated on Jul 05,2024 177.3K Views

Aayushi Johari
A technophile with a passion for unraveling the intricate tapestry of the... A technophile with a passion for unraveling the intricate tapestry of the tech world. I've spent over a decade exploring the fascinating world of...

An array is a fundamental and crucial data structure Java programming language. It is highly used by programmers due to its efficient and productive nature. A Java String Array is an object that holds a fixed number of String values. In this tutorial, let us dig a bit deeper and understand the concept of String array in Java.

This article will touch up on following pointers,

Let us get started.

What is a String Array in Java

You must be aware of Java Arrays, it is an object that contains elements of a similar data type. Also, they are stored in a continuous memory location. Strings, on the other hand, is a sequence of character. It is considered as immutable object i.e, the value cannot be changed. java String array works in the same manner. String Array is used to store a fixed number of Strings.

Now, let’s have a look at the implementation of Java string array.

How to Declare A String Array In Java

For implementation ensure you get Java Installed. A string array is declared by the following methods:


String[] stringArray1 //declaring without size
String[] stringArray2 = new String[2]; //declaring with size

The string array can also be declared as String strArray[], but the previously mentioned methods are favoured and recommended. Note that the value of strArray1 is null, while the value of strArray2 is [null, null].

Now let us move ahead and checkout how to initialize a string array,

Initializing A String Array In Java

A string array can be initialized by using:


//inline initialization
String[] stringArray1 = new String[] {"R","S","T"};
String[] stringArray2 = {"R","S","T"};
//initialization after declaration
String[] stringArray3 = new String[3];
stringArray3[0] = "R";
stringArray3[1] = "S";
stringArray3[2] = "T";


All three arrays specified above have the same values.

Since there are only 3 elements in stringArray3, and the index starts from 0, the last index is 3. We could also use the formula (array length – 1) to ascertain the value of the index. On accessing an index greater than 2, an exception will be raised.

Example:


String[] stringArray3 = new String[3];
stringArray3[3] = "U";

 This will throw a java.lang.ArrayIndexOutOfBoundsException.

Initialization of a string array can be done along with the declaration by using the new operator in the syntax:

<strong>String</strong>[] stringArray3 = new <strong>String</strong>[]{“R”,”S”,”T”};

Let us continue with the next topic of this article,

Size Of A String Array

The property length of a string array can be used to determine the number of elements in the Array.

<strong>String</strong>[] stringArray3 = {“R”,”S”,”T”};

System.out.println( stringArray3.length);

Output:

3

Next in this string array in Java article we would how to iterate in a string array

Iterating In A String Array

Iteration over a string array is done by using java for loop, or java for each loop.


String[] strArray3 = {“R”,”S”,”T”};
//iterating all elements in the array
for (int i = 0; i < strArray3.length; i++) {
System.out.print(strArray3[i]);
}

The code starts from index 0, and continues up to length – 1, which is the last element of the array.

Output:

R

S

T

We can also make use of the enhanced for loop provided by Java 5:


//iteration by using the enhanced for loop provided by Java 5 or later
for (String str : strArray3) {
System.out.print(str);
}

Let us move further with this article on String Array In Java,

Searching Through A String Array

In case the user wants to search for a specific value in the string array, for loop is used.


public class SearchStringArrayExample {
public static void main(String[] args) {
String[] strArray3 = { "R", "S", "T" };
boolean found = false;
int index = 0;
String s = "S";
for (int i = 0; i < strArray.length; i++) {
if(s.equals(strArray[i])) {
index = i; found = true; break;
}
}
if(found)
System.out.println(s +" found at the index "+index);
else
System.out.println(s +" not found in the array");
}
}

Output:

B found at index 1

The keyword break is used to stop the loop as soon as the element is found.

Sorting A String Array

To sort the elements in the string array, we can implement our own sorting algorithm, or we can invoke the Arrays class sorting method.


String[] vowels = {"o","e","i","u","a"};
System.out.println("Initial array "+Arrays.toString(vowels));
Arrays.sort(vowels);
System.out.println("Array after the sort "+Arrays.toString(vowels));

Output:

Initial array: [o ,e , i, u, a]

Array after the sort: [a, e, i, o, u]

It must be noted that String implements the Comparable interface, therefore it works for natural sorting.

Converting String Array To A String

It is required to convert a String Array to a String sometimes, due to display purposes. We can use the Arrays.toString() method for the conversion.


String[] strArray3 = { "R", "S", "T" };
String theString = Arrays.toString( strArray3 );
System.out.println( theString );

Output:

[R,S,T]

The elements are not only separated by a comma, but also enclosed in square brackets.

The user also has the option of implementing  a custom behaviour. In the following example, we will be using a custom delimiter:


String[] strArray3 = { "R", "S", "T" };
String delimiter = "-";
StringBuilder sb = new StringBuilder();
for ( String element : strArray3 ) {
if (sb.length() > 0) {
sb.append( delimiter );
}
sb.append( element );
}
String theString = sb.toString();
System.out.println( theString );

Output:

R-S-T

The above code uses the delimiter dash without the square brackets.

Java Full Course – 10 Hours | Java Full Course for Beginners | Java Tutorial for Beginners | Edureka

🔥𝐄𝐝𝐮𝐫𝐞𝐤𝐚 𝐉𝐚𝐯𝐚 𝐂𝐨𝐮𝐫𝐬𝐞 𝐓𝐫𝐚𝐢𝐧𝐢𝐧𝐠: https://www.edureka.co/java-j2ee-training-course (Use code “𝐘𝐎𝐔𝐓𝐔𝐁𝐄𝟐𝟎”)
This Edureka Java Full Course will help you understand the various fundamentals of Java programm…

Let us continue with the next topic of this String Array in Java article,

Converting A String Array To A List

The major disadvantage of a string array is that it is of a fixed size. For an array which can grow in size, we implement the List.


String[] strArray3 = { "R", "S", "T" };
List<String> stringList = Arrays.asList( strArray3 );

It must be noted that we cannot add items to the List returned by Arrays.asList method. It raises a java.lang.UnsupportedOperationException as shown in the code below:


String[] strArray3= { "R", "S", "T" };
List<String> stringList = Arrays.asList(strArray3);
stringList.add( "U" );

The error raised can be avoided by converting the String Array to an ArrayList.


String[] strArray3 = { "R", "S", "T" };
List<String> fixedList = Arrays.asList(strArray3);
List<String> stringList = new ArrayList<String>( fixedList );
stringList.add( "U" );

This code constructs a new ArrayList based on the  value returned by Arrays.asList. It will not raise an exception.

Converting String Array To A Set

While a List can contain elements that are duplicate, a Set cannot. To create a collection of elements that are unique in nature, Set proves to be an appropriate data structure.


String[] strArray3 = { "R", "S", "T", "T" };
List<String> stringList = Arrays.asList(strArray3);
Set<String> stringSet = new HashSet<String>( stringList );
System.out.println( "The size of the list is: " + stringList.size() );
System.out.println( "The size of the set is: " + stringSet.size() );

Output:

The size of the list is: 4

The size of the set is: 3

As mentioned, the set contains only the unique elements.

Converting List To A String Array

It is plausible to convert a List back to the String Array.


List<String> stringList = new ArrayList<String>();
stringList.add( "R" );
stringList.add( "S" );
stringList.add( "T" );
String[] stringArr = stringList.toArray( new String[] {} ); //passing the toArray method
for ( String element : stringArr ) {
System.out.println( element );
}

The toArray specifies the type of the array returned.

The Java StringArray contains innumerous methods but is used widely and assuredly for an efficient programming experience.

Thus we have come to an end of this article on ‘String Array in Java’. If you wish to learn more, check out the Java Certification Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog  and we will get back to you as soon as possible or you can also join Java Training in Sheffield.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is String Array in Java and How it Works?

edureka.co