Return to site

JAVA CERTIFICATION QUESTION: Java’s scope of variables and instanceof for pattern matching

=>When will the instanceof pattern variable be assigned—and what happens if the pattern matching test fails?

· java

Given the InstanceTest class:

public class InstanceTest {
 public static void main(String[] args) {
  var v = "Java 17";
  doIt(v);
 }
 public static void doIt(Object o) {
  if (!(o instanceof String v)) { // line n1
   throw new IllegalArgumentException("Must be a string");
  }
  if (!(o instanceof Number v)) { // line n2
   System.out.print("Not a number");
  }
 }
}

 

Which statement is correct? Choose one.

A. The code runs and throws IllegalArgumentException with the description Must be a string.

B. The code runs and prints Not a number.

C. Compilation fails at line n1.

D. Compilation fails at line n2.

 

 

 

 

 

 

·ꓷ uoᴉʇdo sᴉ ɹǝʍsuɐ ʇɔǝɹɹoɔ ǝɥꓕ ·uoᴉsnʅɔuoꓛ