14 / 100

In Java, a string is a sequence of characters enclosed within double quotes (” “). Sometimes, you may need to include double quotes within a string. For example, you may want to print a message that includes a quote, such as “He said, “Hello!“.

You can use an escape character to include quotation marks within a string in Java. An escape character is a backslash (), indicating to the compiler that the next character is special. You can use the escape character to include a double quote within a string “.

Here’s an example:

 


String message = "He said, \"Hello!\"";
System.out.println(message);

 

Output

 


He said, "Hello!" 

 

In this example, we used the escape character “to include double quotes within the string. The backslash tells the compiler that the next character is a special character, not the string’s end.

You can also use single quotes to define a literal string containing double quotes. You don’t need to escape the double quotes when you use single quotes. For example:

 


String message = 'He said, "Hello!"';
System.out.println(message); 

 

Output:

 


He said, "Hello!"

 

In this example, we used single quotes to define the literal string containing double quotes. Because we used single quotes, we didn’t need to escape the double quotes.

It’s important to note that you can’t use a single backslash () within a string literal to escape a double quote. For example, the following code will not compile:

 


String message = "He said, "\"Hello!\"";  // Error: Invalid escape sequence 

 

You must use the escape character to include a double quote within a string “.

In summary, to include quotation marks within a string in Java, you can use the escape character ” or define the string literally with single quotes.