Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

assertion

 
Maciek Zywno
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello
I tried the following piece of code :
public class AssertTest {

public void methodA( int i ){
assert i >= 0 : methodB();
System.out.println( i );
}

public int methodB(){
System.out.println( "The value must be nonnegative" );
return 1;
}

public static void main(String[] args) {
AssertTest test = new AssertTest();
test.methodA( -10 );
}
}
As I execute it only "-10" is printed and no print from methodB().
I wonder why methodB() is not invoked. Sun's docs say that in
assert Expression1 : Expression2 ;
expression2 cannot be the invocation of a method that is declared void.
In "my" case methodB() is not of a void type, so why it is not executed?
If it is not executed how the expression2 is evaluated?
what am I missing?
thanks
 
Alton Hernandez
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You must run it with assertion flag on:
java -ea AssertTest
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic