Java Questions 21 - 30  «Prev  Next»

Arrays and Final References in Java SE 25

Review array declarations, allocation, component types, runtime store checks, and the limits of final.

  1. What is an array?

    Answer: An array is an object containing a fixed number of component variables of one component type. Components are accessed using zero-based integer indices. The array's length is fixed when it is created, although its components can normally be assigned new values.

    Array length is obtained through the length field, not a length method. An array may have length zero. Access outside the valid index range throws ArrayIndexOutOfBoundsException; an array does not automatically grow when a new index is used.

  2. Which kinds of values can array components hold?

    Answer: A component type can be primitive or reference-valued. An int array stores int values, while a String array stores String references or null. Reference components do not hold whole object copies.

    Arrays can also have array component types, as in int[][], producing arrays of arrays rather than necessarily a rectangular grid. Reference-array covariance permits some assignments to broader array types, but stores are checked against the actual array type at runtime.

  3. Where are an array and the objects it references stored?

    Answer: The array itself is an object in the JVM heap model. In a reference array, components hold references to other objects; allocating the array does not allocate a new instance of its component class for every slot.

    For example, new Thread[3] creates one array whose three elements initially contain null. It creates no Thread objects. Local versus field placement of the variable referencing that array does not change the array's object semantics, and physical optimization details remain implementation-dependent.


  4. How do you declare and use an array variable?

    Answer: Declare a type such as int[] scores, then assign an array reference before reading the local. You can combine declaration and allocation as int[] scores = new int[3];, or use an initializer such as int[] scores = {2, 4, 6};.

    Writing int scores[] is also legal, but keeping the brackets with the type is usually clearer. A declaration by itself does not allocate an array. An array reference field defaults to null until assigned; an unassigned local cannot be read.

  5. How do you declare arrays of int values and Thread references?

    Answer: Use int[] keys; and Thread[] threads;. The standard class name is Thread, not Threads. These declarations define reference variables, not individual int values or started threads.

    New int[2] initializes both components to zero. New Thread[2] initializes both to null. Assign a constructed Thread to an element and start it explicitly if execution is required. An array of references does not perform its elements' construction or lifecycle management for you.

  6. Where is an array's size specified?

    Answer: In an array creation expression, such as new int[5], not inside the declared type. The declaration int[5] scores; is illegal. A combined declaration and initialization may certainly contain a size on the initializer side.

    import java.util.Arrays;
    
    public class ArrayCreation {
        public static void main(String[] args) {
            final int[] values = new int[4];
            for (int i = 0; i < values.length; i++) values[i] = i;
            values[0] = 9;
            System.out.println(Arrays.toString(values));
            Object[] names = new String[1];
            try {
                names[0] = Integer.valueOf(7);
            } catch (ArrayStoreException expected) {
                System.out.println("Incompatible array store");
            }
        }
    }

    This prints [9, 1, 2, 3], then Incompatible array store. The second operation is accepted using the Object[] reference type but rejected by the actual String[] object's runtime store check.


  7. When is space for an array requested?

    Answer: When an array creation expression or array initializer is evaluated, not merely when a reference variable is declared. Components receive their default or explicitly supplied values as part of array creation.

    A negative requested length causes NegativeArraySizeException; a valid length can still exceed available resources. Reassigning an array variable to a differently sized array replaces the reference rather than resizing the original array. Other references can continue to refer to the original.

  8. What does final mean on an array or object reference variable?

    Answer: After initialization, the variable cannot be reassigned to another reference or null. Final does not prevent changing accessible mutable state in the referenced object. In the example above, final int[] values still permits values[0] = 9.

    A blank final local may be assigned later when definite-assignment rules allow it. Once assigned, the fixed reference and the mutability of the target remain separate properties. Final alone does not make concurrent mutation safe.

  9. Is a final object the same as an immutable object?

    Answer: No. Final can modify a variable or class declaration, but it is not an object-level immutability switch. A final class cannot be subclassed and may still contain mutable fields; a final reference cannot be reassigned and may still point to mutable state.

    Immutability requires a design that prevents observable state changes, including through exposed references. Arrays are mutable even when reached through final variables. Copying or wrapping data can help define an API boundary, but shallow copies do not freeze referenced elements.

  10. What are the main meanings of final?

    Answer: A final class cannot be subclassed. A final instance method cannot be overridden, and a final static method cannot be hidden. A final variable can be assigned only according to the language's one-assignment rules.

    These rules do not all describe immutability. Final does not prevent overloading a method, does not make array components final, and does not supply a lock. Apply the meaning that corresponds to the declaration being modified rather than treating final as a universal restriction on change.

References: Arrays, Final variables, and Array expressions.