public class TestLoop { public static void main(String[] args) { int array[] = { 0, 1, 2, 3, 4 }; int key = 3; for (int pos = 0; pos < array.length; ++pos) { if (array[pos] == key) { break; } } System.out.print("Found " + key + "at " + pos); } }
What is the result?
1. Found 3 at 2 2. Found 3 at 3 3. Compilation fails 4. An exception is thrown at runtime
Correct Answer : Get Lastest Questions and Answer : Explanation: The following line does not compile: System.out.print("Found " + key + "at " + pos); The variable pos is undefined at this line, as its scope is only valid in the for loop. Any variables created inside of a loop are LoCAL To THE LooP
Question : A method doSomething () that has no exception handling code is modified to trail a method that throws a checked exception. Which two modifications, made independently, will allow the program to compile?
A. Catch the exception in the method doSomething(). B. Declare the exception to be thrown in the doSomething() method signature. C. Cast the exception to a RunTimeException in the doSomething() method. D. Catch the exception in the method that calls doSomething(). 1. A,B 2. B,C 3. C,D 4. A,D
5. A,C
Correct Answer : Get Lastest Questions and Answer : Explanation: Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following: - A try statement that catches the exception. The try must provide a handler for the exception, as described in Catching and Handling Exceptions. - A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception, as described in Specifying the Exceptions Thrown by Method. Code that fails to honor the Catch or Specify Requirement will not compile.