El Bundy El Bundy - 1 month ago 5
Java Question

How to add ''\" Backslash to a String?

I have a

String a = "51109965.xml";


I need to add this character:
'\'
. So at the end I will get a new string
"\51109965.xml"
.

I am trying to use this command:

StringBuilder PathBufferXML_new_Provider = new StringBuilder().append("\").append("51109965").append(".xml");


But because this sign
'\'
is saved, I get an error.
How can I solve this issue?

Answer

In Java, \ is an escape character. It means, that it escapes the original meaning of the following sign. For example, when one wants to print " which has a special meaning, he can write System.out.println("\"");. Let's try to find the answer to your question which could be refactored to:

How can I print \ in Java, as it's a special character which escapes special meaning from the special characters?

System.out.println("\\"); will be what you're looking for as it's escaped speacial meaning of a \ character.

...and a very important thing: characters in Java are represented in single quotes: '\' instead of "\" which represents a String object which has a private field of type char[].

Comments