Sunday, 15 July 2012

Backslash in Java

Like C/C++, Java also comes with a group of characters treated as a single character and this single character also represents an ASCII value. These characters are known as escape sequences and precede (starts) with a backward slash \ like \n and \t etc. The name is so derived as they escape the normal flow or printing of characters. The \n escapes of printing in the same line and instead prints in a separate line.

The following table prints the list of escape sequences supported by Java..

Escape sequenceASCII valueMeaning
\n10new line
\f12form feed
\r13carriage return
\"34double quote
\'39single quote

Following program shows the way to print the ASCII values of escape sequences (the same procedure you followed in C/C++).

public class StringCapitalize
  public static void main(String args[])
    System.out.println("\\b ASCII value: " + (int)'\b');
    System.out.println("\\t ASCII value: " + (int)'\t');   
    System.out.println("\\n ASCII value: " + (int)'\n');
    System.out.println("\\f ASCII value: " + (int)'\f');  
    System.out.println("\\r ASCII value: " + (int)'\r');  
    System.out.println("\\\" ASCII value: " + (int)'\"');  
    System.out.println("\\' ASCII value: " + (int)'\'');   
    System.out.println("\\\\ ASCII value: " + (int)'\\');   

Observe the println() statements in the above code; all confusing with multiple backslashes. This is where the programmer should be careful with backslash menace.

Backslash Menace

String str1 = “hello\sir”;

The above two statements do not compile and compiler raises "illegal escape character" regarding \s. Any letter suffixed to \ is treated as an escape sequence by the JVM. Now \s is checked with the standard list of escape sequences and did not find, the JVM raised an error. Suppose if you would like to have really \s in the code, instead of one \ place two \\. \\ is also an escape sequence and JVM places a single slash (instead of two slashes) in the output. The following works nice.

String str1 = “hello\\sir”;

In writing the regular expressions also, it must be taken care of.

String str2 = str1.replaceAll(“\\d”, “OK”);

The above statement is used in "Java String replaceAll" to replace each digit in the string with OK. The \\d is a regular expression where d represents each digit in the string. It is actually \d is required; but \d raises an error. Instead, \\d is placed which is converted to \d by the JVM and evaluated. This is where the programmer should be capable of.

Regular expressions are discussed, to some extent, in in JDK 1.4 (J2SE 4) Version. But regular expressions usage is a big subject which requires a good study. You are advised to refer a good Web site that primarily discusses regular expressions.

No comments:

Post a Comment

There was an error in this gadget