Java Arrays — Java Technical Interview Questions & Answers

Java Arrays

Java Arrays

  • An array is a fixed-size row of boxes, all the same type. Create: int[] a = new int[5]; or int[] a = {10, 20, 30}; Indexes start at 0. First item is a[0]. Length is a.length — a field, not a method.
  • Loop with for or for-each. Size cannot grow later. If you need a growing list, use ArrayList. Last valid index is a.length - 1. a[a.length] throws ArrayIndexOutOfBoundsException.
  • Interview line: fixed size, same type, index from 0, length field.
  • Let's take this on the board with one tiny Main class — no extra files. Java Arrays — output: 10 then 20 then 30. Index 0, 1, 2. a[3] would throw ArrayIndexOutOfBoundsException. Start from main, go line by line, and stop at each print. That output is the proof for Arrays.
  index →  0    1    2
  array → [10,  20,  30]
           ↑         ↑
         first   length-1

Technical Interview Tip: Last index is length - 1. Contrast with ArrayList.

Code Examples for Java Arrays

Example

public class Main {
  public static void main(String[] args) {
    int[] a = {10, 20, 30};
    for (int i = 0; i < a.length; i++) {
      System.out.println(a[i]);
    }
  }
}

Java Arrays — output: 10 then 20 then 30. Index 0, 1, 2. a[3] would throw ArrayIndexOutOfBoundsException.

How to Explain Java Arrays to an Interviewer

What is an array?

Fixed-size Same type Index from 0

Is length a method on arrays?

No It is a field: a.length

When do you use ArrayList instead?

When size must grow