return keyword in java
The "return"
keyword causes a method to return to the method that called it, passing a value that matches the return type of the returning method.
In other words,
The return
keyword is used to stop the execution of a method and return a value to the caller.
Example
return for a void method will stop the further execution of a method
- public void displayName(String name)
- {
- System.out.println("Name -> "+name);
- return;
- }
public void displayName(String name) { System.out.println("Name -> "+name); return; }
If the method has a non−void return type, the return statement must have an argument of the same or a compatible type as shown in below examples.
returning String
from a method
- public String getName()
- {
- String s = "Raj";
- return s;
- }
public String getName() { String s = "Raj"; return s; }
returning double
from a method
- public double getTotalAmount()
- {
- double d = 500.5;
- return(d);
- }
public double getTotalAmount() { double d = 500.5; return(d); }
returning object
from a method as below
- public Object getObject() {
- Object object = new Object();
- // some statements using object instance
- return object;
- }
public Object getObject() { Object object = new Object(); // some statements using object instance return object; }
returning Custom object
from a method as below
- public Customer getCustomer() {
- Customer customer = new Customer();
- // some statements using customer instance
- return customer;
- }
public Customer getCustomer() { Customer customer = new Customer(); // some statements using customer instance return customer; }
returning Null
from a method as below
- <strong></strong>
- public Customer getAdminCustomer(boolean isAdmin) {
- if(
- Customer customer = new Customer();
- // some statements using customer instance
- return customer;
- }
<strong></strong> public Customer getAdminCustomer(boolean isAdmin) { if( Customer customer = new Customer(); // some statements using customer instance return customer; }