Skip to content

Latest commit

 

History

History
83 lines (63 loc) · 2.69 KB

File metadata and controls

83 lines (63 loc) · 2.69 KB

About

The key thing to remember about Java strings is that they are immutable objects representing text as a sequence of Unicode characters (letters, digits, punctuation, etc.). Double quotes are used to define a String instance:

String fruit = "Apple";

Manipulating a string can be done using method of class String. As string values can never change after having been defined, all string manipulation methods will return a new string.

A string is delimited by double quote (") characters. Some special characters need escaping using the backslash (\) character. Characters to be escaped in Java:

  • "
  • \
String escaped = "c:\\test.txt";
// => c:\test.txt

To put a newline character in a string, use the \n escape code (\r\n on Windows):

"<html>\n    <body>\n        <h1>Hello, World!</h1>\n    </body>\n</html>\n"

For code that should work on varying operating systems Java offers System.lineSeparator(), which returns the system-dependent line separator string. This is important if you're writing to files that will be read on the same system.

To comfortable work with texts that contain a lot of newlines you can use Text Blocks. These multi-line strings are delimited by triple double quote (") characters.

String multilineHtml = """
<html>
    <body>
        <h1>Hello, World!</h1>
    </body>
</html>
""";
// => "<html>\n    <body>\n        <h1>Hello, World!</h1>\n    </body>\n</html>\n"

Finally, there are many ways to concatenate a string. The simplest one is the + operator:

String name = "Jane";
"Hello " + name + "!";
// => "Hello Jane!"

For any string formatting more complex than simple concatenation, String.format method is preferred.

String name = "Jane";
String.format("Hello %s!", name);
// => "Hello Jane!"

The conversion %n in a format string inserts a system-dependent line separator.

String name = "Jane";
String.format("Hello,%n%s!", name);
// => "Hello,\nJane!" (Linux, macOS)
// => "Hello,\r\nJane!" (Windows)

Other possibilities to build more complex strings are: