004-005-009

Initialize Array with Literal

Medium

Problem Description

Array Literals: Concise Initialization

Array literals allow declaration and initialization in one line, making code more readable and maintainable. They are the preferred way to initialize arrays with known values.

Learning Points

  • Array Literal Syntax: type[] name = {v1, v2, v3}
  • Automatic Size: Array length determined by number of values
  • Declaration-Only Usage: Literals only work at declaration time
  • Enhanced For Loop: Simplest way to iterate over arrays

Array Literal Syntax

type[] arrayName = {value1, value2, value3};

Comparison with Multi-Step Initialization

Array Literal (Preferred)Multi-Step (Verbose)
String[] fruits = {"Apple", "Banana", "Cherry"};
String[] fruits = new String[3];
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Cherry";

Common Mistakes

Mistake 1: Using Literal for Reassignment

Incorrect code:

String[] fruits;
fruits = {"Apple", "Banana"};  // Compile error!

Correct code:

String[] fruits;
fruits = new String[]{"Apple", "Banana"};  // Use new type[]{}

Mistake 2: Mixing Types in Literal

Incorrect code:

Object[] mixed = {1, "two", 3.0};  // Works but loses type safety

Better code:

int[] numbers = {1, 2, 3};  // Homogeneous types preferred

Enhanced For Loop (for-each)

for (String fruit : fruits) {
    System.out.println(fruit);
}

Benefits: No index variable, no off-by-one errors, cleaner code.

Limitation: Cannot modify array or access index during iteration.

When to Use Each Style

  • Array literal: Known values at compile time
  • new type[size]: Dynamic size, filled later
  • Enhanced for: Read-only iteration
  • Traditional for: Need index or modification

Prerequisites

Let's review the knowledge needed to solve this problem.

Basic Concepts

Understanding the fundamental programming concepts covered in this problem is the first step toward a correct solution. Grasp how each element of the code works together.

Implementation Approach

Here is a step-by-step thinking process for solving this problem:

  1. Read the problem statement and understand the relationship between input and output
  2. Identify the required variables and data structures
  3. Build the processing flow
  4. Verify behavior with test cases

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?