Java OCA OCP Practice Question 2135

Question

Which statements are true about the following program?.

import java.util.regex.Pattern;
public class Main {
  public static void main(String[] args) {
    System.out.println(Pattern.matches("+?\d", "+2007"));      // (1)
    System.out.println(Pattern.matches("+?\\d+","+2007"));     // (2)
    System.out.println(Pattern.matches("\+?\\d+", "+2007"));   // (3)
    System.out.println(Pattern.matches("\\+?\\d+", "+2007"));  // (4)
  }
}

Select the two correct answers.

  • (a) Only in the statements at (1) and (2) will the compiler report an invalid escape sequence.
  • (b) Only in the statements at (3) and (4) will the compiler report an invalid escape sequence.
  • (c) Only in the statements at (1) and (3) will the compiler report an invalid escape sequence.
  • (d) The statements at (2) and (4) will compile but will throw an exception at runtime.
  • (e) After any compile-time errors have been eliminated, only one of the statements will print true when executed.
  • (f) None of the above.


(c) and (e)

Note

To escape any metacharacter in regex, we need to specify two backslashes (\\) in Java strings.

A backslash (\) is used to escape metacharacters in both Java strings and in regular expressions.

In (1), the compiler reports that \d is an invalid escape sequence in a Java string.

(2) will throw a java.util.regex.PatternSyntaxException: dangling metacharacter +, which is the first character in the regex, is missing an operand.

In (3), the compiler reports that \+ is an invalid escape sequence.

(4) will match a positive integer with an optional + sign, printing true.

The method Pattern.matches() returns true if the regex matches the entire input.




PreviousNext

Related