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

  1.  public void displayName(String name)
  2.  {
  3.         System.out.println("Name -> "+name);
  4.         return;
  5.  }
 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

  1.  public String getName()
  2.  {
  3.      String s = "Raj";
  4.      return s;
  5.  }
 public String getName()
 {
     String s = "Raj";
     return s;
 }

returning double from a method

  1.  public double getTotalAmount()
  2.  {
  3.      double d = 500.5;
  4.      return(d);
  5.  }
 public double getTotalAmount()
 {
     double d = 500.5;
     return(d);
 }

returning object from a method as below

  1. public Object getObject() {
  2.     Object object = new Object();
  3.            // some statements using object instance
  4.     return object;
  5. }
public Object getObject() {
    Object object = new Object();
           // some statements using object instance
    return object;
}

returning Custom object from a method as below

  1. public Customer getCustomer() {
  2.     Customer customer = new Customer();
  3.            // some statements using customer instance
  4.     return customer;
  5. }
public Customer getCustomer() {
    Customer customer = new Customer();
           // some statements using customer instance
    return customer;
}

returning Null from a method as below

  1. <strong></strong>
  2. public Customer getAdminCustomer(boolean isAdmin) {
  3. if(
  4.     Customer customer = new Customer();
  5.          // some statements using customer instance
  6.     return customer;
  7. }
<strong></strong>
public Customer getAdminCustomer(boolean isAdmin) {
if(
    Customer customer = new Customer();
         // some statements using customer instance
    return customer;
}


About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on