×

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 import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.