×

String Array in Java

String Array in Java

An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types like primitive or non-primitive.

What is a String array in Java?

In Java,a String array is a fixed size objectthat stores string values. The String is a sequence of characters. It is an immutable object it means that values stored in the array object cannot be modified.

Declaring a String array in Java

There are the following ways to declare a String array in Java.

  1. Declaring without size

Syntax:

String[] myStrArray;

This way a String array myStrArraycan be declared like any other normal variable. But before using this, it should be instantiated with new.

  • Declaring with size

Syntax:

String[] myStrArray = new String[5];

          Here, the String array myStrArray is declared using the newkeyword. It can store five elements.

Initializing a String array

There are two ways to initialize an array:

Inline Initialization: In inline initialization, first we declare an array after that put the elements of the array.

Syntax:

 String[] myStrArray1 = new String[]{"a", "b", "c"};
String[] myStrArray2 ={"a", "b", "c"}; 

Here, myStrArray1 is declared and initialized immediately. And myStrArray2 is instantiated just after declaration.

We can also split the first statement, as follows:

 String[] myStrArray1;                                       // array declaration
myStrArray1 = new String[] { "A", "B", "C", "D", "E" };     // array initialization 

Initialization after declaration

Syntax:

 String[] strarr = new String[4];
strarr[0] = "a";
strarr[1] = "b";
strarr[2] = "c";
strarr[3] = "d"; 

          Here, the strarr is first declared and then it is initialized one by one using the index.

Operations Performed on String array

  1. Size of String array

The Java String class provides a property called length. It determines the length of the string.

StringSize.java

 public class StringSize
{
    /* Driver Code */
    public static void main(String []args)
     {
        /* String Array declaration and initialization */
        String[] myStrArr1 ={"a", "b", "c"};   
        /*prints length of array */
        System.out.println("Length of the String array: "+myStrArr1.length);
     }
} 

Output:

Length of the String array: 3

In the above class StringSize, a String array myStrArr1 is declared and initialized immediately. Length property is used to print the length of myStrArr1.

  • Iterating in an array

IterateString.java

 public class IterateString
{
    /* Driver Code */
    public static void main(String []args)
     {
        /* String Array declaration and initialization */
        String[] myStrArr1 ={"a", "b", "c"};   
        /*iterates over array */
        for(int i=0;i<myStrArr1.length;i++)
        System.out.println("myStrArr1["+i+"]: "+myStrArr1[i]);
     }
} 

Output:

 myStrArr1[0]: a
myStrArr1[1]: b
myStrArr1[2]: c 

In the above program we have used Java for loop that iterates over the array. The loop starts from the 0 and execute till the length of the array.

  • Searching an element in a String array

SearchStrArray.java

 public class SearchStrArray
{
    /*Driver Code */
    public static void main(String[] args)
    {
        /* String Array declaration and initialization */
        String[] myStrArr1 = { "a", "b", "c" };
        boolean flag = false;
        int index = 0;
        String k = "b"; /* Element to be searched */
        for (int i = 0; i < myStrArr1.length; i++)
        {
            if(k.equals(myStrArr1[i]))
            {
                index = i;
                flag = true;
                break;  /*stops the loop after element is found */
            }
        }
        if(flag)
            System.out.println("Element "+ k +" found at the index "+ index);
        else
            System.out.println("Element "+ k +" not found in the array");
    }
} 

Output:

Element b found at the index 1

In the above program, we have searched for the element b. In the if statement we have compared the element (b) with each element of the array. If match is not found, the break keyword breaks the execution of the loop and the execution jumps to the next statement.

  • Sorting a String array

SortStrArray.java

 import java.util.*;
public class SortStrArray
{
    /*Driver Code */
    public static void main(String[] args)
    {
        /* String Array declaration and initialization */
        String[] myStrArr = { "c", "a", "b", "f", "e" };
        System.out.println("Before Sorting: "+ Arrays.toString(myStrArr));
        /*Sorting operation */
        Arrays.sort(myStrArr);
        System.out.println("After Sorting: "+ Arrays.toString(myStrArr));
    }
} 

Output:

String Array in Java

In the above code, Arrays.sort(myStrArr) method is used to sort the String array.

  • Converting a String array to a String

StrArraytoStr.java

 import java.util.*;
public class StrArraytoStr
{
    /*Driver Code */
    public static void main(String[] args)
    {
        /* String Array declaration and initialization */
        String[] myStrArr = { "c", "a", "b", "f", "e" };
        /* String array to String conversion */
        String theString = Arrays.toString( myStrArr);
        System.out.println("String: "+ theString);
    }
} 

Output:

String Array in Java

     In the above code, the String array is converted into String using Arrays.toString(myStrArr) method.

  • Converting a String array to a List and adding a new element to the List

StrArraytoList.java

 import java.util.*;
public class StrArraytoList
{
    /*Driver Code */
    public static void main(String[] args)
    {
        /* String Array declaration and initialization */
        String[] myStrArr = { "a", "b", "c", "e", "f" };
        /* String array to List conversion */
        List<String> fixedList = Arrays.asList(myStrArr);
        System.out.print("String array to List: ");
        for (String str : fixedList)
        {
             System.out.print(str + " " );
        }
        /* A new list for adding new elements */
        List<String> stringList = new ArrayList<String>( fixedList );
        /*Adding a new element to the List */
        stringList.add( "g" );
        System.out.println();
        System.out.print("List after adding a new element: ");
        for (String str : stringList)
        {
             System.out.print(str + " " );
        }
    }
} 

Output:

String Array in Java

          In the above code, Arrays.asList(myStrArr) method is used to convert the String array myStrArr to a List.

In this way, we have understood String arrays in Java and various operations performed on them.


Related Topics

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.