Java Method Return Types

🔹 Java Method Return Types

The return type of a method specifies what type of value the method will return to the caller. If a method does not return a value, we use void.


1. Syntax

modifier returnType methodName(parameters) {
// code
return value; // required if returnType is not void
}
  • returnType → data type of the value returned (int, double, String, etc.)

  • return statement → used to send a value back


2. Example 1: Method with int Return Type

public class Main {
static int add(int a, int b) {
return a + b; // returns an int
}

public static void main(String[] args) {
int result = add(5, 10);
System.out.println("Sum = " + result);
}
}

📌 Output:

Sum = 15

3. Example 2: Method with double Return Type

public class Main {
static double multiply(double a, double b) {
return a * b; // returns a double
}

public static void main(String[] args) {
double result = multiply(3.5, 2.0);
System.out.println("Product = " + result);
}
}

📌 Output:

Product = 7.0

4. Example 3: Method with String Return Type

public class Main {
static String greet(String name) {
return "Hello, " + name + "!";
}

public static void main(String[] args) {
String message = greet("Alice");
System.out.println(message);
}
}

📌 Output:

Hello, Alice!

5. Example 4: Method with void Return Type

public class Main {
static void printMessage(String message) {
System.out.println(message);
}

public static void main(String[] args) {
printMessage("Welcome to Java!");
}
}

📌 Output:

Welcome to Java!

Note: void methods do not return a value, so no return statement with value is allowed.


6. Example 5: Using Method Return in Another Method

public class Main {
static int square(int x) {
return x * x;
}

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

public static void main(String[] args) {
System.out.println("Sum of squares = " + sumOfSquares(3, 4));
}
}

📌 Output:

Sum of squares = 25

🧠 Key Points

  • The return type defines what type of value a method gives back.

  • Use void if nothing is returned.

  • A method can call another method and use its return value.

  • Always match the return type with the value being returned.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *