Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is there a way to write a string literal without having to escape quotes?

People also ask

How do you write a literal string in Java?

By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”);

How do I stop characters from escaping in Java?

Essentially the backslash tells the system that the character(s) after it should be interpreted in a special manner (not simply as plain text). When you escape the escape, it gets treated specially as well... as plain text, instead of as an escape character.

How do you remove quotation marks from a string in Java?

To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.

Can we write string in single quotes in Java?

A string literal is bracketed by either single quotes ( ' ) or double quotes ( " ). When single quotes bracket a string literal, the value of the literal is the value within the quotes. When double quotes are used, any references to variables or expressions within the quotes are interpolated.


No, and I've always been annoyed by the lack of different string-literal syntaxes in Java.

Here's a trick I've used from time to time:

String myString = "using `backticks` instead of quotes".replace('`', '"');

I mainly only do something like that for a static field. Since it's static the string-replace code gets called once, upon initialization of the class. So the runtime performance penalty is practically nonexistent, and it makes the code considerably more legible.


The answer is no, and the proof resides in the Java Language Specification:

  StringLiteral:
   "StringCharacters"

  StringCharacters:
   StringCharacter
   | StringCharacters StringCharacter

  StringCharacter:
   InputCharacter but not " or \
   | EscapeSequence

As you can see a StringLiteral can just be bound by " and cannot contain special character without escapes..

A side note: you can embed Groovy inside your project, this will extend the syntax of Java allowing you to use '''multi line string ''', ' "string with single quotes" ' and also "string with ${variable}".


Update Dec. 2018 (12 months later):

Raw string literals (which are on the amber list) won't make it to JDK 12.
See the criticisms here.


There might be in a future version of Java (10 or more).

See JEPS 8196004 from January 2018: ("JEP" is the "JDK Enhancement Program")

JEP draft: Raw String Literals

Add a new kind of literal, a raw string literal, to the Java programming language.
Like the traditional string literal, a raw string literal produces a String, but does not interpret string escapes and can span multiple lines of source code.

So instead of:

Runtime.getRuntime().exec("\"C:\\Program Files\\foo\" bar");
String html = "<html>\n"
              "    <body>\n" +
              "         <p>Hello World.</p>\n" +
              "    </body>\n" +
              "</html>\n";
System.out.println("this".matches("\\w\\w\\w\\w"));

You would be able to type:

Runtime.getRuntime().exec(`"C:\Program Files\foo" bar"`);
    
String html = `<html>
                   <body>
                       <p>Hello World.</p>
                   </body>
               </html>
              `;

System.out.println("this".matches(`\w\w\w\w`));

Neat!

But it is still just a draft: it will need to posted, submitted, be a candidate, and funded, before being completed and making it into the next JDK.


Simple answer: No.

For longer strings that must be escaped, I usually read them from some external resource.


Since Java 15¹ there is new feature called Text Blocks. It looks similar to what you mentioned is available in Python:

String text = """
              {
                 "property": "value",
                 "otherProperty": 12
              }
              """;

More details with examples can be found here: https://openjdk.java.net/jeps/378.


¹ Previewed in Java 13 and 14.


you can also use StringEscapeUtils from apache commons

UPDATE: If someone is interested in some examples here is a useful link : https://dzone.com/articles/commons-lang-3-improved-and-powerful-StringEscapeUtils