Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

exit method

Status
Not open for further replies.

FoxStudent

Technical User
Feb 24, 2000
85
GB
What is the syntax to leave a method prematurely?

Thank you,
Grainne

 
Hi,

The syntax to leave a method prematurely is 'return;' provided your method is supposed to return a void. If otherwise, you would have to return a type with it as well.

Example:

public class Test
{
public static void main(String[] args)
{
helloWorld();
System.out.println(howRU());
}
public static void helloWorld()
{
int a = 0;
System.out.println("Hello World!!");
if (a == 0)
return;
System.out.println("Hello Worlds!!");
}
public static String howRU()
{
int a=0;
System.out.println("How are you?");
if (a == 0)
return "";
System.out.println("How are you?");
return "I am fine";
}
}

Regards,
Leon If you need additional help, you can email to me at zaoliang@hotmail.com I don't guaranty that I will be able to solve your problems but I will try my best :)
 
For leaving a method you use the return statement. Even if the method is defined as void. But be shure that there is a check before leaving the method, otherwise at compilation the error "Statement is not reached" will be shown.

public void myMethod()
{
// Do some stuff here
if(true)
return; // leave the method
// This is not reached in this example
}

Greetings,
Steven.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top