Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconString Array In Java: Java String Array With Coding Examples

String Array In Java: Java String Array With Coding Examples

Last updated:
20th Oct, 2020
Views
Read Time
5 Mins
share image icon
In this article
Chevron in toc
View All
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

Ads of upGrad blog

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

Ads of upGrad blog

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=””]

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Explore Free Courses

Suggested Blogs

Scrum Master Salary in India: For Freshers &#038; Experienced [2023]
900134
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers &#038; Experienced [2024]
904670
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5011
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag &#038; Attributes in HTML: Features, Uses, Examples
5058
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5030
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5063
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5026
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions &#038; Answers (Freshers &#038; Experienced)
5075
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

10 Best Software Engineering Colleges (India and Global) 2024
5386
Software Engineering is developing, designing, examining, and preserving software. It is a structured and trained approach through which you can devel
Read More

by venkatesh Rajanala

28 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon