Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Entering Non-Printable Characters

Problem

You need to put non-printable characters into strings.

Solution

Use the backslash character and one of the Java string escapes.

Discussion

The Java string escapes are listed in Table 3-1.

Table 3-1. String escapes

To get:

Use this:

Notes

Tab

\t

 

Linefeed (Unix newline)

\n

See System.getProperty("line.separator"), which gives you the platform’s line end.

Carriage return

\r

 

Form feed

\f

 

Backspace

\b

 

Single quote

\'

 

Double quote

\"

 

Unicode character

\u NNNN

Four hexadecimal digits (no \x as in C/C++). See http://www.unicode.org for codes.

Octal(!) character

\ NNN

Who uses octal (base 8) these days?

Backslash

\\

 

Here is a code example that shows most of these in action:

// StringEscapes.java
System.out.println("Java Strings in action:");
// System.out.println("An alarm or alert: \a");    // not supported
System.out.println("An alarm entered in Octal: \007");
System.out.println("A tab key: \t(what comes after)");
System.out.println("A newline: \n(what comes after)");
System.out.println("A UniCode character: \u0207");
System.out.println("A backslash character: \\");

If you have a lot of non-ASCII characters to enter, you may wish to consider using Java’s input methods, discussed briefly in the JDK online documentation.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata