How can I make Java print quotes, like "Hello"?
Asked Answered
K

11

92

How can I make Java print "Hello"?

When I type System.out.print("Hello"); the output will be Hello. What I am looking for is "Hello" with the quotes("").

Krystinakrystle answered 2/10, 2010 at 6:6 Comment(2)
possible duplicate of In Java, is there a way to write a string literal without having to escape quotes?Importunate
Possible duplicate of How to enter quotes in a Java string?Colpitis
E
165
System.out.print("\"Hello\"");

The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include:

  • Carriage return and newline: "\r" and "\n"
  • Backslash: "\\"
  • Single quote: "\'"
  • Horizontal tab and form feed: "\t" and "\f"

The complete list of Java string and character literal escapes may be found in the section 3.10.6 of the JLS.

It is also worth noting that you can include arbitrary Unicode characters in your source code using Unicode escape sequences of the form \uxxxx where the xs are hexadecimal digits. However, these are different from ordinary string and character escapes in that you can use them anywhere in a Java program ... not just in string and character literals; see JLS sections 3.1, 3.2 and 3.3 for a details on the use of Unicode in Java source code.

See also:

Estate answered 2/10, 2010 at 6:8 Comment(3)
Is there a way without backslashes in java like triple quotes in python?Foreshadow
No there isn't.Estate
Actually, starting with Java 13 (September 2019), there is support for [JEP 355](openjdk.java.net/jeps/355 text-blocks which are similar to Python triple-quote strings.Estate
N
11
char ch='"';

System.out.println(ch + "String" + ch);

Or

System.out.println('"' + "ASHISH" + '"');
Nakashima answered 6/9, 2014 at 9:53 Comment(0)
P
7

Escape double-quotes in your string: "\"Hello\""

More on the topic (check 'Escape Sequences' part)

Pecker answered 2/10, 2010 at 6:8 Comment(0)
E
4
System.out.println("\"Hello\""); 
Execrable answered 2/10, 2010 at 6:9 Comment(0)
S
4

You can do it using a unicode character also

System.out.print('\u0022' + "Hello" + '\u0022');
Shutter answered 2/10, 2010 at 6:26 Comment(1)
Even if the compiler simplify this, into \"Hello\" it isn't really readable.Jiggermast
R
4

Adding the actual quote characters is only a tiny fraction of the problem; once you have done that, you are likely to face the real problem: what happens if the string already contains quotes, or line feeds, or other unprintable characters?

The following method will take care of everything:

public static String escapeForJava( String value, boolean quote )
{
    StringBuilder builder = new StringBuilder();
    if( quote )
        builder.append( "\"" );
    for( char c : value.toCharArray() )
    {
        if( c == '\'' )
            builder.append( "\\'" );
        else if ( c == '\"' )
            builder.append( "\\\"" );
        else if( c == '\r' )
            builder.append( "\\r" );
        else if( c == '\n' )
            builder.append( "\\n" );
        else if( c == '\t' )
            builder.append( "\\t" );
        else if( c < 32 || c >= 127 )
            builder.append( String.format( "\\u%04x", (int)c ) );
        else
            builder.append( c );
    }
    if( quote )
        builder.append( "\"" );
    return builder.toString();
}
Ranzini answered 16/3, 2015 at 8:33 Comment(2)
If you do need to do this, a (usually) better alternative to this is to use an existing library method (e.g. Apache Commons) to do the escaping / de-escaping. Or make use of an API's ability to do this; e.g. JDBC PreparedStatement, the URL and URI constructors.Estate
@StephenC yes, of course. The usefulness of this answer just lies in the complement of the "(usually)" that you mentioned. Plus the code may have some educational value.Ranzini
L
2
System.out.println("\"Hello\"")
Loftin answered 2/10, 2010 at 6:8 Comment(0)
W
1

There are two easy methods:

  1. Use backslash \ before double quotes.
  2. Use two single quotes instead of double quotes like '' instead of "

For example:

System.out.println("\"Hello\"");                       
System.out.println("''Hello''"); 
Wellknit answered 20/6, 2013 at 15:13 Comment(1)
Erm ... the 2nd approach is not solving the problem. It is changing the problem. Two single quotes does not mean the same thing as a double quote ... to a computer, or to a knowledgeable person.Estate
B
1

Take note, there are a few certain things to take note when running backslashes with specific characters.

System.out.println("Hello\\\");

The output above will be:

Hello\


System.out.println(" Hello\"  ");

The output above will be:

Hello"

Bartholemy answered 17/1, 2015 at 6:26 Comment(0)
S
0

Use Escape sequence.

\"Hello\"

This will print "Hello".

Solifidian answered 2/10, 2010 at 13:4 Comment(1)
Duplicative answerEstate
H
0

you can use json serialization utils to quote a java String.

like this:

public class Test{
   public static String quote(String a){
       return JSON.toJsonString(a)
   } 
}

if input is:hello output will be: "hello"

if you want to implement the function by self:

it maybe like this:

public static String quotes(String origin) {

        // 所有的 \ -> \\ 用正则表达为: \\ => \\\\" 再用双引号quote起来: \\\\ ==> \\\\\\\\"
        origin = origin.replaceAll("\\\\", "\\\\\\\\");
        //  " -> \" regExt: \" => \\\" quote to param: \\\" ==> \\\\\\\"
        origin = origin.replaceAll("\"", "\\\\\\\"");

        // carriage return: -> \n \\\n
        origin = origin.replaceAll("\\n", "\\\\\\n");

        // tab -> \t
        origin = origin.replaceAll("\\t", "\\\\\\t");
        return origin;
    }

the above implementation will quote escape character in string but exclude the " at the start and end.

the above implementation is incomplete. if other escape character you need , you can add to it.

Hyperboloid answered 20/2, 2022 at 12:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.