Java - How to put quotes in a string

Just type in single quotes in the string.

String str = "'Hello, World'";

But when I put Double Quotes, I get a compile error. This is because the start and end of a string are separated by double quotation marks, so it is not possible to distinguish where the string is.

String str = ""Hello, World"";

Output:

AddQuotesToString.java:9: error: ';' expected
            String str = ""Hello, World"";

Put double quotes in string

When placing double quotes, just put a backslash before the double quotes.

String str = "\"Hello, World\"";
System.out.println(str);

Output:

"Hello, World"

Put double quotes and backslashes in strings

If you want to insert a single backslash into a string, just type the backslash twice as shown below.

To enter a single backslash and a single quotation mark, simply type:

String str = "\\\"Hello, World\"\\";

Output:

\"Hello, World"\
codechachaCopyright ©2019 codechacha