4

I'm trying to add double quotes in a string using the unicode, but when I do so i get the compilation time error.

String unicCode = "\u0022"; //This line gives a compile time error.

The compilation error is that I get is

String literal is not properly closed by a double-quote.

Could some one help me to understand what are the escape characters required to be used to append a unicode of a double quotation mark (").

user3701861
  • 151
  • 1
  • 7
  • What do you want your string to contain? The single character `"`? – Sotirios Delimanolis Nov 17 '14 at 08:16
  • 1
    Why dont you define it as char instead? – SMA Nov 17 '14 at 08:18
  • @SotiriosDelimanolis I'm basically trying to preapre a String to be used to call a web service. my requirement is to add _"abc"_ (including the double quotes) as a part of my soap request. I have tried it by '\"abc\"' but when the request is sent it is converted to '"abc"' – user3701861 Nov 17 '14 at 08:24
  • @almasshaikh : I tried including it as char, but again (as mentioned above) the char is converted to ". Basically, when i add unicode other that \u0022 the character is passed accurately. Thus trying the unicode way. – user3701861 Nov 17 '14 at 08:27
  • @user3701861 i edited the answer, is this what u looking for. – Ankur Singhal Nov 17 '14 at 08:39

2 Answers2

8
 public static void main(String[] args) {
        String quote = "\u005c\u0022";
        System.out.println(quote);
    }

Output

"

public static void main(String[] args) {
        String quote = "\u005c\u0022" + "abc" + "\u005c\u0022";
        System.out.println(quote);
    }

Output

"abc"

If you wanted to put the two double quote chars into the string literal, you can do it with normal escape sequences. But you can't do with Unicode escapes because Java provides no special treatment for Unicode escapes within string literals.

String quote = "\"";

// We can't represent the same string with a single Unicode escape.

// \u0022 has exactly the same meaning to the compiler as ".

// The string below turns into """: an empty string followed

// by an unterminated string, which yields a compilation error.

String quote = "\u0022";
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
2

The \uXXXX escaping is already early resolved when the javac compiler reads the java source text. It has nothing to do with only string literals and backslash escaping there. And \u0022 is the same as char ". And hence needs escaping in a string literal: "\\u0022" which is read as "\"". This means was designed to enable a pure ASCII representation of a java source using any unicode. But you may escape ASCII too:

public \u0063lass Test {
    public static void \u006dain(String[] args) {
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138