Create New Array Example in Java

The below code examples demonstrates how to create a new array of 5 elements of String data type in Java and how to populate each array element. You will also learn how to access each array element individually and print out its value.

Create a New Array in Java. Code example.

package com.appsdeveloperblog.arrays;
 
public class CreateArray {
    public static void main(String[] args)
    {
        // Declare an Array of Strings
        String[] names = new String[5];
        
        // Pupulate an array with first element
        names[0] = "Sergey";
        
        // Populate an array with other elements
        names[1] = "Bill";   
        names[2] = "Josh";         
        names[3] = "Ron";   
        names[4] = "Bell";    
        
        // Print out array size
        System.out.println("Array contains " + names.length + " elements");
        
        // Access a specific element of an array 
        System.out.println("First element of an array is " + names[0]);
    }
}

 

Leave a Reply

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