众所周知,return 只能用在有返回类型的函数中,但是有返回值的函数一定要有return吗?return都可以用在函数的哪些地方呢?这是本文需要讨论的问题。
--------------------------------------------------------------------------------
例一:
class test {
public string test() {
if(true){
return "";
}
else{
return "";
}
}
}
上面这样即可通过编译,但是下面这两个例子却不能通过编译:
(一)
class test {
public string test() {
if(true){
return "";
}
}
}
(二)
class test {
public string test() {
if(istrue()){
return "";
}
else if(!istrue()){//两个if里的判断包括了所有的可能性,但是还是编译期error
return "";
}
}
boolean istrue(){
return true;
}
}
结论1:
对于(一),这是因为java编译器认定单独的if语句只在当一定条件满足情况下才执行,它认为if不会有任何情况下都能执行的能力。
对于(二),这是因为java编译器对if else 语句能够全面囊括所有情况的能力只限定在的if...else(或if...else if...else)时,而不包括if...else if。
--------------------------------------------------------------------------------
再看例二:
class test {
public string test() {
while(true){
return "";
}
}
}
上面这样即可通过编译,但是下面这样不行:
class test {
public string test() {
while(istrue()){
return "";
}
}
boolean istrue(){
return true;
}
}
结论2:
这是因为编译器认为while语句有在任何情况下都能执行的能力,但是只在入参为true的情况下有该能力。
--------------------------------------------------------------------------------
再看例三:
public class test {
string test() throws exception{
throw new exception();//抛出异常后,跳出程序,程序中止
}
}
结论3:
如果函数中创建了异常,并抛出,则该函数可以不返回值。
--------------------------------------------------------------------------------
知道了以上的情况,你就可以熟练自如得运用return了。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器