Wednesday 1 May 2013

Java Escape Character

If you wanted a Java program to display My name is “Andrew”, or whatever your name happens to be, you might try to do it like this:
 
UNIX > cat prog16.java
public class prog16
{
public static void main (String args[])
  {
  System.out.println
  ("My name is "Andrew"");
  }
}
UNIX > javac prog16.java
prog16.java:6: ')' expected
  ("My name is "Andrew"");
                ^
1 error
UNIX >
 
… but it does not work as the compiler treats the double quote before Andrew as the end of the literal then sees Andrew as an error. You can get round this by placing an escape character before the double quotes at the start and end of Andrew. Java then treats these double quotes just like any other character rather than literal delimiters. The escape character to use is a backwards slash as shown below:
 
UNIX > cat prog17.java
public class prog17
{
public static void main (String args[])
  {
  System.out.println
  ("My name is \"Andrew\"");
  }
}
UNIX > javac prog17.java
UNIX > java prog17
My name is "Andrew"
UNIX >

If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.