Java OCA OCP Practice Question 2557

Question

Consider the following program and predict the output:

import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
            String str =/*from   w  w w  .j  av a2  s. c om*/
                    "Java N.=1234567890, SQL Javascript=9898989898";
            Pattern pattern =
                    Pattern.compile("(\\w+)(\\s\\w+)(=)(\\d{10})");
            Matcher matcher = pattern.matcher(str);
            String newStr = matcher.replaceAll("$4:$2,$1");
            System.out.println(newStr);
    }
}
  • a) 1234567890: N.,Java, 9898989898: Javascript,SQL
  • b) Java N.=1234567890, SQL Javascript=9898989898
  • c) Java N.=1234567890, 9898989898: Javascript,SQL
  • d) This program throws a runtime exception.


c)

Note

The first contact does not match with the specified regex (since "." is not covered by "\w+");

hence, the first part of the string is unchanged.

The second part of string matches with the specified regex, so the replace rearranges the substring.




PreviousNext

Related