String

Figure 104. String literal Slide presentation
Code Result
String claim = "This is kind of important";

IO.println( claim);
This is kind of important

exercise No. 29

Quote inside strings

Q:

Complete the following code so that the output is being created.

Code Result
String claim = ...;

IO.println( claim);
This is "kind of" important

Tip

The two quotes interfere with the outer string delimiters. Java offers a way »escaping« the quote character's syntactical meaning.

A:

Prefixing a backslash solves the issue:

String claim = "This is \"kind of\" important";

IO.println( claim);
Figure 105. Multi line String literal (Java 15) Slide presentation
Code Result Code
IO.println("to be is to do (Sokrates)");
IO.println("to do is to be (Sartre)");
IO.println("do be do be do (Sinatra)");
to be is to do (Sokrates)
to do is to be (Sartre)
do be do be do (Sinatra)
IO.println("""
   to be is to do (Sokrates)
   to do is to be (Sartre)
   do be do be do (Sinatra)""");

exercise No. 30

Quote inside strings

Q:

Use a multi line approach for solving Quote inside strings differently.

Tip

A multi line string is being delimited by three successive quotes """ rather than just one. This offers new chances!

A:

Inside a multi-line string only a groups of three quotes in immediate succession are being prohibited. Thus single quotes no longer pose problems:

IO.println("""
    This is "kind of" important""");