Home Java Tutorial Java method return types

Java method return types

by Team Impactmillions
27 minutes read

In this tutorial, you’ll learn about Java method return types, Basic Return Types, Method with void Return Type, Method with a Primitive Return Type along with examples and Why Use Return Types.

  • The return type of a method defines what kind of value the method will return after it completes its execution.
  • If a method performs some calculations or operations, it can send the result back to the part of the program that called it.

Basic Return Types

  • void: This return type means the method does not return any value.
  • Primitive Types: These include int, double, char, boolean, etc., which are the basic data types in Java.
  • Reference Types: These include objects and arrays, such as String, ArrayList, and custom objects.

Method with void Return Type

A method with a void return type doesn’t return any value. It just performs an action.

public class MyProgram {
    public static void sayHelloWorld() {
        System.out.println("Hello, World!");
    }

    public static void main(String[] args) {
        sayHelloWorld(); // Call the sayHelloWorld method
    }
}

In this example, the sayHelloWorld method prints “Hello, World!” but doesn’t return anything.

Method with a Primitive Return Type

Let’s create a method that returns an integer (int).

public class MyProgram {
    public static int add(int a, int b) {
        return a + b; // The method returns the sum of a and b
    }

    public static void main(String[] args) {
        int result = add(5, 3); // Call the add method and store the result
        System.out.println("The sum is: " + result);
    }
}

In this example:

  1. The add method takes two parameters (int a and int b).
  2. It returns the sum of a and b.
  3. The main method calls add, stores the returned value in result, and prints it.

Method with a Reference Return Type

Let’s create a method that returns a String.

public class MyProgram {
    public static String greet(String name) {
        return "Hello, " + name + "!"; // The method returns a greeting message
    }

    public static void main(String[] args) {
        String message = greet("Alice"); // Call the greet method and store the result
        System.out.println(message);
    }
}

In this example:

  • The greet method takes one parameter (String name).
  • It returns a greeting message.
  • The main method calls greet, stores the returned message in message, and prints it.

Why Use Return Types?

  • Reuse Calculations: Methods can perform calculations and return the result to be used elsewhere in the program.
  • Reduce Complexity: By breaking down complex operations into smaller methods that return results, your code becomes easier to manage and understand.
  • Improve Code Quality: Clear return types make your code more predictable and easier to debug.

related posts

Leave a Comment

Enable Notifications OK No thanks