Content

EmptyForInitializerPad

Since Checkstyle 3.4

Description

Checks the padding of an empty for initializer; that is whether a white space is required at an empty for initializer, or such white space is forbidden. No check occurs if there is a line wrap at the initializer, as in

for (
      ; i < j; i++, j--)
        

Properties

name description type default value since
option Specify policy on how to pad an empty for iterator. PadOption nospace 3.4

Examples

To configure the check:

<module name="EmptyForInitializerPad"/>
        

To configure the check to require white space at an empty for iterator:

<module name="EmptyForInitializerPad">
  <property name="option" value="space"/>
</module>
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

EmptyForIteratorPad

Since Checkstyle 3.0

Description

Checks the padding of an empty for iterator; that is whether a white space is required at an empty for iterator, or such white space is forbidden. No check occurs if there is a line wrap at the iterator, as in

for (Iterator foo = very.long.line.iterator();
      foo.hasNext();
     )
        

Properties

name description type default value since
option Specify policy on how to pad an empty for iterator. PadOption nospace 3.0

Examples

To configure the check:

<module name="EmptyForIteratorPad"/>
        

To configure the check to require white space at an empty for iterator:

<module name="EmptyForIteratorPad">
  <property name="option" value="space"/>
</module>
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

EmptyLineSeparator

Since Checkstyle 5.8

Description

Checks for empty line separators after header, package, all import declarations, fields, constructors, methods, nested classes, static initializers and instance initializers.

ATTENTION: empty line separator is required between token siblings, not after line where token is found. If token does not have same type sibling then empty line is required at its end (for example for CLASS_DEF it is after '}'). Also, trailing comments are skipped.

ATTENTION: violations from multiple empty lines cannot be suppressed via XPath: #8179.

Properties

name description type default value since
allowNoEmptyLineBetweenFields Allow no empty line between fields. boolean false 5.8
allowMultipleEmptyLines Allow multiple empty lines between class members. boolean true 6.3
allowMultipleEmptyLinesInsideClassMembers Allow multiple empty lines inside class members. boolean true 6.18
tokens tokens to check subset of tokens PACKAGE_DEF , IMPORT , STATIC_IMPORT , CLASS_DEF , INTERFACE_DEF , ENUM_DEF , STATIC_INIT , INSTANCE_INIT , METHOD_DEF , CTOR_DEF , VARIABLE_DEF , RECORD_DEF , COMPACT_CTOR_DEF . PACKAGE_DEF , IMPORT , STATIC_IMPORT , CLASS_DEF , INTERFACE_DEF , ENUM_DEF , STATIC_INIT , INSTANCE_INIT , METHOD_DEF , CTOR_DEF , VARIABLE_DEF , RECORD_DEF , COMPACT_CTOR_DEF . 5.8

Examples

To configure the default check:

<module name="EmptyLineSeparator"/>
        

Example of declarations without empty line separator:

///////////////////////////////////////////////////
//HEADER
///////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.whitespace;
import java.io.Serializable;
class Foo {
  public static final int FOO_CONST = 1;
  public void foo() {} //should be separated from previous statement.
}
        

Example of declarations with empty line separator that is expected by the Check by default:

///////////////////////////////////////////////////
//HEADER
///////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.whitespace;

import java.io.Serializable;

class Foo {
  public static final int FOO_CONST = 1;

  public void foo() {}
}
        

To check empty line after VARIABLE_DEF and METHOD_DEF:

<module name="EmptyLineSeparator">
  <property name="tokens" value="VARIABLE_DEF, METHOD_DEF"/>
</module>
        

To allow no empty line between fields:

<module name="EmptyLineSeparator">
  <property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
        

Example:

class Foo {
  int field1; // ok
  double field2; // ok
  long field3, field4 = 10L, field5; // ok
}
        

Example of declarations with multiple empty lines between class members (allowed by default):

///////////////////////////////////////////////////
//HEADER
///////////////////////////////////////////////////


package com.puppycrawl.tools.checkstyle.whitespace;



import java.io.Serializable;


class Foo {
  public static final int FOO_CONST = 1;



  public void foo() {} //should be separated from previous statement.
}
        

To disallow multiple empty lines between class members:

<module name="EmptyLineSeparator">
  <property name="allowMultipleEmptyLines" value="false"/>
</module>
        

To disallow multiple empty lines inside constructor, initialization block and method:

<module name="EmptyLineSeparator">
  <property name="allowMultipleEmptyLinesInsideClassMembers" value="false"/>
</module>
        

The check is valid only for statements that have body: CLASS_DEF , INTERFACE_DEF , ENUM_DEF , STATIC_INIT , INSTANCE_INIT , METHOD_DEF , CTOR_DEF .

Example of declarations with multiple empty lines inside method:

///////////////////////////////////////////////////
//HEADER
///////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.whitespace;

class Foo {

  public void foo() {


    System.out.println(1); // violation since method has 2 empty lines subsequently
  }
}
        

To disallow multiple empty lines between class members:

<module name="EmptyLineSeparator">
  <property name="allowMultipleEmptyLines" value="false"/>
</module>
        

Example:

package com.puppycrawl.tools.checkstyle.whitespace;

class Test {
    private int k;


    private static void foo() {} // violation, before this like there two empty lines

}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

FileTabCharacter

Since Checkstyle 5.0

Description

Checks that there are no tab characters ('\t') in the source code.

Rationale:

  • Developers should not need to configure the tab width of their text editors in order to be able to read source code.
  • From the Apache jakarta coding standards: In a distributed development environment, when the commit messages get sent to a mailing list, they are almost impossible to read if you use tabs.

Properties

name description type default value since
eachLine Control whether to report on each line containing a tab, or just the first instance. boolean false 5.0
fileExtensions Specify file type extension of files to process. String[] all files 5.0

Examples

To configure the check to report only the first instance in each file:

<module name="FileTabCharacter"/>
        

Example - Test.java:

public class Test {
  int a;      // violation, indented using tab

  public void foo (int arg) { // OK, indented using tab, only first occurrence in file reported
      a = arg;                // OK, indented using spaces
  }                           // OK, indented using spaces
}
        

To configure the check to report each instance in each file:

<module name="FileTabCharacter">
  <property name="eachLine" value="true"/>
</module>
        

Example - Test.java:

public class Test {
  int a;      // violation, indented using tab

  public void foo (int arg) { // violation, indented using tab
      a = arg;                // OK, indented using spaces
  }                           // OK, indented using spaces
}
        

To configure the check to report instances on only certain file types:

<module name="FileTabCharacter">
  <property name="fileExtensions" value="java, xml"/>
</module>
        

Example - Test.java:

public class Test {
  int a;      // violation, indented using tab

  public void foo (int arg) { // OK, indented using tab, only first occurrence in file reported
      a = arg;                // OK, indented using spaces
  }                           // OK, indented using spaces
}
        

Example - Test.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<UserAccount>
  <FirstName>John</FirstName> <!-- violation, indented using tab -->
  <LastName>Doe</LastName>    <!-- only first occurrence in file reported -->
</UserAccount>
        

Example - Test.html:

<head>
  <title>Page Title</title> <!-- no check performed, html file extension -->
</head>                     <!-- not specified in check config -->
<body>
  <p>This is a simple html document.</p>
</body>
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

Checker

GenericWhitespace

Since Checkstyle 5.0

Description

Checks that the whitespace around the Generic tokens (angle brackets) "<" and ">" are correct to the typical convention. The convention is not configurable.

Left angle bracket ("<"):

  • should be preceded with whitespace only in generic methods definitions.
  • should not be preceded with whitespace when it is precede method name or constructor.
  • should not be preceded with whitespace when following type name.
  • should not be followed with whitespace in all cases.

Right angle bracket (">"):

  • should not be preceded with whitespace in all cases.
  • should be followed with whitespace in almost all cases, except diamond operators and when preceding method name or constructor.

Examples

To configure the check:

<module name="GenericWhitespace"/>
        

Examples with correct spacing:

// Generic methods definitions
public void <K, V extends Number> boolean foo(K, V) {}
// Generic type definition
class name<T1, T2, ..., Tn> {}
// Generic type reference
OrderedPair<String, Box<Integer>> p;
// Generic preceded method name
boolean same = Util.<Integer, String>compare(p1, p2);
// Diamond operator
Pair<Integer, String> p1 = new Pair<>(1, "apple");
// Method reference
List<T> list = ImmutableList.Builder<T>::new;
// Method reference
sort(list, Comparable::<String>compareTo);
// Constructor call
MyClass obj = new <String>MyClass();
          

Examples with incorrect spacing:

List< String> l; // violation, "<" followed by whitespace
Box b = Box. <String>of("foo"); // violation, "<" preceded with whitespace
public<T> void foo() {} // violation, "<" not preceded with whitespace

List a = new ArrayList<> (); // violation, ">" followed by whitespace
Map<Integer, String>m; // violation, ">" not followed by whitespace
Pair<Integer, Integer > p; // violation, ">" preceded with whitespace
          

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

MethodParamPad

Since Checkstyle 3.4

Description

Checks the padding between the identifier of a method definition, constructor definition, method call, or constructor invocation; and the left parenthesis of the parameter list. That is, if the identifier and left parenthesis are on the same line, checks whether a space is required immediately after the identifier or such a space is forbidden. If they are not on the same line, reports a violation, unless configured to allow line breaks. To allow linebreaks after the identifier, set property allowLineBreaks to true.

Properties

name description type default value since
allowLineBreaks Allow a line break between the identifier and left parenthesis. boolean false 3.4
option Specify policy on how to pad method parameter. PadOption nospace 3.4
tokens tokens to check subset of tokens CTOR_DEF , LITERAL_NEW , METHOD_CALL , METHOD_DEF , SUPER_CTOR_CALL , ENUM_CONSTANT_DEF , RECORD_DEF . CTOR_DEF , LITERAL_NEW , METHOD_CALL , METHOD_DEF , SUPER_CTOR_CALL , ENUM_CONSTANT_DEF , RECORD_DEF . 3.4

Examples

To configure the check:

<module name="MethodParamPad"/>
        
public class Test {
  public Test() { // OK
    super(); // OK
  }

  public Test (int aParam) { // Violation - '(' is preceded with whitespace
    super (); // Violation - '(' is preceded with whitespace
  }

  public void method() {} // OK

  public void methodWithVeryLongName
    () {} // Violation - '(' is preceded with whitespace

}
        

To configure the check to require a space after the identifier of a method definition, except if the left parenthesis occurs on a new line:

<module name="MethodParamPad">
  <property name="tokens" value="METHOD_DEF"/>
  <property name="option" value="space"/>
  <property name="allowLineBreaks" value="true"/>
</module>
        
public class Test {
  public Test() { // OK
    super(); // OK
  }

  public Test (int aParam) { // OK
    super (); // OK
  }

  public void method() {} // Violation - '(' is NOT preceded with whitespace

  public void methodWithVeryLongName
    () {} // OK, because allowLineBreaks is true

}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

NoLineWrap

Since Checkstyle 5.8

Description

Checks that chosen statements are not line-wrapped. By default this Check restricts wrapping import and package statements, but it's possible to check any statement.

Properties

name description type default value since
tokens tokens to check subset of tokens IMPORT , STATIC_IMPORT , PACKAGE_DEF , CLASS_DEF , METHOD_DEF , CTOR_DEF , ENUM_DEF , INTERFACE_DEF , RECORD_DEF , COMPACT_CTOR_DEF . PACKAGE_DEF , IMPORT , STATIC_IMPORT . 5.8

Examples

To configure the check to force no line-wrapping in package and import statements (default values):

<module name="NoLineWrap"/>
        

Examples of line-wrapped statements (bad case):

package com.puppycrawl. // violation
    tools.checkstyle.checks;

import com.puppycrawl.tools. // violation
    checkstyle.api.AbstractCheck;

import static java.math. // violation
    BigInteger.ZERO;
        

Examples:

package com.puppycrawl.tools.checkstyle. // violation
  checks.whitespace;

import java.lang.Object; // OK
import java.lang. // violation
  Integer;

import static java.math. // violation
  BigInteger.TEN;
        
package com.puppycrawl.tools.checkstyle.checks.coding; // OK

import java.lang. // violation
  Boolean;

import static java.math.BigInteger.ONE; // OK
        

To configure the check to force no line-wrapping only in import statements:

<module name="NoLineWrap">
  <property name="tokens" value="IMPORT"/>
</module>
        

Example:

package com.puppycrawl. // OK
  tools.checkstyle.checks;

import java.io.*; // OK
import java.lang. // violation
  Boolean;

import static java.math. // OK
  BigInteger.ZERO;
        

To configure the check to force no line-wrapping only in class, method and constructor definitions:

<module name="NoLineWrap">
  <property name="tokens" value="CLASS_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
        

Example:

public class // violation, class definition not wrapped in a single line
  Foo {

  public Foo() { // OK
  }

  public static void // violation, method definition not wrapped in a single line
    doSomething() {
  }
}

public class Bar { // OK

  public // violation, constructor definition not wrapped in a single line
    Bar() {
  }

  public int fun() { // OK
  }
}
        

Examples of not line-wrapped statements (good case):

import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import static java.math.BigInteger.ZERO;
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

NoWhitespaceAfter

Since Checkstyle 3.0

Description

Checks that there is no whitespace after a token. More specifically, it checks that it is not followed by whitespace, or (if linebreaks are allowed) all characters on the line after are whitespace. To forbid linebreaks after a token, set property allowLineBreaks to false.

The check processes ARRAY_DECLARATOR and INDEX_OP tokens specially from other tokens. Actually it is checked that there is no whitespace before this tokens, not after them. Space after the ANNOTATIONS before ARRAY_DECLARATOR and INDEX_OP will be ignored.

Properties

name description type default value since
allowLineBreaks Control whether whitespace is allowed if the token is at a linebreak. boolean true 3.0
tokens tokens to check subset of tokens ARRAY_INIT , AT , INC , DEC , UNARY_MINUS , UNARY_PLUS , BNOT , LNOT , DOT , TYPECAST , ARRAY_DECLARATOR , INDEX_OP , LITERAL_SYNCHRONIZED , METHOD_REF . ARRAY_INIT , AT , INC , DEC , UNARY_MINUS , UNARY_PLUS , BNOT , LNOT , DOT , ARRAY_DECLARATOR , INDEX_OP . 3.0

Examples

To configure the check:

<module name="NoWhitespaceAfter"/>
        

To configure the check to forbid linebreaks after a DOT token:

<module name="NoWhitespaceAfter">
  <property name="tokens" value="DOT"/>
  <property name="allowLineBreaks" value="false"/>
</module>
        

If the annotation is between the type and the array, the check will skip validation for spaces:

public void foo(final char @NotNull [] param) {} // No violation
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

NoWhitespaceBefore

Since Checkstyle 3.0

Description

Checks that there is no whitespace before a token. More specifically, it checks that it is not preceded with whitespace, or (if linebreaks are allowed) all characters on the line before are whitespace. To allow linebreaks before a token, set property allowLineBreaks to true. No check occurs before semi-colons in empty for loop initializers or conditions.

Properties

name description type default value since
allowLineBreaks Control whether whitespace is allowed if the token is at a linebreak. boolean false 3.0
tokens tokens to check subset of tokens COMMA , SEMI , POST_INC , POST_DEC , DOT , GENERIC_START , GENERIC_END , ELLIPSIS , LABELED_STAT , METHOD_REF . COMMA , SEMI , POST_INC , POST_DEC , ELLIPSIS , LABELED_STAT . 3.0

Examples

To configure the check:

<module name="NoWhitespaceBefore"/>
        

Example:

int foo;
foo ++; // violation, whitespace before '++' is not allowed
foo++; // OK
for (int i = 0 ; i < 5; i++) {}  // violation
           // ^ whitespace before ';' is not allowed
for (int i = 0; i < 5; i++) {} // OK
int[][] array = { { 1, 2 }
                , { 3, 4 } }; // violation, whitespace before ',' is not allowed
int[][] array2 = { { 1, 2 },
                   { 3, 4 } }; // OK
Lists.charactersOf("foo").listIterator()
       .forEachRemaining(System.out::print)
       ; // violation, whitespace before ';' is not allowed
{
  label1 : // violation, whitespace before ':' is not allowed
  for (int i = 0; i < 10; i++) {}
}

{
  label2: // OK
  while (true) {}
}
        

To configure the check to allow linebreaks before default tokens:

<module name="NoWhitespaceBefore">
  <property name="allowLineBreaks" value="true"/>
</module>
        

Example:

int[][] array = { { 1, 2 }
                , { 3, 4 } }; // OK, linebreak is allowed before ','
int[][] array2 = { { 1, 2 },
                   { 3, 4 } }; // OK, ideal code
void ellipsisExample(String ...params) {}; // violation, whitespace before '...' is not allowed
void ellipsisExample2(String
                        ...params) {}; //OK, linebreak is allowed before '...'
Lists.charactersOf("foo")
       .listIterator()
       .forEachRemaining(System.out::print); // OK
        

To Configure the check to restrict the use of whitespace before METHOD_REF and DOT tokens:

<module name="NoWhitespaceBefore">
  <property name="tokens" value="METHOD_REF"/>
  <property name="tokens" value="DOT"/>
</module>
        

Example:

Lists.charactersOf("foo").listIterator()
       .forEachRemaining(System.out::print); // violation, whitespace before '.' is not allowed
Lists.charactersOf("foo").listIterator().forEachRemaining(System.out ::print); // violation,
                          // whitespace before '::' is not allowed  ^
Lists.charactersOf("foo").listIterator().forEachRemaining(System.out::print); // OK
        

To configure the check to allow linebreak before METHOD_REF and DOT tokens:

<module name="NoWhitespaceBefore">
  <property name="tokens" value="METHOD_REF"/>
  <property name="tokens" value="DOT"/>
  <property name="allowLineBreaks" value="true"/>
</module>
        

Example:

Lists .charactersOf("foo") //violation, whitespace before '.' is not allowed
        .listIterator()
        .forEachRemaining(System.out ::print); // violation,
                                 // ^ whitespace before '::' is not allowed
Lists.charactersOf("foo")
       .listIterator()
       .forEachRemaining(System.out::print); // OK
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

OperatorWrap

Since Checkstyle 3.0

Description

Checks the policy on how to wrap lines on operators.

Properties

Examples

To configure the check:

<module name="OperatorWrap"/>
        

Example:

class Test {
    public static void main(String[] args) {
        String s = "Hello" +
        "World"; // violation, '+' should be on new line

        if (10 ==
                20) { // violation, '==' should be on new line.
        // body
        }
        if (10
                ==
                20) { // ok
        // body
        }

        int c = 10 /
                5; // violation, '/' should be on new line.

        int d = c
                + 10; // ok
    }

}
        

To configure the check for assignment operators at the end of a line:

<module name="OperatorWrap">
  <property name="tokens"
    value="ASSIGN,DIV_ASSIGN,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,MOD_ASSIGN,
           SR_ASSIGN,BSR_ASSIGN,SL_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN,BAND_ASSIGN"/>
  <property name="option" value="eol"/>
</module>
        

Example:

class Test {
    public static void main(String[] args) {
            int b
                    = 10; // violation, '=' should be on previous line
            int c =
                    10; // ok
            b
                    += 10; // violation, '+=' should be on previous line
            b +=
                    10; // ok
            c
                    *= 10; // violation, '*=' should be on previous line
            c *=
                    10; // ok
            c
                    -= 5; // violation, '-=' should be on previous line
            c -=
                    5; // ok
            c
                    /= 2; // violation, '/=' should be on previous line
            c
                    %= 1; // violation, '%=' should be on previous line
            c
                    >>= 1; // violation, '>>=' should be on previous line
            c
                >>>= 1; // violation, '>>>=' should be on previous line
        }
        public void myFunction() {
            c
                    ^= 1; // violation, '^=' should be on previous line
            c
                    |= 1; // violation, '|=' should be on previous line
            c
                    &=1 ; // violation, '&=' should be on previous line
            c
                    <<= 1; // violation, '<<=' should be on previous line
    }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

ParenPad

Since Checkstyle 3.0

Description

Checks the policy on the padding of parentheses; that is whether a space is required after a left parenthesis and before a right parenthesis, or such spaces are forbidden. No check occurs at the right parenthesis after an empty for iterator, at the left parenthesis before an empty for initialization, or at the right parenthesis of a try-with-resources resource specification where the last resource variable has a trailing semi-colon. Use Check EmptyForIteratorPad to validate empty for iterators and EmptyForInitializerPad to validate empty for initializers. Typecasts are also not checked, as there is TypecastParenPad to validate them.

Properties

Examples

To configure the check:

<module name="ParenPad"/>
        

Example:

class Foo {

  int n;

  public void fun() {  // OK
    bar( 1);  // violation, space after left parenthesis
  }

  public void bar(int k ) {  // violation, space before right parenthesis
    while (k > 0) {  // OK
    }

    Test obj = new Test(k);  // OK
  }

  public void fun2() {  // OK
    switch( n) {  // violation, space after left parenthesis
      case 2:
        bar(n);  // OK
      default:
        break;
    }
  }

}
        

To configure the check to require spaces for the parentheses of constructor, method, and super constructor calls:

<module name="ParenPad">
  <property name="tokens" value="LITERAL_FOR, LITERAL_CATCH,
    SUPER_CTOR_CALL"/>
  <property name="option" value="space"/>
</module>
        

Example:

class Foo {

  int x;

  public Foo(int n) {
  }

  public void fun() {
    try {
      System.out.println(x);
    } catch( IOException e) {  // violation, no space before right parenthesis
    } catch( Exception e ) {  // OK
    }

    for ( int i = 0; i < x; i++ ) {  // OK
    }
  }

}

class Bar extends Foo {

  public Bar() {
    super(1 );  // violation, no space after left parenthesis
  }

  public Bar(int k) {
    super( k ); // OK

    for ( int i = 0; i < k; i++) {  // violation, no space before right parenthesis
    }
  }

}
        

The following cases are not checked:

for ( ; i < j; i++, j--) // no check after left parenthesis
for (Iterator it = xs.iterator(); it.hasNext(); ) // no check before right parenthesis
try (Closeable resource = acquire(); ) // no check before right parenthesis
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

SeparatorWrap

Since Checkstyle 5.8

Description

Checks line wrapping with separators.

Properties

name description type default value since
option Specify policy on how to wrap lines. WrapOption eol 5.8
tokens tokens to check subset of tokens DOT , COMMA , SEMI , ELLIPSIS , AT , LPAREN , RPAREN , ARRAY_DECLARATOR , RBRACK , METHOD_REF . DOT , COMMA . 5.8

Examples

To configure the check:

<module name="SeparatorWrap"/>
        

Example:

import java.io.
         IOException; // OK

class Test {

  String s;

  public void foo(int a,
                    int b) { // OK
  }

  public void bar(int p
                    , int q) { // violation, separator comma on new line
    if (s
          .isEmpty()) { // violation, separator dot on new line
    }
  }

}
        

To configure the check for METHOD_REF at new line:

<module name="SeparatorWrap">
  <property name="tokens" value="METHOD_REF"/>
  <property name="option" value="nl"/>
</module>
        

Example:

import java.util.Arrays;

class Test2 {

  String[] stringArray = {"foo", "bar"};

  void fun() {
    Arrays.sort(stringArray, String::
      compareToIgnoreCase);  // violation, separator method reference on same line
    Arrays.sort(stringArray, String
      ::compareTo);  // OK
  }

}
        

To configure the check for comma at the new line:

<module name="SeparatorWrap">
  <property name="tokens" value="COMMA"/>
  <property name="option" value="nl"/>
</module>
        

Example:

class Test3 {

  String s;

  int a,
    b;  // violation, separator comma on same line

  public void foo(int a,
                     int b) {  // violation, separator comma on the same line
    int r
      , t; // OK
  }

  public void bar(int p
                    , int q) {  // OK
  }

}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

SingleSpaceSeparator

Since Checkstyle 6.19

Description

Checks that non-whitespace characters are separated by no more than one whitespace. Separating characters by tabs or multiple spaces will be reported. Currently the check doesn't permit horizontal alignment. To inspect whitespaces before and after comments, set the property validateComments to true.

Setting validateComments to false will ignore cases like:

int i;  // Multiple whitespaces before comment tokens will be ignored.
private void foo(int  /* whitespaces before and after block-comments will be
ignored */  i) {
        

Sometimes, users like to space similar items on different lines to the same column position for easier reading. This feature isn't supported by this check, so both braces in the following case will be reported as violations.

public long toNanos(long d)  { return d;             } // 2 violations
public long toMicros(long d) { return d / (C1 / C0); }
        

Properties

name description type default value since
validateComments Control whether to validate whitespaces surrounding comments. boolean false 6.19

Examples

To configure the check:

<module name="SingleSpaceSeparator"/>
        

Example:

int foo()   { // violation, 3 whitespaces
  return  1; // violation, 2 whitespaces
}
int fun1() { // OK, 1 whitespace
  return 3; // OK, 1 whitespace
}
void  fun2() {} // violation, 2 whitespaces
        

To configure the check so that it validates comments:

<module name="SingleSpaceSeparator">
  <property name="validateComments" value="true"/>
</module>
        

Example:

void fun1() {}  // violation, 2 whitespaces before the comment starts
void fun2() { return; }  /* violation here, 2 whitespaces before the comment starts */

/* violation, 2 whitespaces after the comment ends */  int a;

String s; /* OK, 1 whitespace */

/**
 * This is a Javadoc comment
 */  int b; // violation, 2 whitespaces after the javadoc comment ends

float f1; // OK, 1 whitespace

/**
 * OK, 1 white space after the doc comment ends
 */ float f2;
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

TypecastParenPad

Since Checkstyle 3.2

Description

Checks the policy on the padding of parentheses for typecasts. That is, whether a space is required after a left parenthesis and before a right parenthesis, or such spaces are forbidden.

Properties

name description type default value since
option Specify policy on how to pad parentheses. PadOption nospace 3.2

Examples

To configure the check:

<module name="TypecastParenPad"/>
        

Example:

class Foo {

  float f1 = 3.14f;

  int n = ( int ) f1; // violation, space after left parenthesis and before right parenthesis

  double d = 1.234567;

  float f2 = (float ) d; // violation, space before right parenthesis

  float f3 = (float) d; // OK

  float f4 = ( float) d; // violation, space after left parenthesis

}
        

To configure the check to require spaces:

<module name="TypecastParenPad">
  <property name="option" value="space"/>
</module>
        

Example:

class Bar {

  double d1 = 3.14;

  int n = ( int ) d1; // OK

  int m = (int ) d1; // violation, no space after left parenthesis

  double d2 = 9.8;

  int x = (int) d2; // violation, no space after left parenthesis and before right parenthesis

  int y = ( int) d2; // violation, no space before right parenthesis

}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

WhitespaceAfter

Since Checkstyle 3.0

Description

Checks that a token is followed by whitespace, with the exception that it does not check for whitespace after the semicolon of an empty for iterator. Use Check EmptyForIteratorPad to validate empty for iterators.

Properties

name description type default value since
tokens tokens to check subset of tokens COMMA , SEMI , TYPECAST , LITERAL_IF , LITERAL_ELSE , LITERAL_WHILE , LITERAL_DO , LITERAL_FOR , DO_WHILE . COMMA , SEMI , TYPECAST , LITERAL_IF , LITERAL_ELSE , LITERAL_WHILE , LITERAL_DO , LITERAL_FOR , DO_WHILE . 3.0

Examples

To configure the check:

<module name="WhitespaceAfter"/>
        

Example:

public void myTest() {
    if (foo) {              // OK
        //...
    } else if(bar) {        // violation
        //...
    }

    testMethod(foo, bar);   // OK
    testMethod(foo,bar);    // violation

    for (;;){}               // OK
    for(;;){}                // violation, space after 'for' is required
}
          

To configure the check for whitespace only after COMMA and SEMI tokens:

<module name="WhitespaceAfter">
  <property name="tokens" value="COMMA, SEMI"/>
</module>
        

Example:

public void myTest() {
    int a; int b;           // OK
    int a;int b;            // violation

    testMethod(foo, bar);   // OK
    testMethod(foo,bar);    // violation

    for(;;) {} // OK
}
          

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker

WhitespaceAround

Since Checkstyle 3.0

Description

Checks that a token is surrounded by whitespace. Empty constructor, method, class, enum, interface, loop bodies (blocks), lambdas of the form

public MyClass() {}      // empty constructor
public void func() {}    // empty method
public interface Foo {} // empty interface
public class Foo {} // empty class
public enum Foo {} // empty enum
MyClass c = new MyClass() {}; // empty anonymous class
while (i = 1) {} // empty while loop
for (int i = 1; i > 1; i++) {} // empty for loop
do {} while (i = 1); // empty do-while loop
Runnable noop = () -> {}; // empty lambda
public @interface Beta {} // empty annotation type
        

may optionally be exempted from the policy using the allowEmptyMethods, allowEmptyConstructors, allowEmptyTypes, allowEmptyLoops, allowEmptyLambdas and allowEmptyCatches properties.

This check does not flag as violation double brace initialization like:


new Properties() {{
    setProperty("key", "value");
}};
          

Parameter allowEmptyCatches allows to suppress violations when token list contains SLIST to check if beginning of block is surrounded by whitespace and catch block is empty, for example:


try {
    k = 5 / i;
} catch (ArithmeticException ex) {}
          

With this property turned off, this raises violation because the beginning of the catch block (left curly bracket) is not separated from the end of the catch block (right curly bracket).

Properties

name description type default value since
allowEmptyConstructors Allow empty constructor bodies. boolean false 4.0
allowEmptyMethods Allow empty method bodies. boolean false 4.0
allowEmptyTypes Allow empty class, interface and enum bodies. boolean false 5.8
allowEmptyLoops Allow empty loop bodies. boolean false 5.8
allowEmptyLambdas Allow empty lambda bodies. boolean false 6.14
allowEmptyCatches Allow empty catch bodies. boolean false 7.6
ignoreEnhancedForColon Ignore whitespace around colon in enhanced for loop. boolean true 5.5
tokens tokens to check subset of tokens ASSIGN , ARRAY_INIT , BAND , BAND_ASSIGN , BOR , BOR_ASSIGN , BSR , BSR_ASSIGN , BXOR , BXOR_ASSIGN , COLON , DIV , DIV_ASSIGN , DO_WHILE , EQUAL , GE , GT , LAMBDA , LAND , LCURLY , LE , LITERAL_CATCH , LITERAL_DO , LITERAL_ELSE , LITERAL_FINALLY , LITERAL_FOR , LITERAL_IF , LITERAL_RETURN , LITERAL_SWITCH , LITERAL_SYNCHRONIZED , LITERAL_TRY , LITERAL_WHILE , LOR , LT , MINUS , MINUS_ASSIGN , MOD , MOD_ASSIGN , NOT_EQUAL , PLUS , PLUS_ASSIGN , QUESTION , RCURLY , SL , SLIST , SL_ASSIGN , SR , SR_ASSIGN , STAR , STAR_ASSIGN , LITERAL_ASSERT , TYPE_EXTENSION_AND , WILDCARD_TYPE , GENERIC_START , GENERIC_END , ELLIPSIS . ASSIGN , BAND , BAND_ASSIGN , BOR , BOR_ASSIGN , BSR , BSR_ASSIGN , BXOR , BXOR_ASSIGN , COLON , DIV , DIV_ASSIGN , DO_WHILE , EQUAL , GE , GT , LAMBDA , LAND , LCURLY , LE , LITERAL_CATCH , LITERAL_DO , LITERAL_ELSE , LITERAL_FINALLY , LITERAL_FOR , LITERAL_IF , LITERAL_RETURN , LITERAL_SWITCH , LITERAL_SYNCHRONIZED , LITERAL_TRY , LITERAL_WHILE , LOR , LT , MINUS , MINUS_ASSIGN , MOD , MOD_ASSIGN , NOT_EQUAL , PLUS , PLUS_ASSIGN , QUESTION , RCURLY , SL , SLIST , SL_ASSIGN , SR , SR_ASSIGN , STAR , STAR_ASSIGN , LITERAL_ASSERT , TYPE_EXTENSION_AND . 3.0

Examples

To configure the check:

<module name="WhitespaceAround"/>
        

Example:

class Test {
    public Test(){} // 2 violations, '{' is not followed and preceded by whitespace.
    public static void main(String[] args) {
        if (foo) { // ok
            // body
        }
        else{ // violation
            // body
        }

        for (int i = 1; i > 1; i++) {} // violation, '{' is not followed by whitespace.

        Runnable noop = () ->{}; // 2 violations,
                                 // '{' is not followed and preceded by whitespace.
        try {
            // body
        } catch (Exception e){} // 2 violations,
                                // '{' is not followed and preceded by whitespace.

        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        for (char item: vowels) { // ok, because ignoreEnhancedForColon is true by default
            // body
        }
    }
}
        

To configure the check for whitespace only around assignment operators:

<module name="WhitespaceAround">
  <property name="tokens"
    value="ASSIGN,DIV_ASSIGN,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,
           MOD_ASSIGN,SR_ASSIGN,BSR_ASSIGN,SL_ASSIGN,BXOR_ASSIGN,
           BOR_ASSIGN,BAND_ASSIGN"/>
</module>
        

Example:

class Test {
    public static void main(String[] args) {
        int b=10; // violation
        int c = 10; // ok
        b+=10; // violation
        b += 10; // ok
        c*=10; // violation
        c *= 10; // ok
        c-=5; // violation
        c -= 5; // ok
        c/=2; // violation
        c /= 2; // ok
        c%=1; // violation
        c %= 1; // ok
        c>>=1; // violation
        c >>= 1; // ok
        c>>>=1; // violation
        c >>>= 1; // ok
    }
    public void myFunction() {
        c^=1; // violation
        c ^= 1; // ok
        c|=1; // violation
        c |= 1; // ok
        c&=1; // violation
        c &= 1; // ok
        c<<=1; // violation
        c <<= 1; // ok
    }
}
        

To configure the check for whitespace only around curly braces:

<module name="WhitespaceAround">
  <property name="tokens" value="LCURLY,RCURLY"/>
</module>
        

Example:

class Test {
    public void myFunction() {} // violation
    public void myFunction() { } // ok
}
        

To configure the check to allow empty method bodies:

<module name="WhitespaceAround">
  <property name="allowEmptyMethods" value="true"/>
</module>
        

Example:

class Test {
    public void muFunction() {} // ok
    int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
}
        

To configure the check to allow empty constructor bodies:

<module name="WhitespaceAround">
  <property name="allowEmptyConstructors" value="true"/>
</module>
        

Example:

class Test {
    public Test(){} // ok
    public void muFunction() {} // violation, '{' is not followed by whitespace.
}
        

To configure the check to allow empty type bodies:

<module name="WhitespaceAround">
  <property name="allowEmptyTypes" value="true"/>
</module>
        

Example:

class Test {} // ok
interface testInterface{} // ok
class anotherTest {
    int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
}
        

To configure the check to allow empty loop bodies:

<module name="WhitespaceAround">
  <property name="allowEmptyLoops" value="true"/>
</module>
        

Example:

class Test {
    public static void main(String[] args) {
        for (int i = 100;i > 10; i--){} // ok
        do {} while (i = 1); // ok
        int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
    }
}
        

To configure the check to allow empty lambda bodies:

<module name="WhitespaceAround">
  <property name="allowEmptyLambdas" value="true"/>
</module>
        

Example:

class Test {
    public static void main(String[] args) {
        Runnable noop = () -> {}; // ok
        int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
    }
}
        

To configure the check to allow empty catch bodies:

<module name="WhitespaceAround">
  <property name="allowEmptyCatches" value="true"/>
</module>
        

Example:

class Test {
    public static void main(String[] args) {
        int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
        try {
            // body
        } catch (Exception e){} // ok
    }
}
        

Also, this check can be configured to ignore the colon in an enhanced for loop. The colon in an enhanced for loop is ignored by default.

To configure the check to ignore the colon:

<module name="WhitespaceAround">
  <property name="ignoreEnhancedForColon" value="false" />
</module>
        

Example:

class Test {
    public static void main(String[] args) {
        int a=4; // 2 violations , '=' is not followed and preceded by whitespace.
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        for (char item: vowels) { // violation, ':' is not preceded by whitespace.
            // body
        }
    }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.whitespace

Parent Module

TreeWalker