|
SCJP : Regular Expression Mock Exam Practice Questions
Questions no -1
What is the output for the below code ?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String... args) {
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("b");
boolean b = m.matches();
System.out.println(b);
}
}
options
A)true
B)Compile Error
C)false
D)b
Correct answer is : A
Explanations : a*b means "a" may present zero or more time and "b" should be present once.
Questions no -2
What is the output for the below code ?
public class Test {
public static void main(String... args) {
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
}
}
options
A)1 2 red blue
B)Compile Error - because Scanner is not defind in java.
C)1 fish 2 fish red fish blue fish
D)1 fish 2 fish red blue fish
Correct answer is : A
Explanations : java.util.Scanner is a simple text scanner which can parse primitive types and strings using regular expressions.
Questions no -3
What is the output for the below code ?
public class Test {
public static void main(String... args) {
Pattern p = Pattern.compile("a{3}b?c*");
Matcher m = p.matcher("aaab");
boolean b = m.matches();
System.out.println(b);
}
}
options
A)true
B)Compile Error
C)false
D)NullPointerException
Correct answer is : A
Explanations :
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
Questions no -4
What is the output for the below code ?
public class Test {
public static void main(String... args) {
Pattern p = Pattern.compile("a{1,3}b?c*");
Matcher m = p.matcher("aaab");
boolean b = m.matches();
System.out.println(b);
}
}
options
A)true
B)Compile Error
C)false
D)NullPointerException
Correct answer is : A
Explanations :
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
| |