Java Tutorial

Methods and Arrays

Create reusable methods and store fixed-size sequences in arrays.

Concept

Methods define reusable behavior. A method signature includes its name and parameter types, while its declared return type describes the result.

Arrays hold a fixed number of elements of one declared type. Indexes begin at zero, so valid indexes range from zero through length minus one.

Example

static int add(int a, int b) {
    return a + b;
}

int[] marks = {72, 81, 65};
System.out.println(add(marks[0], marks[1]));
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.

Practice Tasks

  1. Write a max(int a, int b) method.
  2. Find the average of an integer array.
  3. Reverse an array without using a collection.

Key Takeaways

  • Methods improve reuse.
  • Arrays are fixed-size.
  • Check array bounds carefully.