(我真的不知道如何更好地表达这个问题。我确信这里涉及到一个我不知道的概念,所以如果可以的话请建议一个更好的措辞——或者指导我如果结果是重复的,则回答问题)
我一直在玩Java,发现了一些我无法解释的行为。在下面的代码中,我期望 0
待打印。但是,没有打印任何内容。我能想到的唯一可能的解释是 main 方法在打印流刷新之前结束,但对我来说这没有意义。简而言之,这段代码不打印任何内容而不是 0
是怎么回事? ?
class Test {
public static void main (String [] args) {
if(false && method()){
}
}
public static boolean method(){
System.out.println(0);
return true;
}
}
最佳答案
因为该方法没有被调用。 false
导致 和 short-ciruit .
if(false & method()){ // <-- body will not execute, but the evaluation
// does not short circuit.
或
if(false || method()){ // <-- body will execute, method() is true
或
if(method() && false){ // <-- body will not execute, because of false.
将按您的预期工作。
关于java - 为什么从 "empty"main 调用方法时不执行打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43421416/