White Space

White space consists mostly of the space character that you produce by hitting the space bar on your keyboard and that is commonly used to separate words in sentences. There are four other white space characters in Java, the horizontal tab, the form feed, the carriage return, and the linefeed. Depending on your platform, when you hit the return or enter key, you get either a carriage return (the Mac), a linefeed (Unix) or both (DOS, Windows, VMS). This produces a hard line break in the source code text.

Outside of String literals Java treats all white space and runs of white space (more than one white space character in immediate succession) the same. It's used to separate tokens, and one space is as good as seven spaces, a tab and two carriage returns. Exactly which white space characters you use is primarily a result of what's convenient for human beings reading the code. The compiler doesn't care.

Inside String and character literals the only white space permitted is the space character. Carriage returns, tabs, line feeds and form feeds must be inserted with special escape sequences like \r, \t, \f, and \n. You cannot break a String across a line like this:

String poem = "Mary had a little lamb
whose fleece was white as snow
and everywhere that Mary went
the lamb was sure to go.";

Instead you must use \n and the string concatenation operator, +, like this:

String poem = "Mary had a little lamb\n" +
"whose fleece was white as snow\n" +
"and everywhere that Mary went\n" +
"the lamb was sure to go.";

Note that you can break a statement across multiple lines, you just can't break a String literal.

Also note that \n only works on Unix. You should probably use System.getProperty("line.separator") instead to return the proper line separator string for the platform your program is running on.

Java does not have all the escape sequences C has. Besides those already mentioned it has only \b for backspace, \\ for the backslash character itself.

There are also \u escapes that let you include any Unicode character.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999, 2005 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified February 2, 2005