Java Programming/Syntax/Whitespace
Whitespace in Java is used to separate the tokens in a Java source file. Whitespace is required in some places, such as between access modifiers, type names and Identifiers, and is used to improve readability elsewhere.
Wherever whitespace is required in Java, one or more whitespace characters may be used. Wherever whitespace is optional in Java, zero or more whitespace characters may be used.
Java whitespace consists of the
- space character
' '
(0x20), - the tab character (hex 0x09),
- the form feed character (hex 0x0c),
- the line separators characters newline (hex 0x0a) or carriage return (hex 0x0d) characters.
Line separators are special whitespace characters in that they also terminate line comments, whereas normal whitespace does not.
Other Unicode space characters, including vertical tab, are not allowed as whitespace in Java.
[edit] Required Whitespace
Below is the declaration of an abstract
method taken from a Java class
![]() |
public abstract Distance distanceTo(Destination dest);
|
Whitespace is required between public
and abstract
, between abstract
and Distance
, between Distance
and distanceTo
, and between Destination
and dest
.
However, the following is not legal:
![]() |
publicabstractDistance distanceTo(Destination dest);
|
because whitespace is required between keywords and identifiers. The following is lexically valid
![]() |
publicabstractDistance distanceTo(Destination dest);
|
but means something completely different: it declares a method which has the return type publicabstractDistance
It is unlikely that this type exists and the method is no longer abstract, so the above would result in a semantic error.
[edit] Indentation
Java ignores all whitespace in front of a statement. As this, these two code snippets are identical for the compiler:
![]() |
public static void main(String[] args) {
printMessage(); } void printMessage() { System.out.println("Hello World!"); } |
![]() |
public static void main(String[] args) {
printMessage(); } void printMessage() { System.out.println("Hello World!"); } |
However, the first one's style (with whitespace) is preferred, as the readability is higher. The method body is easier to distinguish from the head, even at a higher reading speed.