Escape character for single quotes. Is it really required in String?

M

Mausam

Hello,

http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#101089
defines escape character for single character as well.

But single quote works fine in String without any escape character.

public class Class1 {

private static String str = "I have a single quote. That's it";
private static String str1 = "I have a single quote. That\'s it";
public static void main(String[] args) {
System.out.println(str);
System.out.println(str1);
}
}

How the two string is different? And when should I use escape
character for single quote?
 
M

Mausam

In character literals.

char apostrophe = '\'';

Thanks. For char it makes sense. But then my understanding that this escape character does not make any difference when used in String is correct.
 
K

Knute Johnson

Thanks. For char it makes sense. But then my understanding that this escape character does not make any difference when used in String is correct.

and the Strings are equal;

public class Class1 {

private static String str = "I have a single quote. That's it";
private static String str1 = "I have a single quote. That\'s it";
public static void main(String[] args) {
System.out.println(str);
System.out.println(str1);
System.out.println(str.equals(str1));
}
}


C:\Documents and Settings\Knute Johnson>java Class1
I have a single quote. That's it
I have a single quote. That's it
true
 
L

Lew


That's the wrong document! Why are you citing ancient information? Get current.
http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html
defines escape character for single character as well.

But single quote works fine in String without any escape character.

public class Class1 {

private static String str = "I have a single quote. That's it";
private static String str1 = "I have a single quote. That\'s it";
public static void main(String[] args) {
System.out.println(str);
System.out.println(str1);
}
}

How the two string is different?

Why do you claim that they're different?
And when should I use escape character for single quote?

When you need to in order to make the expression mean what you intend.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top