How to declare String array in Java?

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