Given:
public class Counter {
public static int getCount(String[] arr) {
int count =0 ;
for(String var:arr) {
if(var!=null) count++;
}
return count;
}
public static void main(String[] args) {
String[] arr =new String[4];
arr[1] = “C”;
arr[2] = “”;
arr[3] = “Java”;
assert (getCount(arr) < arr.length);
System.out.print(getCount(arr));
}
}
And the commands:
javac Counter.java
java ea Counter
What is the result?
A.
2
B.
3
C.
NullPointException is thrown at runtime
D.
AssertionError is thrown at runtime
E.
Compilation fails
Explanation:
The command line javac Counter.java
will compile the code.
The command line java ea Counter
will run the cod with assertions enabled.The following line:
assert (getCount(arr) < arr.length);
where the Boolean expressiongetCount(arr) < arr.lengthwill evaluate to false, will ensure that anAssertionError is thrown at runtime.Note:The javac command compiles Java source code into Java bytecodes. You then use the Java interpreter – the java command – to interprete the Java bytecodes.
Note 2:The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class’s main method. The method declaration must look like the following:
public static void main(String args[])Paramater ea:
-enableassertions[:<package name>”…” | :<class name> ] -ea[:<package name>”…” | :<class name> ]
Enable assertions. Assertions are disabled by default. With no arguments, enableassertions or -ea enables assertions.Note 3:
An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program.
Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error.
if it is given as java -ea Counter
Answer is 3
Otherwise
Exception in thread “main” java.lang.NoClassDefFoundError: ea
Caused by: java.lang.ClassNotFoundException: ea
+1
Yes, I partly agree with Jetendra. I tested this code and received in ouput 3. But if array init one more element the system throws ‘Exception in thread “main” java.lang.AssertionError’, not NoClassDefFoundError.. Jetendra,I’d advise you to run test with -ea
ans is 3
B
3
B
B. 3
b