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
2
3
4
5
 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

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

returning double from a method

1
2
3
4
5
 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

1
2
3
4
5
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

1
2
3
4
5
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

1
2
3
4
5
6
7
<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;
}


About the Author

Karibasappa G C (KB)
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