The difference between apostrophe and backslash + apostrophe

I do not understand the difference between "'" and "\'" . I.e

 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!"); } } 

Gets the same result:

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

Is this a sign of language? Or maybe a more complex description? Is there the same result on Android?

+4
source share
2 answers

For string literals, there is no difference between ' and \' . But for character literals that are enclosed in ' characters in Java, an escape is required.

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

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

Character and string escape sequences allow the representation of certain non-graphic characters, as well as single quotes, double quotes, 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 expected the same thing for Android.

+13
source

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

As he said, in this context there is no difference between ' and \' . In the case of the backslash, ' is executed, although this is not practical, since in this situation there is no need to escape (the compiler can distinguish the contents from the shell without help).

If you tried to use ' as a char, that would be important. For instance:

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

The same goes for escaping the double quote in a String declaration. For instance:

 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 terminate the shell, and the compiler thinks that there is an erroneous character at the end of your line.

Now, to tie everything together, this works great:

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

And that’s because the compiler doesn’t have a problem with the ' from " difference to finish the case. Hopefully this fixes some screening issues for others.

+1
source

Source: https://habr.com/ru/post/1489554/


All Articles