Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between apostrophe and backslash+apostrophe

Tags:

java

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?

like image 200
Vyacheslav Avatar asked Dec 08 '22 14:12

Vyacheslav


1 Answers

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.

like image 127
rgettman Avatar answered Dec 11 '22 04:12

rgettman