How to Initialize an Array in Java in One Line

In this example, we will demonstrate how to initialize an Array in Java in one line.

Learn complete Arrays in Java at https://www.javaguides.net/2018/08/java-array-basics-guide.html.

How to Initialize an Array in Java in One Line

The following program demonstrates:
1. Initialize Integer Array in one line
2. Initialize Spring Array in one line
3. Initialize Employee Array in one line
package com.javaguides.corejava.arrays;

/**
 * Class demonstrate the basics of Array
 * @author javaguides.net
 *
 */
public class JavaArrayDemonstration {

    public static void main(String[] args) {
    
       // shortcut syntax to create and initialize an integer array
       int[] array = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
       // Each array element is accessed by its numerical index:
       System.out.println("Element 1 at index 0: " + array[0]);
       System.out.println("Element 2 at index 1: " + array[1]);
       System.out.println("Element 3 at index 2: " + array[2]);
       System.out.println("Element 4 at index 3: " + array[3]);
       System.out.println("Element 5 at index 4: " + array[4]);
  
       // shortcut syntax to create and initialize an string array
       String[] arrayOfStrings = {"abc", "xyz", "name", "address", "id"};
       // Each array element is accessed by its numerical index:
       System.out.println("Element 1 at index 0: " + arrayOfStrings[0]);
       System.out.println("Element 2 at index 1: " + arrayOfStrings[1]);
       System.out.println("Element 3 at index 2: " + arrayOfStrings[2]);
       System.out.println("Element 4 at index 3: " + arrayOfStrings[3]);
       System.out.println("Element 5 at index 4: " + arrayOfStrings[4]);
  
       // shortcut syntax to create and initialize an array
       Employee[] employees = {new Employee(10, "ramesh"),new Employee(11, "john")};
       // Each array element is accessed by its numerical index:
       System.out.println("Element 1 at index 0: " + employees[0].getName());
       System.out.println("Element 2 at index 1: " + employees[1].getName());  
    }
}

class Employee {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Employee(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
}
Output:
Element 1 at index 0: 100
Element 2 at index 1: 200
Element 3 at index 2: 300
Element 4 at index 3: 400
Element 5 at index 4: 500
Element 1 at index 0: abc
Element 2 at index 1: xyz
Element 3 at index 2: name
Element 4 at index 3: address
Element 5 at index 4: id
Element 1 at index 0: ramesh
Element 2 at index 1: john

Reference


Comments