Java OCA OCP Practice Question 3118

Question

Consider the following program:

public class Main {
        public static void main(String []args) {
               String[]strings = {"Severity 1", "severity 2", "severity3","severity five"};
               for(String str : strings) {
                       if(!str.matches("^severity[\\s+][1-5]")) {
                               System.out.println(str + " does not match");
                       }/*from w  w  w. j a v  a 2s  .  co m*/
               }
        }
}

Which one of the following options correctly shows the output of this program?

a)
Severity 1 does not match//from  w ww.j  a v  a  2s .co m
severity 2 does not match
severity five does not match
b)
severity3 does not match
severity five does not match
c)
Severity 1 does not match
severity 2 does not match
d)
Severity 1 does not match
severity3 does not match
severity five does not match


d)

Note

Here is the meaning of the patterns used:

[^xyz]          Any character except x, y, or z (i.e., negation)
\s              A whitespace character
[a-z]           from a to z

So the pattern ^severity[\\s+][1-5]" matches the string "severity" followed by whitespace followed by one of the letters 1 to 5.

severity[\\s+][1-5]" matches the string "severity" followed by whitespace followed by one of the letters 1 to 5.

For this pattern,

  • "Severity 1" does not match because of the capital S in "Severity".
  • "severity 2" matches.
  • "severity3" does not match since there is no whitespace between severity and 3.
  • "severity five" does not match since "five" does not match a numeral from 1 to 5.



PreviousNext

Related