Java OCA OCP Practice Question 2632

Question

Consider the following program:

import java.util.regex.Pattern;

public class Main {
        public static void main(String []args) {
                String date = "10-01-2012"; // 10th January 2012 in dd-mm-yyyy format
                String [] dateParts = date.split("-");
                System.out.print("Using String.split method: ");
                for(String part : dateParts) {
                        System.out.print(part + " ");
                }//from  w w w. j a  va 2s.co m
                System.out.print("\nUsing regex pattern: ");
                Pattern datePattern = Pattern.compile("-");
                dateParts = datePattern.split(date);
                for(String part : dateParts) {
                        System.out.print(part + " ");
                }
        }
}

This program prints the following:

a)Using String.split method: 10-01-2012
  Using regex pattern: 10 01 2012/*from   ww w.  j  ava2  s.c  o  m*/

b)Using String.split method: 10 01 2012
  Using regex pattern: 10 01 2012

c)Using String.split method: 10-01-2012
  Using regex pattern: 10-01-2012

d)Using String.split method:
  Using regex pattern: 10 01 2012

e)Using String.split method: 10 01 2012
  Using regex pattern:
 
f)Using String.split method:
  Using regex pattern:


b)

Note

Using str.split(regex) gives the same result as Pattern.compile(regex).split(str).




PreviousNext

Related