Scripting in Java Tutorial - Scripting in Java String








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.

String literals

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);




Escape Squence

The following table lists the escape sequences defined in Nashorn.

Character Escape SequenceUnicode Escape SequenceCharacter Name
\b\u0008backspace
\t\u0009horizontal tab
\n\u000Anew line
\v\u000Bvertical tab
\f\u000Cform feed
\r\u000Dcarriage return
\"\u0022double quote
\'\u0027single quote
\\\u005Cbackslash