Java Programming - Assertions - Discussion
Discussion Forum : Assertions - Finding the output (Q.No. 3)
3.
What will be the output of the program?
public class Test
{
public static int y;
public static void foo(int x)
{
System.out.print("foo ");
y = x;
}
public static int bar(int z)
{
System.out.print("bar ");
return y = z;
}
public static void main(String [] args )
{
int t = 0;
assert t > 0 : bar(7);
assert t > 1 : foo(8); /* Line 18 */
System.out.println("done ");
}
}
Answer: Option
Explanation:
The foo() method returns void. It is a perfectly acceptable method, but because it returns void it cannot be used in an assert statement, so line 18 will not compile.
Discussion:
10 comments Page 1 of 1.
Adam Prog said:
7 years ago
After ":" can be any expression which has a value.
Ron said:
8 years ago
The formula after ":" should have no type, even void, it is supposed to be an expression like a sentence.
Vishesh said:
10 years ago
If you execute this program in IDE then it does not throw any exception. So compile it on cmd and for execution type
----> java -ea ClassName
Here ea used for to enable assertion.
----> java -ea ClassName
Here ea used for to enable assertion.
Vishesh said:
10 years ago
Why colon (:) used here explain it. And if at place of : semicolon (;) used then output is bar foo done?
And both assert false after this no error thrown why? even when I made return type of method foo is int.
And both assert false after this no error thrown why? even when I made return type of method foo is int.
Tom Nguyen said:
1 decade ago
@Jagadeesh,
Assert is used for troubleshooting, we want to make sure that the variables should be got right values at the specific locations.
Assert is used for troubleshooting, we want to make sure that the variables should be got right values at the specific locations.
Jagadeesh Urella said:
1 decade ago
Can any one tell me what is assert? why we use it in java.
Vinay said:
1 decade ago
If we comment the line 18 the output is strange? any explanation?
Dhirendra Kumar said:
1 decade ago
The error is at line:
assert t > 1 : foo(8); /* Line 18 *
beacause foo()'s return type is void assert can not have void as return type.
assert t > 1 : foo(8); /* Line 18 *
beacause foo()'s return type is void assert can not have void as return type.
(1)
Aditya valluru said:
1 decade ago
Here why assert will't return assert error when t>0 is false.
Assert expects only true boolean value but it gets false. Am I correct ?
Assert expects only true boolean value but it gets false. Am I correct ?
Manuja George said:
1 decade ago
Assert can call method with which return type?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers