Tutorials  /  JavaScript

Java String Array - Tutorial

Ccentron Redaktion · March 2024 ·5 min read ·JavaScript, Tutorial

Java String array is used to hold a fixed number of Strings. String array is very common in simple Java programs, especially among beginners to Java and to test some specific scenarios. Even the Java main method argument is a string array - public static void main(String[] args). So today, we will look into different aspects of the Java string array with example programs.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

Java String array is basically an array of objects.

There are two ways to declare a string array - declaration without size and declare with size.

There are two ways to initialize a string array - at the time of declaration, populating values after declaration.

We can do different kinds of processing on the string array such as iteration, sorting, searching, etc.

Let’s go over Java string array example programs now.

Java String Array Declaration

Below code snippet shows different ways for string array declaration in Java.

Code
String[] strArray; //declare without size

String[] strArray1 = new String[3]; //declare with size

Note that we can also write a string array as String strArray[] but the above shows way is the standard and recommended way. Also, in the above code, strArray is null whereas strArray1 value is [null, null, null].

Initialization

Let’s look at different ways to initialize a string array in Java.

Code
//inline initialization
String[] strArray1 = new String[] {"A","B","C"};
String[] strArray2 = {"A","B","C"}; 

//initialization after declaration
String[] strArray3 = new String[3];
strArray3[0] = "A";
strArray3[1] = "B";
strArray3[2] = "C";

All the three-string arrays will have the same values. However, if you call equals method on them, it will return false.

Code
System.out.println(strArray1.equals(strArray2)); // false
System.out.println(Arrays.toString(strArray1).equals(Arrays.toString(strArray2)));// true

The reason is that arrays are Objects and the Object class implements equals() method like below.

Code
public boolean equals(Object obj) {
        return (this == obj);
    }

The second statement is true because when converted to String, their values are the same and String class equals() method implementation checks for values. For more details, please check the String class API documentation.

Iterating over Java string array

We can iterate over a string array using Java for loop or Java foreach loop.

Code
String[] strArray2 = {"A","B","C"}; 
for (int i = 0; i < strArray2.length; i++) {
    System.out.print(strArray2[i]);
}

for (String str : strArray2) {
    System.out.print(str);
}

Search for a String

We can use a for loop to search for a string in the array, below is a simple example of that.

Go
package com.journaldev.stringarray;

public class JavaStringArrayExample {

    public static void main(String[] args) {
        String[] strArray = { "A", "B", "C" };
        
        boolean found = false;
        int index = 0;
        String s = "B";
        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 index "+index);
        else
            System.out.println(s +" not found in the array");
        
    }

}

Notice the use of the break keyword to get out of the loop as soon as we found the string.

Java String Array Sorting

We can implement our own sorting algorithm, or we can use the Arrays class sorting method.

Code
String[] vowels = {"a","i","u","e","o"};
        
System.out.println("Before sorting "+Arrays.toString(vowels));

Arrays.sort(vowels);
        
System.out.println("After sorting "+Arrays.toString(vowels));

Output of the above code snippet will be:

    • Before sorting [a, i, u, e, o]
    • After sorting [a, e, i, o, u]

</ul

Note that String implements Comparable interface, so it works for natural sorting. In case you want to sort by some other way, you can use Arrays.sort() overloaded method by passing a Comparator.

Convert String to String Array

We can convert String to string array using its split() method. It’s useful when you get a single string as input with values separated using a delimiter character.

Code
String str = "a,e,i,o,u";
String[] vowels = str.split(",");
System.out.println(Arrays.toString(vowels)); //[a, e, i, o, u]

Convert String Array to String

We can use Arrays.toString() method to convert String array to String. Note that array doesn’t implement toString() method, so if you will try to get its string representation then you will have to rely on Arrays class, or else write your own custom code.

Code
String[] vowels = { "a", "e", "i", "o", "u" };
System.out.println(vowels);
System.out.println(Arrays.toString(vowels));

Output will be like below.

      • [Ljava.lang.String;@3d04a311
      • [a, e, i, o, u]

The first output is because of Object class toString() implementation like below.

Code
public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

Java String Array to List

We can get a list representation of string array using Arrays.asList() method. Note that this list is backed by the array and any structural modification will result in java.lang.UnsupportedOperationException.

Code
String[] vowels = { "a", "e", "i", "o", "u", "a", "o" };

List vowelsList = Arrays.asList(vowels);
System.out.println("vowelsList = "+vowelsList);
//vowelsList.add("x"); //java.lang.UnsupportedOperationException

vowelsList.set(0, "x"); //allowed because no structural modification
System.out.println("vowelsList = "+vowelsList);

That’s all for Java string array.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren