Skip to main content

03 - Methods and Basic Data Structures

Methods in Java: definition, parameters, overloading, pass by value. One-dimensional and multidimensional arrays, common operations.

What do you think about this article?

At a Glance

Methods in Java: definition, parameters, overloading, pass by value. One-dimensional and multidimensional arrays, common operations.

Methods in Java

Methods are reusable blocks of code that perform specific tasks. They help organize code, avoid duplication, and make programs more readable and maintainable.

What You Will Learn

  • Define and call methods
  • Parameters and return values
  • Method overloading
  • Pass by value vs reference
  • One-dimensional and multidimensional arrays
  • Common array operations

Anatomy of a Method

Basic Structure
// General syntax
modifiers returnType methodName(parameters) {
    // method body
    return value; // if not void
}

// Concrete example
public static double calculateAverage(int[] grades) {
    int sum = 0;
    for (int grade : grades) {
        sum += grade;
    }
    return (double) sum / grades.length;
}

Method Components

Component Description Example
Modifiers Visibility and behavior public, private, static
Return type Type of returned value int, String, void
Name Method identifier calculateAverage, printGrades
Parameters Method input (int[] grades, int threshold)

void vs Return Methods

Method Types
// void method: returns nothing
public static void printHeader() {
    System.out.println("╔═══════════════════════════╗");
    System.out.println("║     SCHOOL REGISTRY       ║");
    System.out.println("╚═══════════════════════════╝");
}

// Method with return: returns a value
public static boolean isPassing(double average) {
    return average >= 6.0;
}

// Method returning String
public static String getAssessment(int grade) {
    if (grade >= 9) return "Excellent";
    if (grade >= 7) return "Good";
    if (grade >= 6) return "Satisfactory";
    return "Insufficient";
}

Method Parameters

Passing Parameters
// Single parameters
public static int sum(int a, int b) {
    return a + b;
}

// Multiple parameters of same type
public static double calculateWeightedAverage(int grade1, int weight1, int grade2, int weight2) {
    return (double)(grade1 * weight1 + grade2 * weight2) / (weight1 + weight2);
}

// Varargs parameters (variable number)
public static int sumGrades(int... grades) {
    int sum = 0;
    for (int grade : grades) {
        sum += grade;
    }
    return sum;
}

// Using varargs
int total1 = sumGrades(7, 8, 6);           // 21
int total2 = sumGrades(9, 8, 7, 6, 8, 9);  // 47

Method Overloading

Overloading allows defining multiple methods with the same name but different parameters (number, type, or order).

Overloading
public class GradeCalculator {

    // Calculate average of 2 grades
    public static double average(int g1, int g2) {
        return (g1 + g2) / 2.0;
    }

    // Calculate average of 3 grades
    public static double average(int g1, int g2, int g3) {
        return (g1 + g2 + g3) / 3.0;
    }

    // Calculate average of an array
    public static double average(int[] grades) {
        int sum = 0;
        for (int g : grades) sum += g;
        return (double) sum / grades.length;
    }

    // Calculate weighted average
    public static double average(int[] grades, double[] weights) {
        double weightedSum = 0;
        double totalWeight = 0;
        for (int i = 0; i < grades.length; i++) {
            weightedSum += grades[i] * weights[i];
            totalWeight += weights[i];
        }
        return weightedSum / totalWeight;
    }
}

// Usage - compiler chooses the right method
double m1 = GradeCalculator.average(7, 8);              // 7.5
double m2 = GradeCalculator.average(7, 8, 9);           // 8.0
double m3 = GradeCalculator.average(new int[]{7,8,9});  // 8.0

Pass by Value

In Java, all parameters are passed by value. This means the method receives a copy of the value.

Pass by Value - Primitives
public static void incrementGrade(int grade) {
    grade++; // modifies local copy
    System.out.println("Inside method: " + grade);
}

public static void main(String[] args) {
    int myGrade = 7;
    incrementGrade(myGrade);
    System.out.println("After call: " + myGrade); // Still 7!
}

// Output:
// Inside method: 8
// After call: 7
Pass by Value - Arrays (Reference)
// Arrays pass the reference (but still by value!)
public static void incrementAllGrades(int[] grades) {
    for (int i = 0; i < grades.length; i++) {
        grades[i]++; // modifies original array!
    }
}

public static void main(String[] args) {
    int[] classGrades = {6, 7, 8};
    incrementAllGrades(classGrades);
    // Now classGrades = {7, 8, 9} - original array was modified!
}

Primitives vs References

  • Primitives: Method works on a copy, original doesn't change
  • Arrays/Objects: Method receives a copy of reference, so it can modify the original object

Arrays in Java

An array is a data structure that stores elements of the same type in contiguous memory locations, accessible by index.

Declaration and Initialization

Creating Arrays
// Separate declaration and allocation
int[] grades;                    // declaration
grades = new int[5];             // allocation (5 elements initialized to 0)

// Declaration and allocation together
String[] subjects = new String[4];  // 4 null elements

// Initialization with values
int[] classGrades = {7, 8, 6, 9, 8};
String[] coreSubjects = {"English", "Math", "History", "Spanish"};

// Explicit initialization with new
int[] numbers = new int[]{1, 2, 3, 4, 5};

Accessing Elements

Reading and Writing
int[] grades = {7, 8, 6, 9, 8};

// Read access (index from 0 to length-1)
int firstGrade = grades[0];    // 7
int lastGrade = grades[4];     // 8
int thirdGrade = grades[2];    // 6

// Write access
grades[2] = 7;  // now array is {7, 8, 7, 9, 8}

// Array length
int gradeCount = grades.length;  // 5

// CAUTION: out of bounds index causes ArrayIndexOutOfBoundsException
// grades[5] = 10; // ERROR! Maximum index is 4

Iterating Over Arrays

Array Loops
String[] students = {"John", "James", "Anna", "Sarà"};
int[] grades = {7, 8, 6, 9};

// Classic for (useful when index is needed)
System.out.println("=== Grade Registry ===");
for (int i = 0; i < students.length; i++) {
    System.out.println(students[i] + ": " + grades[i]);
}

// for-each (cleaner when index not needed)
System.out.println("\n=== Student List ===");
for (String student : students) {
    System.out.println("- " + student);
}

// Calculate average with for-each
int sum = 0;
for (int grade : grades) {
    sum += grade;
}
double average = (double) sum / grades.length;

Common Operations

Array Utilities
import java.util.Arrays;

int[] grades = {7, 9, 6, 8, 7};

// Sorting
Arrays.sort(grades);  // {6, 7, 7, 8, 9}

// Binary search (array must be sorted!)
int index = Arrays.binarySearch(grades, 8);  // 3

// Array comparison
int[] otherGrades = {6, 7, 7, 8, 9};
boolean equal = Arrays.equals(grades, otherGrades);  // true

// Array copy
int[] gradesCopy = Arrays.copyOf(grades, grades.length);
int[] firstThree = Arrays.copyOfRange(grades, 0, 3);  // {6, 7, 7}

// Fill array
int[] newGrades = new int[5];
Arrays.fill(newGrades, 6);  // {6, 6, 6, 6, 6}

// Print array
System.out.println(Arrays.toString(grades));  // [6, 7, 7, 8, 9]

Multidimensional Arrays

Matrices (2D Arrays)
// Grade matrix: rows = students, columns = subjects
int[][] classRegistry = {
    {7, 8, 6, 9},  // John: Eng, Math, Hist, Span
    {8, 9, 7, 8},  // James
    {6, 7, 6, 7},  // Anna
    {9, 8, 8, 9}   // Sarà
};

String[] students = {"John", "James", "Anna", "Sarà"};
String[] subjects = {"English", "Math", "History", "Spanish"};

// Access: classRegistry[row][column]
int johnMathGrade = classRegistry[0][1];  // 8
int saraSpanishGrade = classRegistry[3][3];  // 9

// Complete iteration
System.out.println("╔══════════════════════════════════════════════╗");
System.out.println("║               CLASS REGISTRY                 ║");
System.out.println("╠══════════════════════════════════════════════╣");

for (int i = 0; i < students.length; i++) {
    System.out.printf("║ %-8s: ", students[i]);
    double sum = 0;
    for (int j = 0; j < subjects.length; j++) {
        System.out.printf("%d ", classRegistry[i][j]);
        sum += classRegistry[i][j];
    }
    System.out.printf("| Average: %.1f ║%n", sum / subjects.length);
}
System.out.println("╚══════════════════════════════════════════════╝");
Jagged Arrays
// Arrays with rows of different lengths
int[][] gradesPerSemester = new int[2][];
gradesPerSemester[0] = new int[]{7, 8, 6};     // S1: 3 grades
gradesPerSemester[1] = new int[]{8, 9, 7, 8};  // S2: 4 grades

// Iterating over jagged arrays
for (int s = 0; s < gradesPerSemester.length; s++) {
    System.out.print("Semester " + (s+1) + ": ");
    for (int grade : gradesPerSemester[s]) {
        System.out.print(grade + " ");
    }
    System.out.println();
}

Complete Example: Registry Management

RegistryManagement.java
package edu.school.registry;

import java.util.Arrays;

public class RegistryManagement {

    // Constants
    private static final int MIN_GRADE = 1;
    private static final int MAX_GRADE = 10;
    private static final double PASSING_THRESHOLD = 6.0;

    public static void main(String[] args) {
        // Registry data
        String[] students = {"John Smith", "James Green", "Anna White", "Sarà Black"};
        String[] subjects = {"English", "Math", "History", "Spanish", "Science"};

        int[][] grades = {
            {7, 8, 6, 9, 7},  // John
            {8, 9, 7, 8, 8},  // James
            {6, 5, 6, 7, 6},  // Anna
            {9, 8, 8, 9, 9}   // Sarà
        };

        // Print complete registry
        printRegistry(students, subjects, grades);

        // Statistics per student
        System.out.println("\n=== STUDENT STATISTICS ===");
        for (int i = 0; i < students.length; i++) {
            analyzeStudent(students[i], grades[i]);
        }

        // Statistics per subject
        System.out.println("\n=== SUBJECT STATISTICS ===");
        for (int j = 0; j < subjects.length; j++) {
            int[] subjectGrades = extractColumn(grades, j);
            System.out.printf("%s: Average %.2f%n", subjects[j], calculateAverage(subjectGrades));
        }
    }

    // Print formatted registry
    public static void printRegistry(String[] students, String[] subjects, int[][] grades) {
        System.out.println("╔════════════════════════════════════════════════════════════╗");
        System.out.println("║                      CLASS REGISTRY                        ║");
        System.out.println("╠════════════════════════════════════════════════════════════╣");

        // Subject header
        System.out.print("║ Student         │");
        for (String s : subjects) {
            System.out.printf(" %-4s│", s.substring(0, Math.min(4, s.length())));
        }
        System.out.println(" Avg   ║");
        System.out.println("╠═════════════════╪══════════════════════════════════════════╣");

        // Student rows
        for (int i = 0; i < students.length; i++) {
            System.out.printf("║ %-15s │", students[i]);
            for (int grade : grades[i]) {
                System.out.printf("  %2d │", grade);
            }
            System.out.printf(" %.2f ║%n", calculateAverage(grades[i]));
        }
        System.out.println("╚════════════════════════════════════════════════════════════╝");
    }

    // Analyze a single student
    public static void analyzeStudent(String name, int[] grades) {
        double average = calculateAverage(grades);
        int max = findMax(grades);
        int min = findMin(grades);
        int failures = countFailures(grades);

        System.out.println("\n" + name + ":");
        System.out.printf("  Average: %.2f%n", average);
        System.out.printf("  Max grade: %d, Min grade: %d%n", max, min);
        System.out.printf("  Failing grades: %d%n", failures);
        System.out.printf("  Outcome: %s%n", determineOutcome(average, failures));
    }

    // Calculate average of grade array
    public static double calculateAverage(int[] grades) {
        if (grades == null || grades.length == 0) return 0;
        int sum = 0;
        for (int g : grades) sum += g;
        return (double) sum / grades.length;
    }

    // Find maximum grade
    public static int findMax(int[] grades) {
        int max = grades[0];
        for (int g : grades) {
            if (g > max) max = g;
        }
        return max;
    }

    // Find minimum grade
    public static int findMin(int[] grades) {
        int min = grades[0];
        for (int g : grades) {
            if (g < min) min = g;
        }
        return min;
    }

    // Count failing grades
    public static int countFailures(int[] grades) {
        int count = 0;
        for (int g : grades) {
            if (g < 6) count++;
        }
        return count;
    }

    // Determine final outcome
    public static String determineOutcome(double average, int failures) {
        if (average >= PASSING_THRESHOLD && failures == 0) {
            return "PASSED";
        } else if (failures <= 2) {
            return "CONDITIONAL - Makeup exams required";
        } else {
            return "NOT PASSED";
        }
    }

    // Extract column from matrix (grades for one subject)
    public static int[] extractColumn(int[][] matrix, int columnIndex) {
        int[] column = new int[matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            column[i] = matrix[i][columnIndex];
        }
        return column;
    }

    // Validate a grade
    public static boolean isValidGrade(int grade) {
        return grade >= MIN_GRADE && grade <= MAX_GRADE;
    }
}

Conclusion

In this article we explored methods in Java, from definition to overloading, and basic data structures like one-dimensional and multidimensional arrays.

In the next article we will begin Object-Oriented Programming (OOP): classes, objects, state and behavior.

Key Points to Remember

  • Methods: Reusable code blocks with name, parameters and return
  • void: Methods that return nothing
  • Overloading: Same name, different parameters
  • Pass by value: Primitives are copied, objects pass reference
  • Arrays: Fixed-size structures, index from 0
  • Arrays utility: sort(), binarySearch(), copyOf(), toString()

Frequently asked questions

What is the purpose of methods in Java programming?

Methods are reusable blocks of code that perform specific tasks, helping to organize code, avoid duplication, and make programs more readable and maintainable.

How does method overloading work in Java?

Overloading allows defining multiple methods with the same name but different parameters (number, type, or order).

What is the default behavior when passing variables as method parameters in Java?

In Java, all parameters are passed by value, meaning the method receives a copy of the value.

What is an array in Java programming?

An array is a data structure that stores elements of the same type in contiguous memory locations, accessible by index.

Sources and further reading

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects