How do I create an object from a class in Java?

A class defines the data and behavior of its objects. You can create an object using the new keyword, then access its fields and call its methods.

In this example, you will create two objects from a Book class. Each object stores its own title and author.

Source code

public class ObjectCreationExample {
    void main() {
        Book firstBook = new Book();
        firstBook.title = "Learning Java";
        firstBook.author = "Alice";

        Book secondBook = new Book();
        secondBook.title = "Exploring Java";
        secondBook.author = "Bob";

        firstBook.printDetails();
        secondBook.printDetails();
    }
}

class Book {
    String title;
    String author;

    void printDetails() {
        IO.println("Title: " + title);
        IO.println("Author: " + author);
        IO.println();
    }
}

Explanation

The Book class declares two fields and one method:

class Book {
    String title;
    String author;

    void printDetails() {
        IO.println("Title: " + title);
        IO.println("Author: " + author);
        IO.println();
    }
}

The fields title and author hold the data for each book. The printDetails() method prints that data.

The following statement creates a Book object:

Book firstBook = new Book();

Each part has a purpose:

Part Purpose
Book Declares the variable’s type
firstBook Names the variable that refers to the object
new Book() Creates and initializes a new Book object

Because Book does not declare a constructor, Java provides a default constructor with no parameters.

After creating the object, you can assign values to its fields using the dot operator:

firstBook.title = "Learning Java";
firstBook.author = "Alice";

You also use the dot operator to call a method:

firstBook.printDetails();

The second call to new Book() creates a separate object:

Book secondBook = new Book();

Each object has its own instance fields. Setting the title of secondBook does not change the title of firstBook.

Both classes are placed in the same source file. Only ObjectCreationExample is declared public, so the file is named ObjectCreationExample.java.

Run the example

Compile and run the file:

javac ObjectCreationExample.java
java ObjectCreationExample

Output

Title: Learning Java
Author: Alice

Title: Exploring Java
Author: Bob

This example assigns fields directly to show how objects work. In the next example, you will use a constructor to supply these values when creating each object.

How do I pass a variable number of arguments to a method in Java?

You can use varargs to let a method accept any number of arguments of the same type. Declare a varargs parameter by adding three dots (...) after its type.

In this example, you will create a method that adds integers. You can call it with two numbers, several numbers, or no numbers.

Source code

public class VarargsExample {
    void main() {
        IO.println("Sum of two numbers: " + sum(10, 20));
        IO.println("Sum of four numbers: " + sum(5, 10, 15, 20));
        IO.println("Sum with no arguments: " + sum());

        int[] numbers = {3, 6, 9};
        IO.println("Sum of array elements: " + sum(numbers));
    }

    int sum(int... numbers) {
        int total = 0;

        for (int number : numbers) {
            total += number;
        }

        return total;
    }
}

Explanation

The sum() method declares a varargs parameter:

int sum(int... numbers) {

The declaration int... numbers lets callers pass zero or more int values. Inside the method, numbers is an int[] array.

For example, this call passes two values:

sum(10, 20)

Inside the method, numbers contains 10 and 20.

The method starts with a total of zero, then adds each element:

int total = 0;

for (int number : numbers) {
    total += number;
}

The statement total += number adds the current number to total. After the loop finishes, the method returns the total.

When you call the method without arguments:

sum()

Java supplies an empty array. The loop has no elements to process, so the method returns 0.

You can also pass an existing array directly:

int[] numbers = {3, 6, 9};
sum(numbers);

The method reads the array elements and returns 18.

Run the example

Compile and run the file:

javac VarargsExample.java
java VarargsExample

Output

Sum of two numbers: 30
Sum of four numbers: 50
Sum with no arguments: 0
Sum of array elements: 18

Rules to remember

A method can have only one varargs parameter, and it must be the last parameter.

For example, this declaration is valid:

int sum(String label, int... numbers)

This declaration is invalid because another parameter appears after the varargs parameter:

int sum(int... numbers, String label)

Use varargs when callers should be able to supply different numbers of values without creating an array explicitly.

How do I overload a method in Java?

Method overloading lets you define multiple methods with the same name but different parameter lists. You can use it to perform a similar task with different inputs.

In this example, you will create three add() methods to add two integers, three integers, or two floating-point numbers.

Source code

public class MethodOverloadingExample {
    void main() {
        int twoIntegerSum = add(10, 20);
        int threeIntegerSum = add(10, 20, 30);
        double twoDoubleSum = add(2.5, 3.75);

        IO.println("Sum of two integers: " + twoIntegerSum);
        IO.println("Sum of three integers: " + threeIntegerSum);
        IO.println("Sum of two doubles: " + twoDoubleSum);
    }

    int add(int first, int second) {
        return first + second;
    }

    int add(int first, int second, int third) {
        return first + second + third;
    }

    double add(double first, double second) {
        return first + second;
    }
}

Explanation

All three methods are named add(), but their parameter lists differ:

Method Parameters
add(int first, int second) Two integers
add(int first, int second, int third) Three integers
add(double first, double second) Two doubles

When you call an overloaded method, the compiler selects the applicable version based on the number and types of the arguments.

The following call passes two int values:

int twoIntegerSum = add(10, 20);

It selects add(int, int) and returns 30.

This call passes three int values:

int threeIntegerSum = add(10, 20, 30);

It selects add(int, int, int) and returns 60.

Finally, this call passes two double values:

double twoDoubleSum = add(2.5, 3.75);

It selects add(double, double) and returns 6.25.

Run the example

Compile and run the file:

javac MethodOverloadingExample.java
java MethodOverloadingExample

Output

Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 6.25

Rules to remember

Overloaded methods must differ in the number, types, or order of their parameter types.

Changing only the parameter names does not create a different overload. Changing only the return type is also insufficient. For example, these two declarations cannot appear together in the same class:

int add(int first, int second) {
    return first + second;
}

double add(int first, int second) {
    return first + second;
}

Both methods have the same name and parameter types, so the compiler reports an error.

How do I create a method that returns a value in Java?

A method can perform a task and return a result to the code that calls it. You can store that result in a variable or use it in another expression.

In this example, you will create a method that adds two integers and returns their sum.

Source code

public class ReturnValueExample {
    void main() {
        int firstNumber = 12;
        int secondNumber = 8;

        int result = add(firstNumber, secondNumber);

        IO.println("First number: " + firstNumber);
        IO.println("Second number: " + secondNumber);
        IO.println("Sum: " + result);
    }

    int add(int first, int second) {
        return first + second;
    }
}

Explanation

The add() method accepts two integers and returns an integer:

int add(int first, int second) {
    return first + second;
}

Each part of the declaration has a purpose:

Part Purpose
int before add Specifies the type of value the method returns
add Names the method
int first, int second Declares the parameters that receive the input values
return first + second; Adds the values and returns the result

The return statement ends the current method call and sends a value back to the caller.

Inside main(), the following statement calls the method:

int result = add(firstNumber, secondNumber);

The values of firstNumber and secondNumber are passed as arguments. Inside add(), the parameters first and second receive those values.

The method calculates 12 + 8 and returns 20. That value is then assigned to result.

Both main() and add() are instance methods in this example. Java 25 supports an instance main() method, so you can call add() directly without making either method static.

Run the example

Compile and run the file:

javac ReturnValueExample.java
java ReturnValueExample

Output

First number: 12
Second number: 8
Sum: 20

Returning a value versus printing it

The add() method returns its result without printing it. The calling code decides what to do with that value.

For example, you can use the returned value in another calculation:

int doubledSum = add(12, 8) * 2;

Here, add(12, 8) returns 20, which is multiplied by two. The value of doubledSum becomes 40.

Use a return type such as int when a method needs to provide a result. Use void when the method does not return a value.

How do I loop through a two-dimensional array in Java?

You can use nested enhanced for loops to read every element in a two-dimensional array. The outer loop reads each row, and the inner loop reads the values in that row.

In this example, you will print a grid of integers, with each row on a separate line.

Source code

public class TwoDimensionalArrayExample {
    void main() {
        int[][] numbers = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        for (int[] row : numbers) {
            String separator = "";

            for (int number : row) {
                IO.print(separator + number);
                separator = " ";
            }

            IO.println();
        }
    }
}

Explanation

The following declaration creates a two-dimensional array:

int[][] numbers = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};

In Java, a two-dimensional array is an array whose elements are arrays. Here, numbers contains three rows, and each row contains three integers.

The outer loop reads one row at a time:

for (int[] row : numbers) {

The variable row has the type int[] because each row is an array of integers.

Inside the outer loop, the inner loop reads each number in the current row:

for (int number : row) {
    IO.print(separator + number);
    separator = " ";
}

IO.print() writes output without starting a new line.

The separator variable starts as an empty string for each row. After printing the first number, it becomes a space. This places spaces between the numbers without adding a trailing space.

After the inner loop finishes, the following statement starts a new line:

IO.println();

The outer loop then moves to the next row.

Run the example

Compile and run the file:

javac TwoDimensionalArrayExample.java
java TwoDimensionalArrayExample

Output

1 2 3
4 5 6
7 8 9

Rows with different lengths

The same loop also works when rows contain different numbers of elements. For example, replace the array declaration with:

int[][] numbers = {
        {1, 2},
        {3, 4, 5},
        {6}
};

The output becomes:

1 2
3 4 5
6

Each inner loop processes the elements in its current row, so the rows do not need to have the same length.