⬅ Previous Topic
Java public KeywordNext Topic ⮕
Java short Keyword⬅ Previous Topic
Java public KeywordNext Topic ⮕
Java short Keywordreturn
Keyword in JavaThe return
keyword in Java is used to exit from a method and optionally send a value back to the caller. It plays a central role in method communication, allowing you to write reusable and logical code blocks.
return
Used?The return
keyword can be used in two scenarios:
void
.return
return; // Used in void methods
return expression; // Used to return a value from non-void methods
return
to Exit a void
Methodpublic class Demo {
public static void greet(String name) {
if (name == null) {
System.out.println("No name provided.");
return; // exits the method early
}
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
greet(null);
greet("Alice");
}
}
No name provided.
Hello, Alice
When name
is null
, the return
statement exits the method immediately, skipping the greeting message.
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(10, 20);
System.out.println("Sum: " + result);
}
}
Sum: 30
The method add
returns the sum of two integers using the return
keyword. The value is stored in the result
variable in main
and printed.
public class GradeChecker {
public static String getGrade(int score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "F";
}
public static void main(String[] args) {
System.out.println(getGrade(85));
System.out.println(getGrade(65));
}
}
B
F
This shows how return
is used in multiple decision paths. The method exits immediately once a matching condition is found.
return
int
, String
, etc.), it must return a value.void
, you can use return;
to exit early, but it’s optional.return
statement in a method is unreachable and will cause a compile-time error.public class Demo {
public static int getNumber(boolean flag) {
if (flag) {
return 10;
}
// Compile-time error: missing return statement
}
}
return
early to avoid unnecessary nesting of logic.return
You should avoid using return
inside deeply nested blocks unless it improves readability. In large methods, excessive returns may reduce clarity.
The return
keyword in Java serves as the bridge between a method’s logic and its output. Whether you’re cutting short a method’s execution or sending back computed results, mastering return
helps write effective, modular Java code.
return
keyword do in a void
method?return
statements?⬅ Previous Topic
Java public KeywordNext Topic ⮕
Java short KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.