How to insert double quotes into a string in Java

In this tutorial, you will see how to insert double quotes into a string in Java. Sometimes you need to print those statements in a program where you may have double quotes printed on a sentence and if you think that you can achieve this by writing the program like System.out.println(“hello “hi” world!”) then you will get an error,

HelloWorld.java:4: error: ')' expected
        System.out.println("Hello"hii"World");
                                  ^
HelloWorld.java:4: error: not a statement
        System.out.println("Hello"hii"World");
                                     ^
HelloWorld.java:4: error: ';' expected
        System.out.println("Hello"hii"World");
                                            ^
3 errors

The above shown will be the thing that you will get after printing the above statement. So, if you want to get rid of this error and to really print the statement with double quotes present inside the print statement then, you are at the right place to enhance your knowledge of how to insert double quotes into a string.
Removing Double Quotes from a String in Java

Insert double quotes into a string in Java

You can achieve it by following ways:-

1) By Escape characters
An escape character is a two-character sequence that starts with \ also, it represents a special character, that would otherwise be printable.

Example:-

Class EscapeChar
{
    public static void main(String[] args)
    {
        System.out.println("Hello My name is \"Shubham\" Raj");
    }
}

The output will be-

Hello My name is "shubham" Raj

2) The below code will also let you achieve your solution.

Class Doublequotes
{
    public static void main(String[] args)
    {
        String name="\"shubham\"";
        System.out.println("My name is"+name+"raj");
    }
}

The output will be-

My name is "shubham"raj

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *