英文:
Why is assert passing all test cases when it shouldn't
问题
public class Main {
public static void main(String args[]) {
sumArray(8);
}
public static int sumArray(int nums){
assert nums == 5;
return nums;
}
}
我只是在想,当我传递一个不等于5的数字时,为什么编译器不会抛出任何错误,因为我断言`nums`等于5呢?
英文:
public class Main {
public static void main(String args[]) {
sumArray(8);
}
public static int sumArray(int nums){
assert nums == 5;
return nums;
}
}
I was just wondering, when I pass a number that is not equal to 5, why doesn't the compiler throw any errors, since I am asserting that nums
is equal to 5?
答案1
得分: 1
如果程序在启用断言的情况下运行,则会在运行时检查条件。如果条件为false,则Java运行时系统会抛出一个AssertionError
。
为了保持向后兼容性,默认情况下JVM会禁用断言验证。必须通过使用-enableassertions
命令行参数或其简写-ea
显式启用断言。
参考链接:https://www.baeldung.com/java-assert
英文:
If the program is running with assertions enabled, then the condition is checked at runtime. If the condition is false, the Java runtime system throws an AssertionError
.
For backward compatibility, the JVM disables assertion validation by default. They must be explicitly enabled using either the -enableassertions
command line argument, or its shorthand -ea
Reference: https://www.baeldung.com/java-assert
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论