Home Java Collection How to declare String array in Java?
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

How to declare String array in Java?

Advertisement
Following example will show you how to declare string array in java. There are many ways to declare an array and initialize them. We can use 'new' keyword to declare an array. However, an array can also be declared without the use of 'new' keyword.

Following example will show you how to declare string array in java. There are many ways to declare an array and initialize them. We can use 'new' keyword to declare an array. However, an array can also be declared without the use of 'new' keyword.

Following example declare, initialize and access elements of one dimensional array and two dimensional array.

1. String arr[] = new String[] {"Somendra", "Nishant", "Shashank", "Gitika"};
2. String arr[] = {"Somendra", "Nishant", "Shashank", "Gitika"};

public class ArrayDimensions {
    public static void main(String[] args) {
        //declare and initialize one dimension array
        String[] names = new String[]{"Somendra", "Nishant", "Shashank", "Gitika"};
        System.out.println("These are elements of one Dim array.");
        for (int i = 0; i < names.length; i++) {
            System.err.println(names[i] + "   ");
        }
        //declare and initialize two dimensional array
        String dim2[][] = {
            {"Somendra", "Shashank"},
            {"Sandeep", "Gunjan"},
            {"Amit", "Gitika"}
        };
        System.out.println("These are elements of two Dim array.");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.println(dim2[i][j]);
            }
        }
    }
}

Output:

These are elements of one Dim array.
Somendra
Nishant
Shashank
Gitika

These are elements of two Dim array.
Somendra
Shashank
Sandeep
Gunjan
Amit
Gitika

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 10, 2013

Ask Questions?    Discuss: How to declare String array in Java?  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com