004-001-006

Array Basics: Favorite Items List

Medium

Problem Description

[Explanation]

🎯 Problem Overview

This problem teaches the fundamentals of arrays, an essential data structure. Arrays are like containers that can manage multiple data items of the same type under one variable name. In real development, arrays are fundamental for managing lists and collections.

📚 Prerequisites

Knowledge required to solve this problem:

  • Variable declaration and assignment: How to create int and String variables
  • For loops: Basic syntax for repetitive processing
  • Index concept: Identifying elements with numbers starting from 0

💡 Key Points

1. Array Declaration and Initialization

To use an array, you first need to declare it:

String[] items = new String[3];  // String array with 3 elements
```java
At this point, the array has three "empty boxes" prepared.

### 2. **Assigning to Array Elements**
Use indices (numbers starting from 0) to assign values to each element:
```java
items[0] = "First";   // 1st element
items[1] = "Second";  // 2nd element
items[2] = "Third";   // 3rd element
```java
Note: Indices start at 0, so a 3-element array is accessed with 0, 1, 2.

### 3. **Array Length**
Arrays have a "length" property to get the number of elements:
```java
items.length  // In this case, 3
```java
Using this allows the same code to work even when array size changes.

## 📖 Code Explanation (Step by Step)

### Step 1: Array Declaration
```java
String[] items = new String[3];
```java
This line creates an array that can store 3 String elements. At this point, each element is null (empty).

The "[]" before the variable name indicates it's an array. The "new String[3]" part actually allocates memory for 3 elements.

### Step 2: Assigning Values to Array
```java
items[0] = "The Great Gatsby";
items[1] = "1984";
items[2] = "To Kill a Mockingbird";
```java
Using indices, we assign values to each position in the array. Note that array indices always start at 0. This is a common rule in Java and many other programming languages.

Array state after execution:
- items[0] → "The Great Gatsby"
- items[1] → "1984"
- items[2] → "To Kill a Mockingbird"

### Step 3: Traversing Array with For Loop
```java
for (int i = 0; i < items.length; i++) {
    System.out.println("Item " + (i + 1) + ": " + items[i]);
}
```java
Using a for loop, we process all array elements in order.

- **Initialization**: `int i = 0` - Start counter variable i from 0
- **Condition**: `i < items.length` - Continue while i is less than array length
- **Update**: `i++` - Increment i by 1 each iteration

Inside the loop, we use `(i + 1)` to display numbers starting from 1. This is because indices start at 0, but it's more natural for humans to count "1st, 2nd".

### Step 4: String Concatenation and Output
```java
System.out.println("Item " + (i + 1) + ": " + items[i]);
```java
This line concatenates multiple strings with the "+" operator:
- "Item " - fixed string
- (i + 1) - calculated number
- ": " - separator
- items[i] - array element retrieved

Combining these produces output like "Item 1: The Great Gatsby".

## ⚠️ Common Mistakes

### 1. **Starting Array Index at 1**
```java
// Wrong example
items[1] = "First";  // This is the 2nd element
items[2] = "Second";
items[3] = "Third";  // Error: Out of array bounds
```java
**Reason**: Java array indices start at 0. For a 3-element array, valid indices are 0, 1, 2.

**Correct approach**:
```java
items[0] = "First";   // 1st
items[1] = "Second";  // 2nd
items[2] = "Third";   // 3rd
```java

### 2. **Hardcoding Array Length**
```java
// Not recommended
for (int i = 0; i < 3; i++) {  // 3 is hardcoded
```java
**Reason**: When array size changes, this number must also change. Forgetting to update causes bugs.

**Correct approach**:
```java
for (int i = 0; i < items.length; i++) {  // Use actual array length
```java

### 3. **Using Array Without Initialization**
```java
// Wrong example
String[] items;
items[0] = "First";  // Error: Array not initialized
```java
**Reason**: Arrays cannot be used just by declaration. Initialization (memory allocation) is required.

**Correct approach**:
```java
String[] items = new String[3];  // Initialize before use
items[0] = "First";
```java

## 🚀 Advanced Topics

Hints for deeper learning:

### More Efficient Initialization
You can set values while declaring the array:
```java
String[] items = {"The Great Gatsby", "1984", "To Kill a Mockingbird"};
```java
This way, no size specification or individual assignment is needed.

### Enhanced For Loop (for-each)
From Java 5 onwards, there's a more readable notation:
```java
int index = 1;
for (String item : items) {
    System.out.println("Item " + index + ": " + item);
    index++;
}
```java
However, since we need index numbers here, regular for loops are more suitable.

### Real-world Applications
Arrays are used in scenarios like:
- Managing user information lists
- Storing menu items
- Temporarily holding data
- Storing search results

## 🔗 Related Learning Topics

Topics to learn next or concepts related to this problem:
- **Multi-dimensional Arrays** (Category 004-002): Managing tabular data with arrays of arrays
- **Array Operations** (Category 004-003): Sorting, searching, and copying arrays
- **ArrayList Class** (Category 012): Variable-size list structures
- **Arrays with Loops** (Category 006): Efficient array processing methods.

Test Cases

※ Output examples follow programming industry standards

Input:
Expected Output:
Item 1: The Great Gatsby
Item 2: 1984
Item 3: To Kill a Mockingbird
Input:
Expected Output:
Item 1: Apple
Item 2: Banana
Item 3: Cherry
Item 4: Date
Item 5: Elderberry
Input:
Expected Output:
Item 1: Single Item
Input:
Expected Output:
Error: Array index out of bounds
Input:
Expected Output:
Error: Null array reference
❌ Some tests failed
❌ エラー発生

Your Solution

Current Mode: My Code
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Write your code here

sc.close();
}
}
0 B / 5 MB

You have 6 free executions remaining