断言:
1.定义:JAVA中的断言用来对程序的状态进行某种判断;它包含一个布尔表达式,
在程序的正常运行中,他应该为true。另外,断言用于保证程序的正确性,
避免逻辑错误;
2.格式:
a) assert expression; b) assert expression:detaMessage;
解释:expression----布尔表达式
detaMessage----expression为false,显示的消息
如果expression为true,则程序正常往下执行
如果expression为false,则程序抛出AssertionError
3.判断断言是否开启
boolean isOpen=false; assert isOpen=true; System.out.println("isOpen: "+isOpen);
解释:如果isOpen为true则证明断言开启;
如果isOpen为false则证明断言关闭;
4.开启/关闭断言:断言可以局部开启,因此断言不具备继承性
eclipse中开启断言:
Run--->Run Configurations--->右边选择Arguments--->
在下面的VM arguments文本框中输入-ea开启断言
如果输入-da表示禁止断言
5.断言实例:
ep1:
完整代码:
package com.ahuiby.test; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub int i; int sum=0; for(i=0;i<10;i++){ sum=sum+i; } assert i==4:"Hello World"; assert sum>10&&sum<5*10:"sum is"+sum; System.out.println("sum = "+sum); } }
运行结果:
Exception in thread "main" java.lang.AssertionError: Hello World at com.ahuiby.test.Test.main(Test.java:13)
ep2:
完整代码:
package com.ahuiby.test; class ObjectStack{ private static final int defaultSize=10; private int size; private int top; private Object[] listarray; public ObjectStack(){ initialize(defaultSize); } public ObjectStack(int size){ initialize(size); } public void initialize(int size){ this.size=size; this.top=0; listarray=new Object[size]; } //进栈 public void push(Object it){ assert top<size:"栈溢出"; listarray[top++]=it; } //出栈,并返回出栈的那个元素 public Object pop(){ assert !isEmpty():"栈已空"; return listarray[--top]; } //获取栈顶元素 public Object topValue(){ assert !isEmpty():"栈已空"; return listarray[top-1]; } public boolean isEmpty(){ return top==0; } } public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ObjectStack os=new ObjectStack(); os.push(new Integer(30)); os.push(new Integer(20)); os.push(new Integer(10)); System.out.println(os.pop()); System.out.println(os.pop()); System.out.println(os.pop()); System.out.println(os.pop());//断言执行 } }
运行结果:
10 20 30 Exception in thread "main" java.lang.AssertionError: 栈已空 at com.ahuiby.test.ObjectStack.pop(Test.java:31) at com.ahuiby.test.Test.main(Test.java:58)