Is the char literal '\“' the same as '”' ?(backslash-doublequote vs only-doublequote)

限于喜欢 提交于 2019-11-30 09:39:03

问题


Is there's any difference between char literals '\"' and '"' ?


回答1:


There is absolutely no difference. The two char are ==.

System.out.println('\"' == '"'); // prints "true"

Strictly speaking it's not necessary to escape a double quote in a char literal, but it doesn't change this fact that \" denotes the double quote character \u0022.

References

  • JLS 3.10.6 Escape Sequences for Character and String Literals

String analog

We also have the analogous situation for String literals:

System.out.println("\'".equals("'")); // prints "true"

In fact, we can even go a step further and use == for reference equality:

System.out.println("\'" == "'"); // prints "true"

The second snippet proves that the two string literals are really equal, and therefore subject to string interning at compile-time.

References

  • JLS 3.10.5 String Literals

    String literals --or, more generally, strings that are the values of constant expressions-- are "interned" so as to share unique instances, using the method String.intern.

Related questions

  • How do I compare strings in Java?
  • Java String.equals versus ==
  • Where do Java and .NET string literals reside?
  • When “” == s is false but “”.equals( s ) is true

Summary

  • A single-quote in a char literal MUST be escaped
    • Because char literal is quoted in single-quotes
  • A double-quote in a String literal MUST be escaped
    • Because String literal is quoted in double-quotes
  • It doesn't hurt to escape, even when it's not necessary
    • Go with what's most readable


来源:https://stackoverflow.com/questions/3224337/is-the-char-literal-the-same-as-backslash-doublequote-vs-only-doubleq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!