×

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

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.