String type represents sequences of Unicode characters.
A sequence of characters enclosed in double quotes or single quotes is a string literal.
The number of characters is the length of the string.
The following are examples of using string literals:
The following are examples of using string literals:
var greetings = "Hi there"; var title = 'Java Tutorial'; var emptyMsg = "";
A string literal can contain single quotes if it is enclosed in double quotes and vice versa.
And we can escape the double quote using a backslash.
var msg1 = "It's Monday."; var msg2 = 'He said, "Today is Monday."'; var msg3 = 'It\'s Monday.'; var msg4 = "He said, \"Today is Monday.\"";
A string literal in Nashorn can be written in mutiple lines. Use a backslash at the end of the line as the continuation character.
The backslash and the line terminator are not part of the string literal.
The following code has a string in three lines:
var msg = "Hello \ world\ !"; print(msg);
To insert a newline character, use the escape sequence \n.
var msg= "\ Line one\n\ Line two\n\ Line Three\n\ Line Four\ "; print(msg);
The following table lists the escape sequences defined in Nashorn.
Character Escape Sequence | Unicode Escape Sequence | Character Name |
---|---|---|
\b | \u0008 | backspace |
\t | \u0009 | horizontal tab |
\n | \u000A | new line |
\v | \u000B | vertical tab |
\f | \u000C | form feed |
\r | \u000D | carriage return |
\" | \u0022 | double quote |
\' | \u0027 | single quote |
\\ | \u005C | backslash |