Search This Blog

Sunday, January 30, 2011

Question 20

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

import java.util.Scanner;
public class ScannerDelimiter {
  public static void main(String[] args){
    String input = "AA BB CC";
    Scanner s = new Scanner(input).useDelimiter("\s");
    while(s.hasNext()){
      System.out.print(s.next());
    }
  }
}
Options :


a. Prints "AA BB CC"
b. Prints "AABBCC"
c. Does not compile
d. Causes an exception to be thrown



Answer : C [Does not Compile]

The code is perfect expect the usage of “\s” string as delimiter. The code looks ok in the first shot but if you look carefully you can figure out why the code does not work.

Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler.

As per the above reason we should always use “\\s” to represent a space pattern in the delimiter.

Question 20SocialTwist Tell-a-Friend

No comments:

Post a Comment