Java OCA OCP Practice Question 2139

Question

What will the program print when compiled and run?

public class Main {
  public static void main(String[] args) {
    String regex   = "[Jj].?[Aa].?[Vv].?[Aa]";
    String target1 = "JAVA JaVa java jaVA";
    String target2 = "JAAAVA JaVVa jjaavvaa ja VA";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(target1);
    makeMatch(matcher);//  www. j a v  a  2 s.c  o  m
    matcher.reset();
    makeMatch(matcher);
    matcher.reset(target2);
    makeMatch(matcher);
  }

  public static void makeMatch(Matcher matcher) {
    System.out.print("|");
    while(matcher.find()) {
      System.out.print(matcher.group() + "|");
    }
    System.out.println();
  }
 }

    

Select the one correct answer.

(a) |JAVA|JaVa|java|jaVA|//from ww w . j av a2s .c o  m
    |JAAAVA|JaVVa|jjaavva|ja VA|
(b) |JAVA|JaVa|java|jaVA|
    |
    |JAAAVA|JaVVa|jjaavva|ja VA|
(c) |JAVA|JaVa|java|jaVA|
    |JAVA|JaVa|java|jaVA|
    |JAAAVA|JaVVa|jjaavva|ja VA|
(d) |JAVA|JaVa|java|jaVA|
    |JAVA|JaVa|java|jaVA|
    |JaVVa|jjaavva|ja VA|
(e) The program will throw an exception when run.


(c)

Note

The no-argument reset() method can be used to reset the matcher to the beginning of the current target.

That is why the matching against the first target is repeated in the output.

The same matcher can be applied to different targets by passing the new target to the reset() method.




PreviousNext

Related