aspose file tools*
The moose likes Beginning Java and the fly likes return Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "return" Watch "return" New topic
Author

return

Enkita mody
Ranch Hand

Joined: Aug 06, 2012
Posts: 333

What is difference between these statements :

//1
return;

//2
return null;


OCA7
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

1 is used to return early from a void method. Ugly style IMO.

2 is used to return a null reference from a method that has an object reference return type.
Enkita mody
Ranch Hand

Joined: Aug 06, 2012
Posts: 333

In correct way could i say, first return statement returns void ?
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

Not really as void means there is no return type. So returning void makes no sense.
Enkita mody
Ranch Hand

Joined: Aug 06, 2012
Posts: 333

When we write method definition i.e

public int method1()
{
return 0;
}
//here method1's return type is int that's why we call it returns an int.

public void method2()
{
return;
}

//Same as it doesn't mean that method2's return type is void that's why we could say it returns void.Because it wont be appropriate to say it returns nothing, because it really has type that is void.
gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924
    
    1

return; it simply means return i.e. return the control back to invoking method. it does not return(value) anything. just pass of control. a method with return type void can include return statement at any point

return null; this can be put in any method with return type of the type Object. it actually does something. it returns null , so say i have something like this

Enkita mody
Ranch Hand

Joined: Aug 06, 2012
Posts: 333

Okay nice.
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

Like I stated earlier, I think using return on its own is an ugly style and for this example:

it is redundant as well. Only use return statement when you have something to return to calling code.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: return