java 方法的返回值

先直接上一段代码

public class MethodTest01{
	public static void main(String[] args){
		
	}
	public static int test(){
		boolean flag = true;
		if(flag = true){
			return 1;
		}
	}
}

初一看好像并没有什么问题,在test方法中也有返回值,但是在编译后:

 并没有返回值。。。

在test()方法中,编译器只能识别flag是一个boolean类型,但是不能识别字面值,不能识别到底是true还是false,所以编译器认为可能执行,也可能不执行,所有编译器为了确保程序正确性,提示错误。

修改后:

       第一种修改

public class MethodTest01{
	public static void main(String[] args){
		
	}
	public static int test(){
		boolean flag = true;
		if(flag = true){
			return 1;
		}else{
			return 0;
		}
	}
}

  第二种修改

public class MethodTest01{
	public static void main(String[] args){
		
	}
	public static int test(){
		boolean flag = true;
		if(flag = true){
			return 1;
		}
		return 0;
	}
}

  第三种修改使用三目运算符

public class MethodTest01{
	public static void main(String[] args){
		
	}
	public static int test(){
		boolean flag = true;
		return flag ? 1:0;
	}
}

  

原文地址:https://www.cnblogs.com/homle/p/14038673.html