Java

What Is String Array In Java?

You will discover what a string array in Java is, how to utilize one, and the many operations you can carry out on one in this book.

A string array is a group of strings that are kept in close proximity to one another in memory.

For instance: The string array that follows has four components. These items can be retrieved using an array index, such as: These elements are kept in consecutive memory regions. “Chaitanya” is the first element represented by names[0]. The second element, “Ajeet,” is represented by names[1], the third element, “Hari,” and so on.

String[] names = new String[] {"Chaitanya", "Ajeet", "Hari", "Rahul"};

String Array Declaration

A String array can be declared in Java in two different methods.

1. Without specifying the array size:

String[] strArray;

2. Array size is specified: Up to 5 strings can be stored in the following array.

String[] strArray = new String[5];

String Array Initialization

1. Inline Initialization:

String[] names = new String[] {"Chaitanya", "Ajeet", "Hari", "Rahul"};

OR

String[] names = {"Chaitanya", "Ajeet", "Hari", "Rahul"};

2. Normal Initialization after declaration:

Here, we’ve set a fixed size of 4 for the names array and populated it afterwards.

String[] names= new String[4];  
names[0]= "Chaitanya"; //first element
names[1]= "Ajeet";  //second element
names[2]= "Hari";  //third element
names[3]= "Rahul"; //last element

Simple String Array Example in Java

We have a string array of fruits in this case. There are three elements in this array (strings). Using a for loop, we are showing the string array’s elements. Fruits.length’s length property returns the array’s element count, which in this example is 3.

public class JavaExample {

  public static void main(String a[]){
    //declared and initialized a string array
    String[] fruits = new String[]{"Apple", "Orange", "Banana"};

    for (int i=0; i<fruits.length; i++)
    {
      System.out.println("fruits["+i+"]: "+fruits[i]);
    }
  }
}

Output:

What Is String Srray In Java ?

String array ArrayIndexOutOfBoundsException

The compiler issues a warning if the supplied index is more than the array’s size. ArrayIndexOutOfBoundsException.

public class JavaExample {

  public static void main(String a[]){
    //declared and initialized a string array
    String[] fruits = new String[]{"Apple", "Orange", "Banana"};

    //We are trying to print 11th element of the array
    //but the array contains only 3 elements. This will
    //throw ArrayIndexOutOfBoundsException
    System.out.println(fruits[10]);
  }
}

Output:

What Is String Srray In Java ?

Iterating a String Array

Let’s practice iterating over a string array. Using a regular for loop or an improved for loop, we can iterate (for each loop).

public class JavaExample {

  public static void main(String a[]){
    //declared and initialized a string array
    String[] fruits = new String[]{"Apple", "Orange", "Banana"};

    //iterating using normal for loop
    System.out.println("Iterating using for loop:");
    for (int i=0; i<fruits.length; i++)
    {
      System.out.println("fruits["+i+"]: "+fruits[i]);
    }

    //iterating using for-each loop
    System.out.print("Iterating using foreach loop: ");
    for (String str: fruits)
    {
      System.out.print(str+ " ");
    }
  }
}

Output:

What Is String Srray In Java ?

Adding elements to String array

You already know that the array’s size is fixed, thus once it is full, you are unable to add any more elements to it. There are two ways to add elements to an array, though. Technically speaking, a new array containing all the items of the old array as well as the new elements is created instead of adding the elements to the present array.

  1. Creating a new array
  2.  Using ArrayList

1. Adding elements to an array by creating new array

The procedures used in this program are:

  1.  In order to make room for the additional elements, make a new array that is larger.
  2.  Add all of the elements from the old array to the new array.
  3.  a new array with new items
  4.  Print a fresh assortment
public class JavaExample {

  public static void main(String a[]){
    //declared and initialized a string array
    String[] fruits = new String[]{"Apple", "Orange", "Banana"};

    //we want to add two more elements to the fruits array so let's
    //create a new array with the size of 5
    String[] newFruits = new String[fruits.length+2];


    //copying elements from old array to new array
    for (int i=0; i<fruits.length; i++)
    {
      newFruits[i] = fruits[i];
    }

    //Adding new elements
    newFruits[newFruits.length-2]= "Mango"; //second last element
    newFruits[newFruits.length-1]= "Kiwi"; //last element

    //print new array
    for (String str: newFruits)
    {
      System.out.println(str);
    }
  }
}

Output:

Apple
Orange
Banana
Mango
Kiwi

2. Adding elements to an array using ArrayList

The procedures used in this program are:

  1. ArrayList from array conversion.
  2. Because an array list is dynamic and may expand and shrink on its own, you can add as many elements as you wish to it.
  3. After addition is complete, change the ArrayList back to an Array.
  4. Print the array.
  5. import java.util.*;
    public class JavaExample {
    
      public static void main(String a[]){
        //declared and initialized a string array
        String[] fruits = new String[]{"Apple", "Orange", "Banana"};
    
        //Convert the array "fruits" to an ArrayList
        ArrayList<String> fruitList =
                new ArrayList<String>(Arrays.asList(fruits));
    
        //Adding elements to ArrayList
        fruitList.add("Mango");
        fruitList.add("Kiwi");
    
        //Convert the ArrayList to array
        String[] newFruits = fruitList.toArray(new String[fruitList.size()]);
    
        //print new array
        for (String str: newFruits)
        {
          System.out.println(str);
        }
    
      }
    }

    Output:

    Apple
    Orange
    Banana
    Mango
    Kiwi

Sorting string array

In this example, we’ll show you how to sort a string array. Simply import java.util to get started. To utilize the sort() function of the Arrays class, use the Arrays package. Ascending order is used to sort the array that is supplied to the sort() function.

import java.util.Arrays;
public class JavaExample {

  public static void main(String a[]){
    String[] names = new String[]{"Chaitanya", "Steve", "Rob", "Ajeet"};

    //print array before sorting
    System.out.println("Array before sorting: ");
    for (String str: names)
    {
      System.out.print(str+ " ");
    }

    //sorting array
    Arrays.sort(names);

    //new line
    System.out.println();

    //print array after sorting
    System.out.println("Array after sorting: ");
    for (String str: names)
    {
      System.out.print(str+ " ");
    }
  }
}

Output:

What Is String Srray In Java ?

Search an element in a String array

In this case, a string array entry is being searched. When a match is discovered, we save the index and set the foundFlag to true and iterate through the whole array, matching each element with the searchItem. If no match is discovered after searching the entire array, the message “String is not found” is printed in the if-else expression that follows the for loop.

public class JavaExample {

  public static void main(String a[]){
    String[] names = new String[]{"Chaitanya", "Steve", "Rob", "Ajeet"};

    //this will represent the index of search element when it is found
    int index=0;

    //This will set to true, if element is found in array, else it
    //will remain false.
    boolean foundFlag = false;

    //This is the search element, we are searching for this element in array
    String searchItem ="Rob";

    for (int i = 0; i < names.length; i++) {
      if(searchItem.equals(names[i])) {
        //if element found, get index, set flag to true and break the loop
        index = i;
        foundFlag = true;
        break;
      }
    }
    if(foundFlag)
      System.out.println("String "+searchItem +" is found at index: "+index);
    else
      System.out.println("String "+searchItem +" is not found");

  }
}

Output:

String Rob is found at index: 2

 

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button