Programs

String Array In Java: Java String Array With Coding Examples

In Java, Array refers to a crucial data structure used to collect and store multiple data types from primitive to user-defined. String array is the array of various objects where each of its elements is a string. Users can perform several operations on these components, like adding a component, sorting, joining, searching, splitting, etc.

Check out our free courses to get an edge over the competition.

Introduction To A String Array In Java

It is possible to have an array with strings in Java as its derived elements. This means that users can define ‘String Array’ as an array that holds a certain number of string values or strings. In other words, it refers to a structure that is widely used in Java for having the string value. For instance, even the number of arguments of the prime function in Java refers to a string array.

Check out upGrad’s Advanced Certification in Cyber Security

Learn Software programs online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Declaring The String Array In Java

In Java, a string array can be declared in two methods, i.e. without specifying the actual size or specifying the size. Let us go through each of these processes. Below you will find the two methods of declaring the string array in Java-

String[] myarray ; //String array declaration without size

String[] myarray = new String[5];//String array declaration with size

In the first section, the string array is declared just like a general variable without specifying the size. Remember that before using this method, you have to instantiate the collection with “new”.

Check out upGrad’s Advanced Certification in Blockchain

In the second section, the string array is instantiated and declared with ‘new’. Here the string array in Java is declared with five elements. If you directly print the declaration’s components, you may see the null values because the string array will not get initialized.

Let us go through a program that highlights string array declaration-

public class Main

{

    public static void main(String[] args) {

        String[] myarray; //declaration of string array without the size

        String[] strArray = new String[5]; //declaration with size 

        //System.out.println(myarray[0]); //variable myarray might not have been initialized

        //display elements of second array

        System.out.print(strArray[0] + ” ” +strArray[1]+ ” ” + strArray[2]+ ” ” +

        strArray[3]+ ” ” +strArray[4]);

    }

} 

Output

null null null null

Read about: Top 12 Pattern Programs in Java You Should Checkout Today

Explore Our Software Development Free Courses

Initializing A String Array In Java

Once the string array is declared in Java, you can initialize it with some other values. This is because the default values of the array that are assigned to the string elements are null. Hence, soon after the declaration, you can proceed to initialize a string array. You can initialize the string array through the below-mentioned declaration.

String[] strArray = new String[3];

strArray[0] = “one”;

strArray[1] = “two”;

strArray[2] = “three”;

In the above declaration, the string array is declared at first. And in the next line, individual components are assigned along with their values. As soon as the string array is initialized, you can easily use these values in your program.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

The Length And The Size Of The String Array

To get to the array’s actual size, there is a property named ‘length’ in the array. This goes the same for the string array in Java as well. The length or the size of any array provides the total number of elements present in the array. So, to get the length and the size of the array, you can use many expressions. One of them is declared below-

int len = myarray.length;

We can implement a program that can give an output to the length of a String Array. 

public class Main

{

    public static void main(String[] args) {

    //declare and initialize a string array

    String[] numArray = {“one”,”two”, “three”, “four”, “five”};

    int len = numArray.length; //get the length of array

    //display the length

    System.out.println(“Length of numArray{\”one\”,\”two\”, \”three\”, \”four\”, \”five\”}:” + len);

    }

} 

Output

Length of numArray {“one”, “two”, “three”, “four”, “five”}:5

The length of an array is a significant property that is used to iterate the string array to process it.

Explore our Popular Software Engineering Courses

Iterating And Printing The String Array

So far in this article, we have already discussed the declaration, initialization, and length properties of the string array, and now we will traverse through each of the string array elements and print them. You can easily iterate over the string array with the help of ‘for loop’ and ‘enhance for loop’. Mentioned below is a Java-based declaration that highlights the “enhanced for loop” that is used to iterate the string array and print its elements.

public class Main

{

    public static void main(String[] args) {

        //declare and initialize a string array

        String[] numArray = {“one”,”two”, “three”, “four”, “five”};

        System.out.println(“String Array elements displayed using for loop:”);

        // for loop to iterate over the string array

        for(int i=0; i<numArray.length;i++)

            System.out.print(numArray[i] + ” “);    

        System.out.println(“\n”);   

        System.out.println(“String Array elements displayed using enhanced for loop:”);

        //enhanced for loop to iterate over the string array

        for(String val:numArray)

            System.out.print(val + ” “);

    }

}

Output

String Array elements displayed using for loop:

one two three four five

String Array elements displayed using “enhanced for loop”:

one two three four five

In this program, both the ‘enhanced for loop’ and ‘loop’ are utilized for traversing the string array. Remember that in the enhanced loop case, it is not required for the user to specify the code’s condition or limit. But in the loop, you have to specify the end condition and the start.

In-Demand Software Development Skills

Sorting String Array

The methodology that is used to sort the string array in Java is similar to the other array sorting methods. Below you will find the implementation of this method with the array class that sorts the array strings alphabetically.

import java.util.*;

class Main {

     public static void main(String[] args)

    {

        String[] colors = {“red”,”green”,”blue”,”white”,”orange”};

        System.out.println(“Original array: “+Arrays.toString(colors));

        Arrays.sort(colors);

        System.out.println(“Sorted array: “+Arrays.toString(colors));

    }

}

Output

Original array: [red, green, blue, white, orange]

Sorted array: [blue, green, orange, red, white]

Must Read: 17 Interesting Java Project Ideas & Topics For Beginners

Read our Popular Articles related to Software Development

Conclusion

In this blog, we have seen the details of the string array in Java, and we have gone through the major concepts like string array declaration, initialization, sorting, etc. However, various other operations are related to the same idea, such as converting them to string, list, set, or array.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

array, and then assigns a new string to it. The valueOf() method converts a char array to a string array by parsing the char[] array as params. In return, a new string is formed. The next method is copyValueOf() method is a static method that comes from the string class. It converts a character array into a string array by parsing it. ” image-1=”” headline-2=”h2″ question-2=”What is an array?” answer-2=”Arrays are mainly used when there is a need to store multiple values in a single variable. This saves time and storage and reduces the need to create a separate variable to declare multiple values. An array is defined within square brackets. Arrays can be accessed through their index values where 0 is the index of the first element, 1 is the index of the second element in the array, 2 is the index of the third element, and so on. Therefore, if you alter an array, you need to specify it through its index number. The length method can be used to find out the length of an array. ” image-2=”” count=”3″ html=”true” css_class=””]
Want to share this article?

Leave a comment

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

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks