← Back to Chapters

Java Array Initialization

? Java Array Initialization

? Quick Overview

Array initialization in Java is the process of creating an array and assigning values to it. Java provides multiple ways to initialize arrays depending on when and how the values are known.

? Key Concepts

  • Arrays store multiple values of the same data type
  • Array size is fixed after creation
  • Indexing starts from 0
  • Initialization can be done at declaration or later

? Syntax / Theory

  • Declaration only: memory not allocated
  • Declaration + size: default values assigned
  • Declaration + values: size inferred automatically

? Code Examples

? View Code Example
// Array declaration with size and default initialization
int[] numbers = new int[5];
System.out.println(numbers[0]);
? View Code Example
// Array initialization using literal values
int[] marks = {90, 85, 78, 92};
System.out.println(marks[2]);
? View Code Example
// Initializing array using new keyword with values
String[] names = new String[]{"Java", "Python", "C++"};
System.out.println(names[1]);

? Interactive Visualization

Enter values separated by commas to see how Java stores them in memory with 0-based indexing.

 
// Java code will appear here

? Live Output / Explanation

Explanation

When an array is created with a fixed size, Java assigns default values (0 for integers, null for objects). Using array literals allows direct assignment of values and automatic size calculation.

? Tips & Best Practices

  • Use array literals when values are known in advance
  • Avoid accessing indexes outside array length
  • Prefer enhanced for-loop for read-only traversal
  • Use meaningful variable names for clarity

? Try It Yourself

  • Create an array of 5 integers and print all values
  • Initialize a String array with your favorite languages
  • Find the sum of elements in an integer array