Vyacheslav
Vyacheslav

Reputation: 27221

Difference between apostrophe and backslash+apostrophe

I don't understand the difference between "'" and "\'". That is,

public class test {
    public static void main(String[] args) {

        System.out.println("Hello, I'm the best!");
        System.out.println("Hello, I\'m the best!");
      }
}

Gives the same result:

Hello, I'm the best!
Hello, I'm the best!

Is this the feature of the language? Or may be there is more complicated description? Is there the same result on Android?

Upvotes: 4

Views: 574

Answers (2)

telkins
telkins

Reputation: 10550

I just wanted to add on a bit to rgettman's answer.

Like he said, there is no difference between ' and \' in this context. In the case with the back-slash, the ' is being escaped, though it makes no practical difference because an escape is not necessary in this situation (the compiler can distinguish the content from the enclosure without help).

If you were trying to use the ' as a char, then it would matter. For example:

char c = '''; //compile error
char c = '\''; //escaped correctly

The same then applies to escaping a double-quote within a String declaration. For example:

String s = """; //compile error
String s = "\""; //escaped correctly

Essentially, escaping a character tells the compiler to treat the character as content, because otherwise it would finish the enclosure and the compiler thinks there is an erroneous character at the end of your line.

Now to tie everything together, this works fine:

String s = "'";
char c = '"';

And that is because the compiler has no trouble differentiating the ' from the " to finish the enclosure. Hopefully this clears up some escaping issues for others.

Upvotes: 2

rgettman
rgettman

Reputation: 178303

For string literals, there is no difference between ' and \'. But for character literals, which in Java are enclosed by ' characters, the escape is necessary.

'''   // Not a legal character literal for '
'\''  // A properly escaped character literal for '

According to the JLS, Section 3.10.6, Java escapes are for string and character literals, so you can use them in both cases. Quoting from the JLS link:

The character and string escape sequences allow for the representation of some nongraphic characters as well as the single quote, double quote, and backslash characters in character literals (§3.10.4) and string literals (§3.10.5).

As far as I know, Android uses Java, so I would expect the same to hold for Android as well.

Upvotes: 13

Related Questions