Java Programming - Assertions - Discussion
Discussion Forum : Assertions - Finding the output (Q.No. 1)
1.
What will be the output of the program?
public class Test
{
public static void main(String[] args)
{
int x = 0;
assert (x > 0) ? "assertion failed" : "assertion passed" ;
System.out.println("finished");
}
}
Answer: Option
Explanation:
Compilation Fails. You can't use the Assert statement in a similar way to the ternary operator. Don't confuse.
Discussion:
8 comments Page 1 of 1.
Vishal said:
1 decade ago
assert tests the programmer's assumption during development without writing exception handlers for an exception. Suppose you assumed that a number passed into a method will always be positive. While testing and debugging, you want to validate your assumption. Without the assert keyword, you will write a method like:
private void method(int a) {
if (a >= 0) {
// do something that depends on a not being negative
} else {
// tell the user that a is negative
}
}
This is simple exception handling; consider the case of big one. Assertion will come into the picture when you don't want to take the time to write the exception handling code.
Consider the above program with assertion:
private void method(int a) {
assert (a>=0); //throws an assertion error if a is negative.
// do stuff, knowing that a is not negative
}
In this program, assert (a>0) will pass when 'a' is only positive. Isn't this much cleaner than the previous example? If the value of 'a' is negative, then an AssertionError will be thrown.
private void method(int a) {
if (a >= 0) {
// do something that depends on a not being negative
} else {
// tell the user that a is negative
}
}
This is simple exception handling; consider the case of big one. Assertion will come into the picture when you don't want to take the time to write the exception handling code.
Consider the above program with assertion:
private void method(int a) {
assert (a>=0); //throws an assertion error if a is negative.
// do stuff, knowing that a is not negative
}
In this program, assert (a>0) will pass when 'a' is only positive. Isn't this much cleaner than the previous example? If the value of 'a' is negative, then an AssertionError will be thrown.
(1)
Shrini said:
1 decade ago
How the assert statement really works. ?
Rohit said:
4 years ago
Excellent explanation, Thanks @Vishal.
Suman said:
2 years ago
Excellent explanation, Thanks @Vishal.
Ravali said:
8 years ago
Thanks for explaining it @Vishal.
Sri said:
1 decade ago
What's the assert statement?
Amit said:
1 decade ago
Please explain the answer.
Jagdish Prasad Kumawat said:
8 years ago
Yes, it's prefect reason.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers