- Return variable in java
- Returning a Value from a Method
- Returning a Class or Interface
- Return type in Java | Example Program
- Types of Methods Declaration based on Return type in Java
- How to return primitive values like int, float, double?
- How to return class object in Java?
- How to return current or same class object in Java?
- Ways to return current/same class object
- How to return a variable in Java programming?
- Can we declare return statement inside main method in Java?
Return variable in java
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
Returning a Value from a Method
You declare a method’s return type in its method declaration. Within the body of the method, you use the return statement to return the value.
Any method declared void doesn’t return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
If you try to return a value from a method that is declared void , you will get a compiler error.
Any method that is not declared void must contain a return statement with a corresponding return value, like this:
The data type of the return value must match the method’s declared return type; you can’t return an integer value from a method declared to return a boolean.
The getArea() method in the Rectangle Rectangle class that was discussed in the sections on objects returns an integer:
// a method for computing the area of the rectangle public int getArea()
This method returns the integer that the expression width*height evaluates to.
The getArea method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:
public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env) < Bicycle fastest; // code to calculate which bike is // faster, given each bike's gear // and cadence and given the // environment (terrain and wind) return fastest; >
Returning a Class or Interface
If this section confuses you, skip it and return to it after you have finished the lesson on interfaces and inheritance.
When a method uses a class name as its return type, such as whosFastest does, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number , which is in turn a subclass of Object , as illustrated in the following figure .
The class hierarchy for ImaginaryNumber
Now suppose that you have a method declared to return a Number :
public Number returnANumber()
The returnANumber method can return an ImaginaryNumber but not an Object . ImaginaryNumber is a Number because it’s a subclass of Number . However, an Object is not necessarily a Number it could be a String or another type.
You can override a method and define it to return a subclass of the original method, like this:
public ImaginaryNumber returnANumber()
This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.
Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.
Return type in Java | Example Program
Return type in Java | We know that a method is a function declared inside a class that contains a group of statements.
It is used to perform certain tasks or processing of data in the program to yield the expected results.
A method can accept data from outside and can also return the results. To return the result, a return statement is used inside a method to come out of it to the calling method.
In Java, return is a keyword that is used to exit from the method only with or without returning a value. Every method is declared with a return type in java and it is mandatory for Java methods.
Return type may be a primitive data type like int, float, double, a reference type, or void type which represents “return nothing”. i.e, they don’t give anything back.
When a method is called, the method may return a value to the caller method.
Let’s take an example program to understand the concept of java return type better.
Here, we will write a program to return the square of a number from a method. Look at the following source code.
Program source code 1:
public class Test < int square(int num)< return num * num; // return a square value. >public static void main(String[] args) < // Create an obejct of class Test. Test t = new Test(); // Call the method using object reference variable. Since the return type of this method is int, we will store it using a variable of type int. int squareOfNumber = t.square(20); // Displaying the result. System.out.println("Square of 20: " +squareOfNumber); >>
Explanation: Look at the below figure and understand the explanation that will help you to understand better.
a. In this example program, we have created a method named square(). This method accepts an integer value and calculates the square of it.
After calculating square of value, square() method returns that value to the main() method that is the calling method.
b. Inside the main() method, we are calling square() method using object reference variable t and passing 20 to it as follows: t.square(20);.
c. To get the result returned from the square() method, we have taken a variable “squareOfNumber” of type int as follows: int squareOfNumber = t.square(20);.
d. int before a method name specifies the type of value returned by the method.
e. After method name, we wrote int num as a parameter that receives an integer value into the method. We are passing a value 20 to the method at the time of calling from main method.
f. Now to calculate the square value and return it, we have used return statement (return num * num;) inside the square() method.
Thus, a return statement in java is used to return a value from a method. It can return only one value at a time. When a return statement is used inside the method, the flow of execution comes out of it and goes back to the caller method.
Types of Methods Declaration based on Return type in Java
1. Method with void type :
Here, the void represents “return nothing”. A return type void is used when there is no return value.
2. Methods with return type and value :
If a method is having int, double, float, etc other than void, we must return a value compatible with the declared return type by using the return statement.
If you are not returning any value, it will generate an error message like ” missing return statements “. Let’s take some examples related to it.
Code 2 is an invalid code because, inside the method, the return statement must be the last statement of method.
How to return primitive values like int, float, double?
Let’s take an example program where we will return primitive values like int, float, and char to methods m1(), m2(), and m3() respectively.
Program source code 2:
public class Sample < // Declare a method with return type int. int m1() < System.out.println("m1 method"); // If you declare a method to return a value, you must return a value of declared type. Since the return type of m1() method is an integer. So, we will have to return an integer value. return 20; >Similarly, float m2() < System.out.println("m2 method"); return 20.5f; >static char m3() < System.out.println("m3 method"); return 'd'; >public static void main(String[] args) < // Create an object of the class named Sample. Sample s = new Sample(); // Call m1() method using reference variable s. Since s.m1() is returning an integer value, we will store value by using a variable x with a data type int. int x = s.m1(); // Now print the return value. System.out.println("Return value of m1()= " +x); Similarly, float y = s.m2(); System.out.println("Return value of m2()= " +y); // Call static method using the class name. Since m3() method returns character, we will store a character using a variable ch with type char. char ch = Sample.m3(); System.out.println("Return value of m3() code-block code-block-2" style="margin: 8px 0; clear: both;">