This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding assertion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding assertion" Watch "Regarding assertion" New topic
Author

Regarding assertion

B pandoo
Ranch Hand

Joined: Nov 14, 2006
Posts: 37
public class Asserttest2
{
public static void main(String[] args)
{

for(int i=0;i<10;i++){
try{
assert (i%2==0):i--;
System.out.println("Even"+i);
}catch(AssertionError e){
System.out.println("odd"+ ++i);
}
}
}
}

choices are:

1)it will print odd and even numbers from 0 to 9 corectly(0 even and 1 odd)
2)it will print odd and even numbers from 0 to 9 incoreectly(0 odd and 1 even.
3)compiler error at line 9
4)compiler error at line 10
5)it will result in infinite loop.

when i run the program,i got the result as

Even0
Even1
Even2
Even3
Even4
Even5
Even6
Even7
Even8
Even9

I am totally confused.How it works. the output does not matches the choices also.please explain.
Rancy Chadha
Ranch Hand

Joined: Jul 12, 2006
Posts: 135
Hi Pandoo,

Let me first tell you the correct answer is choice 1
and secondly output is
Even 0
odd 1
Even 2
odd 3
Even 4
odd 5
Even 6
odd 7
Even 8
odd 9

The reason you got the output that you have typed in your message is because
you ran your program using java Asserttest2 which has Assertion set to DISABLED by default.
Hence for assertions to work run your program using command java -ea Asserttest2 which will enable the assertions and you will get the expected output.

Thanks,
Rancy


Thanks,<br />-Rancy
B pandoo
Ranch Hand

Joined: Nov 14, 2006
Posts: 37
Hi,
i am getting the same output even if assertions are enabled
Amresh Singh
Greenhorn

Joined: Nov 12, 2006
Posts: 8
I checked this with -ea option in Eclipse IDE, by entering -ea option in VM arguments block...It's working fine i.e. Even0 Odd1........
B pandoo
Ranch Hand

Joined: Nov 14, 2006
Posts: 37
Hi,

sorry i ran the program with assertion enabled in Program argument block in eclipse.
May i know the difference in giving the arguments in program arg block and VM arg block in eclipse?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding assertion
 
Similar Threads
variable defined INSIDE for loop
Help Please
"assert i%2==0 : i--;"question required
continue statement...
Odd-Even Number print program