Miscellaneous
☰Fullscreen
Table of Content:
🔹 Official Rule in Java
A method can have only one return type.
Example:
public int getNumber() {
return 10; // ✅ One value
}
Here → return type is int → so it returns only one int value.
❓ Then how do people return multiple values?
In Java, you cannot return multiple values directly like this:
return 10, 20; // ❌ Not allowed
But you can return one object that contains multiple values.
✅ Method 1: Return an Array
public int[] getNumbers() {
return new int[]{10, 20, 30};
}
➡ Still returning one object (array)
➡ But that object contains multiple values
✅ Method 2: Return a Custom Class Object (Best Practice)
class Student {
String name;
int age;
}
public Student getStudent() {
Student s = new Student();
s.name = "Rumman";
s.age = 25;
return s;
}
➡ Returning one Student object
➡ That object holds multiple data members
🎯 Final Answer
👉 In Java, a method can return only one value.
👉 That value can be:
-
Primitive type
-
Object
-
Array
-
Collection
But technically → only one return value at a time.