Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.17. The return statement

3.17. The return statement
Last updated: 27 January 2013.

You have already seen return statement examples in the tutorial Java method calling. In those examples, the return statement exits the current method and returns a value to the caller. That use of the return statement is the most common use.

However, a return statement can also be used only to exit the current method without returning a value, which is sometimes useful.

In the example shown below, the method printHello prints "Hello World" only once to the standard output even if it is called several times. Create a class named ReturnTest and write the method printHello as shown below:

public class ReturnTest {

   
boolean alreadyPrinted = false;


   
public void printHello(){

         
if(alreadyPrinted == true)
               
return;

          System.out.println
("Hello World !");

          alreadyPrinted =
true;

   
}

}

alreadyPrinted is a class field of type boolean that is initialized to false. When the method printHello is called for the first time, "Hello World" is printed to the standard output and alreadyPrinted is set to true. As a result, if the method printHello is called again, it will return to the caller without printing anything to the standard output. Create a class named App and call the method printHello several times:

public class App {

   
public static void main(String[] args) {

         
ReturnTest returnTest = new ReturnTest();

          returnTest.printHello
();
          returnTest.printHello
();
          returnTest.printHello
();

   
}

}

The output is:

Hello World !


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.17. The return statement
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   4. Object-Oriented Concepts

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7