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 Tutorials

View All

Suggested Blogs

Top 14 Technical Courses to Get a Job in IT Field in India [2024]
90952
In this Article, you will learn about top 14 technical courses to get a job in IT. Software Development Data Science Machine Learning Blockchain Mana
Read More

by upGrad

15 Jul 2024

25 Best Django Project Ideas &#038; Topics For Beginners [2024]
143863
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

11 Jul 2024

Must Read 50 OOPs Interview Questions &#038; Answers For Freshers &#038; Experienced [2024]
124781
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

04 Jul 2024

Understanding Exception Hierarchy in Java Explained
16880
The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the ex
Read More

by Pavan Vadapalli

04 Jul 2024

33 Best Computer Science Project Ideas &#038; Topics For Beginners [Latest 2024]
198249
Summary: In this article, you will learn 33 Interesting Computer Science Project Ideas & Topics For Beginners (2024). Best Computer Science Proje
Read More

by Pavan Vadapalli

03 Jul 2024

Loose Coupling vs Tight Coupling in Java: Difference Between Loose Coupling &#038; Tight Coupling
65177
In this article, I aim to provide a profound understanding of coupling in Java, shedding light on its various types through real-world examples, inclu
Read More

by Rohan Vats

02 Jul 2024

Top 58 Coding Interview Questions &amp; Answers 2024 [For Freshers &amp; Experienced]
44560
In coding interviews, a solid understanding of fundamental data structures like arrays, binary trees, hash tables, and linked lists is crucial. Combin
Read More

by Sriram

26 Jun 2024

Top 10 Features &#038; Characteristics of Cloud Computing in 2024
16289
Cloud computing has become very popular these days. Businesses are expanding worldwide as they heavily rely on data. Cloud computing is the only solut
Read More

by Pavan Vadapalli

24 Jun 2024

Top 10 Interesting Engineering Projects Ideas &#038; Topics in 2024
43094
Greetings, fellow engineers! As someone deeply immersed in the world of innovation and problem-solving, I’m excited to share some captivating en
Read More

by Rohit Sharma

13 Jun 2024

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