×

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

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.