Search This Blog

Wednesday, February 9, 2011

SCJP 6 Question 27

What is the result of compiling and running the given code?

public class Regex1 {
  public static void main(String[] args){
    String str = "aaaaaaaaabb";
    String[] split = str.split("a{3}");
    System.out.println(split.length);    
  }
}


Choose one answer
a. Compiler error
b. Exception at runtime
c. Prints 0
d. Prints 1
e. Prints 2
f. Prints 3
g. Prints 4



Answer G:

First thing to be learned from this question is about the greedy quantifier X{n} which means that to search X exactly n times. So based on the above greedy quantifier the String str got split into <> with aaa as delimiter.

<>aaa<>aaa<>aaa<bb>.

This creates four elements in the array. The with contents [, , , bb]

SCJP 6 Question 27SocialTwist Tell-a-Friend

No comments:

Post a Comment