# Rules

This is a list of all the rules that are currently implemented in jSparrow.

# Tags

AssertJ, Coding Conventions, Free, IO Operations, JUnit, Java 1.1, Java 1.2, Java 1.3, Java 1.4, Java 1.7, Java 1.8, Java 10, Java 11, Java 14, Java 15, Java 16, Java 5, Java 6, Java 7, Java 8, Java 9, Lambda, Logging, Loop, Marker, Old Language Constructs, Performance, Readability, Security, Spring, String Manipulation, Testing

# List of Rule IDs

Rule Name Rule ID
Add Braces to Control Statements BracketsToControl
Avoid Concatenation in Logging Statements AvoidConcatenationInLoggingStatements
Chain AssertJ AssertThat Statements ChainAssertJAssertThatStatements
Collapse If Statements CollapseIfStatements
Create Temp Files Using Java NIO CreateTempFilesUsingJavaNIO
Escape User Inputs in SQL Queries EscapeUserInputsInSQLQueries
Hide Default Constructor In Utility Classes HideDefaultConstructorInUtilityClasses
Inline Local Variables InlineLocalVariables
Insert Break Statements in For-loops InsertBreakStatementInLoops
Make Fields And Variables Final MakeFieldsAndVariablesFinal
Make SerialVersionUID Static Final SerialVersionUID
Organize Imports OrganizeImports
Rearrange Class Members RearrangeClassMembers
Reformat Code CodeFormatter
Remove Boxing for String Conversions PrimitiveBoxedForString
Remove Collection::addAll RemoveCollectionAddAll
Remove Deprecated Date Constructs DateDeprecated
Remove Double Negations RemoveDoubleNegation
Remove Explicit Call To super() RemoveExplicitCallToSuper
Remove Explicit Type Argument DiamondOperator
Remove Inherited Interfaces from Class Declaration ReImplementingInterface
Remove Lambda Expression Braces StatementLambdaToExpression
Remove Modifiers in Interface Properties RemoveModifiersInInterfaceProperties
Remove Null-Checks Before Instanceof RemoveNullCheckBeforeInstanceof
Remove Redundant Close RemoveRedundantClose
Remove Redundant Type Casts RemoveRedundantTypeCast
Remove toString() on String RemoveToStringOnString
Remove Unnecessary Semicolons RemoveEmptyStatement
Remove Unnecessary Thrown Exceptions on Method Signatures RemoveUnnecessaryThrows
Remove Unused Fields RemoveUnusedFields
Remove Unused Local Variables RemoveUnusedLocalVariables
Remove Unused Methods RemoveUnusedMethods
Remove Unused Parameters in Private Methods RemoveUnusedParameter
Remove Unused Types RemoveUnusedTypes
Rename Fields FieldRenaming
Reorder Modifiers ReorderModifiers
Reorder String Equality Check StringLiteralEqualityCheck
Replace Assignment with Compound Operator ArithmethicAssignment
Replace Collection.sort with List.sort UseListSort
Replace Concatenation with Infix-Operation StringConcatToPlus
Replace Equality Check with isEmpty() UseIsEmptyOnCollections
Replace equals() on Enum Constants EnumsWithoutEquals
Replace Expression Lambda with Method Reference LambdaToMethodReference
Replace For-Loop with Enhanced-For-Loop ForToForEach
Replace For-Loop with Iterable::forEach EnhancedForLoopToStreamForEach
Replace For-Loop with Stream::collect(Collectors.joining()) StringBuildingLoop
Replace For-Loop with Stream::findFirst EnhancedForLoopToStreamFindFirst
Replace For-Loop with Stream::Match EnhancedForLoopToStreamAnyMatch
Replace For-Loop with Stream::sum EnhancedForLoopToStreamSum
Replace For-Loop with Stream::takeWhile EnhancedForLoopToStreamTakeWhile
Replace indexOf() with contains() IndexOfToContains
Replace Inefficient Constructors with valueOf() InefficientConstructor
Replace JUnit 3 Tests ReplaceJUnit3TestCases
Replace JUnit 4 Annotations with JUnit Jupiter ReplaceJUnit4AnnotationsWithJupiter
Replace JUnit 4 Assertions with JUnit Jupiter ReplaceJUnit4AssertionsWithJupiter
Replace JUnit 4 Assumptions with JUnit Jupiter ReplaceJUnit4AssumptionsWithJupiter
Replace JUnit 4 Category with JUnit Jupiter Tag ReplaceJUnit4CategoryWithJupiterTag
Replace JUnit assertThat with Hamcrest ReplaceJUnitAssertThatWithHamcrest
Replace JUnit Assumptions with Hamcrest Junit ReplaceJUnit4AssumptionsWithHamcrestJUnit
Replace JUnit Expected Annotation Property with assertThrows ReplaceJUnitExpectedAnnotationProperty
Replace JUnit ExpectedException with assertThrows ReplaceJUnitExpectedException
Replace JUnit Timeout Annotation Property with assertTimeout ReplaceJUnitTimeoutAnnotationProperty
Replace Map::get by Map::getOrDefault MapGetOrDefault
Replace Multi Branch If By Switch ReplaceMultiBranchIfBySwitch
Replace Nested Loops with flatMap FlatMapInsteadOfNestedLoops
Replace put(..) with putIfAbsent(..) PutIfAbsent
Replace removeAll() with clear() CollectionRemoveAll
Replace Request Mapping Annotation ReplaceRequestMappingAnnotation
Replace Set.removeAll With ForEach ReplaceSetRemoveAllWithForEach
Replace static final Collections with Collections.unmodifiable...() ImmutableStaticFinalCollections
Replace Stream Collect By ToList ReplaceStreamCollectByToList
Replace String Format by Formatted ReplaceStringFormatByFormatted
Replace While-Loop with Enhanced For-Loop WhileToForEach
Replace Wrong Class for Logger ReplaceWrongClassForLogger
Reuse Random Objects ReuseRandomObjects
Shift AssertJ Description Before Assertion ShiftAssertJDescriptionBeforeAssertion
Split Multiple Variable Declarations MultiVariableDeclarationLine
StringBuffer() to StringBuilder() StringBufferToBuilder
System Out To Logging StandardLogger
Use @Override Annotation OverrideAnnotation
Use Arrays Stream UseArraysStream
Use BufferedReader::lines BufferedReaderLines
Use Collections Singleton List UseCollectionsSingletonList
Use Comparator Methods UseComparatorMethods
Use Dedicated Assertions UseDedicatedAssertions
Use Dedicated AssertJ Assertions UseDedicatedAssertJAssertions
Use equals() on Primitive Objects PrimitiveObjectUseEquals
Use Factory Methods for Collections CollectionsFactoryMethods
Use Files.newBufferedReader UseFilesBufferedReader
Use Files.newBufferedWriter UseFilesBufferedWriter
Use Files.writeString UseFilesWriteString
Use Functional Interfaces FunctionalInterface
Use Guard Condition GuardCondition
Use Java Records UseJavaRecords
Use Local Variable Type Inference LocalVariableTypeInference
Use Multi Catch MultiCatch
Use Offset Based String Methods UseOffsetBasedStringMethods
Use Optional::filter OptionalFilter
Use Optional::ifPresent OptionalIfPresent
Use Optional::ifPresentOrElse OptionalIfPresentOrElse
Use Optional::map OptionalMap
Use Parameterized JPA Query UseParameterizedJPAQuery
Use Parameterized LDAP Query UseParameterizedLDAPQuery
Use Parameterized Query UseParameterizedQuery
Use Pattern Matching for Instanceof UsePatternMatchingForInstanceof
Use Portable Newline StringFormatLineSeparator
Use Predefined Standard Charset UsePredefinedStandardCharset
Use SecureRandom UseSecureRandom
Use Stream::collect LambdaForEachCollect
Use Stream::filter LambdaForEachIfWrapperToFilter
Use Stream::map LambdaForEachMap
Use String Join UseStringJoin
Use String Literals RemoveNewStringConstructor
Use StringBuilder::append UseStringBuilderAppend
Use StringUtils Methods StringUtils
Use Switch Expression UseSwitchExpression
Use Ternary Operator UseTernaryOperator
Use Text Block UseTextBlock
Use Try-With-Resource TryWithResource

# Free

The following rules are included directly after installation for Eclipse IDE.

Rule Name
1 Collapse If Statements
2 Replace equals() on Enum Constants
3 Replace For-Loop with Enhanced-For-Loop
4 Replace Inefficient Constructors with valueOf()
5 Replace Expression Lambda with Method Reference
6 Use Optional::filter
7 Split Multiple Variable Declarations
8 Organize Imports
9 Use @Override Annotation
10 Remove Boxing for String Conversions
11 Remove Unnecessary Semicolons
12 Remove Double Negations
13 Remove Null-Checks Before Instanceof
14 Remove toString() on String
15 Remove Unnecessary Thrown Exceptions on Method Signatures
16 Use Try-With-Resource
17 Reorder String Equality Check
18 Replace Equality Check with isEmpty()
19 Use Offset Based String Methods
20 Use SecureRandom

# Summary

Add Braces to Control Statements

Checks if braces are used to encapsulate control statements and adds them if they aren't present.

Read more

Avoid Concatenation in Logging Statements

Avoid always evaluating concatenated logging messages by introducing parameters, which only evaluate when the logging level is active.

Read more

Chain AssertJ AssertThat Statements

AssertJ assertions carried out on the same object can be chained instead of using multiple assertThat, avoiding duplication and increasing the clarity of the code.

Read more

Collapse If Statements

Collapses, when possible, the nested if-statements into a single one by concatenating the conditions with the infix operator &&.

Read more

Create Temp Files Using Java NIO

This rule replaces the temporary file creation using 'java.io.File' by the alternative methods defined in 'java.nio.file.Files'.

Read more

Hide Default Constructor In Utility Classes

Hides the default constructor of utility classes by adding a private constructor.

Read more

Inline Local Variables

This rule scans for local variables which are declared and then immediately returned or thrown and in-lines them if this is possible.

Read more

Insert Break Statements in For-loops

Finds the Enhanced For-loops whose sole purpose is to compute a boolean value without causing side effects and inserts a break statement immediately after the boolean value is computed. Thus, eliminating redundant loop iterations.

Read more

Make Fields And Variables Final

This rule declares private fields and local variables final, if they are effectively final

Read more

Make SerialVersionUID Static Final

Adds the modifiers static and final to SerialVersionUid long variables when they are absent.

Read more

Organize Imports

Organize Imports according to the Eclipse's built in Organize Imports functionality.

Read more

Rearrange Class Members

This rule rearranges the body declarations of a class based on the Oracle Code Convention for File Organization.

Read more

Reformat Code

Reformats code according to the coding conventions defined in Eclipse.

Read more

Remove Boxing for String Conversions

When calling 'toString()' on a boxed primitive no new instance of that primitive has to be created. This rule replaces occurrences of such code with a static method

Read more

Remove Collection::addAll

Calling collection constructors with arguments in order to avoid calls of addAll.

Read more

Remove Deprecated Date Constructs

Some 'java.util.Date' constructors like 'new Date(int year, int month, int day)', 'new Date(int year, int month, int date, int hrs, int min)' and 'new Date(int year, int month, int date, int hrs, int min, int sec)' are deprecated. A 'Calendar' instance should be used instead. This rule searches for deprecated date constructors, introduces calendar instances, sets the time corresponding to the parameters in the deprecated constructor, and replaces the latter with an invocation of 'Calendar.getTime()'.

Read more

Remove Double Negations

Removes multiple negations from boolean expressions.

Read more

Remove Explicit Call To super()

Removes unnecessary explicit call to the default constructor of the super class.

Read more

Remove Explicit Type Argument

Since Java 1.7 the Diamond Operator (<>) can be used to simplify instance creation where generics are involved.

Read more

Remove Inherited Interfaces from Class Declaration

This rule removes interfaces from class declaration, which are already implemented by a super class. These interfaces are inherited from the super class.

Read more

Remove Lambda Expression Braces

If the body of the lambda statement contains only a single expression, the braces are optional. It can be reduced to a lambda expression. This is comparable to if-statements or loops with a single expression inside their body, where braces are also optional.

Read more

Remove Modifiers in Interface Properties

Removes the 'public' modifiers from method declarations and 'public static final' modifiers from field declarations in Java interfaces.

Read more

Remove Null-Checks Before Instanceof

Finds and removes null-checks before occurrences of instanceof. Since null is not an instance of anything, the null-check is redundant.

Read more

Remove Redundant Close

This rule is used to remove redundant 'close()'-invocation statements on resources which are declared in the header of try-with-resource statements.

Read more

Remove Redundant Type Casts

A typecast expression can be removed if it casts an expression to a type which is already exactly the type of the expression. Additionally, also parentheses involved in the cast operation will be removed if they are not necessary any more.

Read more

Remove toString() on String

Removes all invocations of 'toString()' method used on a 'String' element.

Read more

Remove Unnecessary Semicolons

Removes the unnecessary semicolons from the code blocks.

Read more

Remove Unnecessary Thrown Exceptions on Method Signatures

Removes the RuntimeExceptions, duplications and exceptions which are subtypes of already thrown exceptions on the method signatures.

Read more

Remove Unused Fields

Finds and removes fields that are never used actively.

Read more

Remove Unused Local Variables

Finds and removes local variables that are never used actively.

Read more

Remove Unused Methods

Finds and removes methods that are never used in main sources.

Read more

Remove Unused Parameters in Private Methods

Finds and removes unused parameters in private method declarations. Updates the affected method invocations accordingly.

Read more

Remove Unused Types

Finds and removes classes that are never used in main sources.

Read more

Rename Fields

Renames the non-final fields to comply with the naming convention "^[a-z][a-zA-Z0-9]*$" i.e. a lower case prefix followed by any sequence of alpha-numeric characters

Read more

Reorder Modifiers

This rule reorders the modifiers on Type, Field and Method declarations.

Read more

Reorder String Equality Check

Moves the string literals in the left-hand-side of 'equals()' or 'equalsIgnoreCase()' when checking for equality.

Read more

Replace Assignment with Compound Operator

Simplifies arithmetic operations where a compound operator is possible.

Read more

Replace Collection.sort with List.sort

Replace static invocations of 'Collections.sort(List, Comparator)' with 'List.sort(Comparator)'.

Read more

Replace Concatenation with Infix-Operation

This rule replaces the 'concat()' method on 'Strings' with the + operator.

Read more

Replace Equality Check with isEmpty()

This rule replaces comparisons of 'length()' or 'size()' with 0 with a call to 'isEmpty()'. Any occurrences of such a comparison will be replaced, regardless of surrounding control structure.

Read more

Replace equals() on Enum Constants

Replaces occurrences of 'equals()' on Enum constants with an identity comparison (==). In the case the equals relation is wrapped with an boolean negation the result will be an not equals (!=).

Read more

Replace Expression Lambda with Method Reference

This rule simplifies expression lambdas by using method reference. The rule can only be applied if the parameters of the lambda expression and the method match.

Read more

Replace For-Loop with Enhanced-For-Loop

Transforms all possible for loops with iterators to a ForEach loop.

Read more

Replace For-Loop with Iterable::forEach

This rule replaces enhanced for loops (for-each-loops) with an invocation of 'java.lang.Iterable::forEach' method and passes the body of the for-loop as a lambda Consumer parameter.

Read more

Replace For-Loop with Stream::collect(Collectors.joining())

This rule refactors the enhanced for loops which are only being used for concatenating the elements of collections or arrays.

Read more

Replace For-Loop with Stream::findFirst

Replaces enhanced for-loops which are used to find an element within a collection by a stream and uses 'Stream::findFirst' to find the result. By using the stream syntax, a multi-line control statement can be reduced to a single line.

Read more

Replace For-Loop with Stream::Match

Replaces occurrences of enhanced for-loops which are only used to initialize or return a boolean variable with 'Stream::anyMatch', 'Stream::allMatch' or 'Stream::noneMatch'. The stream syntax is more concise and improves readability.

Read more

Replace For-Loop with Stream::sum

Transforms enhanced for-loops which are only used for summing up the elements of a collection to a 'Stream::sum' invocation.

Read more

Replace For-Loop with Stream::takeWhile

The Stream API in Java 9 is extended with the 'takeWhile' method to get the prefix of a stream. This rule replaces the enhanced for-loops with a stream iterating over the prefix of a collection with 'Stream::takeWhile'.

Read more

Replace indexOf() with contains()

This rule replaces calls to 'indexOf()' on instances of Strings or Collections with calls to the 'contains()' method. 'contains()' was introduced in Java 1.4 and helps to make the code more readable.

Read more

Replace Inefficient Constructors with valueOf()

All calls to a constructor of a primitive type will be replaced by the corresponding static 'valueOf()' method. For example 'new Integer("1")' becomes 'Integer.valueOf("1")'.

Read more

Replace JUnit 3 Tests

This rule migrates JUnit 3 tests to either JUnit Jupiter or JUnit 4 depending on the most up-to-date JUnit version available in the classpath.

Read more

Replace JUnit 4 Annotations with JUnit Jupiter

This rule offers a stepwise transition to JUnit 5 by replacing JUnit 4 annotations @Test, @Ignore, @Before, @BeforeClass, @After, and @AfterClass with their corresponding Jupiter alternatives.

Read more

Replace JUnit 4 Assertions with JUnit Jupiter

This rule contributes to the stepwise transition from JUnit 4 to JUnit 5 by replacing the assertions methods defined in JUnit 4 class 'org.junit.Assert' by equivalent assertion methods defined in the JUnit 5 class 'org.junit.jupiter.api.Assertions'.

Read more

Replace JUnit 4 Assumptions with JUnit Jupiter

This rule contributes to the stepwise transition from JUnit 4 to JUnit 5 by replacing the assumption methods defined in the JUnit 4 class 'org.junit.Assume' by equivalent assumption methods defined in the JUnit 5 class 'org.junit.jupiter.api.Assumptions'.

Read more

Replace JUnit 4 Category with JUnit Jupiter Tag

This rule offers a stepwise transition to JUnit 5 by replacing JUnit 4 @Category annotations with JUnit Jupiter @Tag annotations.

Read more

Replace JUnit assertThat with Hamcrest

The JUnit Assert.assertThat method is deprecated. Its sole purpose is to forward the call to the MatcherAssert.assertThat method defined in Hamcrest 1.3. Therefore, it is recommended to directly use the equivalent assertion defined in the third party Hamcrest library.

Read more

Replace JUnit Assumptions with Hamcrest Junit

This rule replaces invocations of the JUnit 4 methods Assume.assumeThat, Assume.assumeNoException and Assume.assumeNotNull with invocations of the hamcrest-junit method MatcherAssume.assumeThat. Thus the use of JUnit 4 methods is replaced by the use of methods of a third party library.

Read more

Replace JUnit Expected Annotation Property with assertThrows

This rule aims to replace the @Test(expected=...) annotation property with 'assertThrows' introduced in JUnit 4.13.

Read more

Replace JUnit ExpectedException with assertThrows

The goal of this rule is to replace the JUnit ExpectedException with 'assertThrows'.

Read more

Replace JUnit Timeout Annotation Property with assertTimeout

This rule aims to replace the @Test(timeout=...) annotation property with 'assertTimeout' in JUnit Jupiter.

Read more

Replace Map::get by Map::getOrDefault

Java 8 introduced 'Map::getOrDefault' which offers the possibility to return a default value if the map does not contain a mapping for the given key. This rule replaces the invocations of 'Map::get' followed by a null-check with 'Map::getOrDefault'.

Read more

Replace Multi Branch If By Switch

In Java 14, the switch expressions turned into a standard feature. This rule replaces multi-branch if statements by corresponding switch expressions or switch statements with switch labeled rules. Because this rule removes a lot of redundant parts of code, readability is improved.

Read more

Replace Nested Loops with flatMap

Nested For-Loops or invocations of forEach commonly used to iterate over all elements of a collection of collections, can be avoided by using flatMap(). Using 'flatMap()' makes code much more readable and can be combined with other stream functions.

Read more

Replace put(..) with putIfAbsent(..)

If 'map.put(..)' is wrapped with a condition verifying the existence of an element one can use 'map.putIfAbsent(...)' instead.

Read more

Replace removeAll() with clear()

Simplifies the code by replacing all occurrences of 'removeAll()' which have the current collection as parameter with 'clear()'.

Read more

Replace Request Mapping Annotation

The Spring Framework 4.3 introduced some composed annotations like '@GetMapping', '@PostMapping', etc, as an alternative of '@RequestMapping(method=...)' for annotating HTTP request handlers. Accordingly, this rule replaces the '@RequestMapping' annotations with their equivalent dedicated alternatives, for example, '@RequestMapping(value = "/hello", method = RequestMethod.GET)' is replaced by '@GetMapping(value = "/hello")'.

Read more

Replace Set.removeAll With ForEach

Calling the method 'removeAll' on a Set with a List as invocation argument may lead to performance problems due to a possible O(n^2) complexity. This rule replaces such invocations. For example, the invocation 'mySet.removeAll(myList);' is replaced by 'myList.forEach(mySet::remove);'.

Read more

Replace static final Collections with Collections.unmodifiable...()

Wraps the initialization of a final collection with 'Collections.unmodifiable...()'

Read more

Replace Stream Collect By ToList

Java 16 introduced 'Stream.toList()' as a shorthand method for converting a Stream into an unmodifiable List. This rule replaces invocations of `collect(Collectors.toUnmodifiableList())` on a stream by the new method `stream.toList()`.

Read more

Replace String Format by Formatted

This rule replaces invocations of the static method `String.format` by invocations of the instance method `String.formatted`.

Read more

Replace While-Loop with Enhanced For-Loop

While-loops over Iterators which could be expressed with a for-loop, are transformed to an equivalent for-loop.

Read more

Replace Wrong Class for Logger

If a given logger is initialized with a class that is different from the class where it is declared, then this rule will replace the wrong initialization argument with the correct one. For example, if a logger for the class 'Employee' is initialized with 'User.class', then the argument of the initialization will be replaced by 'Employee.class'.

Read more

Shift AssertJ Description Before Assertion

This rule shifts the invocation of methods setting descriptions or error messages before the invocations of the actual assertions they intend to describe.

Read more

Split Multiple Variable Declarations

Multiple field or variable declarations on the same line could cause confusion about their types and initial values. That also makes it harder to read and to understand the code. In order to improve readability, each field or variable should be declared on a separate line. This is recommended by the Code Conventions for the Java Programming Language.

Read more

StringBuffer() to StringBuilder()

This rule changes the type of local variables from 'StringBuffer()' to 'StringBuilder()'.

Read more

System Out To Logging

Replaces the standard output statements with logger statements when possible.

Read more

Use @Override Annotation

This rule adds the '@Override' annotation to methods overriding or implementing parent class methods.

Read more

Use Arrays Stream

Rule description.

Read more

Use BufferedReader::lines

Replaces While-Loops and For-Loops that are using 'BufferedReader::readLine' to iterate through lines of a file by a stream generated with 'BufferedReader::lines'.

Read more

Use Collections Singleton List

Replaces Arrays.asList with 0 or 1 parameters respectively with Collections.emptyList() or Collections.singletonList(..)

Read more

Use Comparator Methods

This rule replaces complex lambda expressions that serve as instances of 'java.util.Comparator' by simple invocations of factory methods introduced in the 'java.util.Comparator' interface.

Read more

Use Dedicated Assertions

Replaces boolean assertions e.g., assertTrue and assertFalse with the corresponding dedicated assertions when testing for equality or null values.

Read more

Use Dedicated AssertJ Assertions

This rule finds AssertJ assertions that can be simplified and replaces them with equivalent dedicated assertions.

Read more

Use equals() on Primitive Objects

This rule replaces the infix operators "==" and "!=" with 'equals()' when used on primitive objects.

Read more

Use Factory Methods for Collections

Replaces the invocations of 'Collections.unmodifiableList/Set/Map' with the corresponding factory method 'List.of', 'Set.of' and 'Map.ofEntries' introduced in Java 9.

Read more

Use Files.newBufferedReader

Java 7 introduced the 'java.nio.file.Files' class that contains some convenience methods for operating on files. This rule makes use of 'Files.newBufferedReader' method for initializing 'BufferedReader' objects to read text files in an efficient non-blocking manner.

Read more

Use Files.newBufferedWriter

Java 7 introduced the 'java.nio.file.Files' class that contains some convenience methods for operating on files. This rule makes use of 'Files.newBufferedWriter' method for initializing 'BufferedWriter' objects to write text files in an efficient non-blocking manner.

Read more

Use Files.writeString

This rule makes use of the overloaded static methods 'java.nio.file.Files.writeString' which were introduced in Java 11. With the help of this methods it is possible to write text into a file in an efficient non-blocking manner by one single invocation.

Read more

Use Functional Interfaces

Converts anonymous inner classes to equivalent lambda expressions.

Read more

Use Guard Condition

Replaces the last statement of a method with a guard condition.

Read more

Use Java Records

Since Java 16, record classes are a new kind of class in the Java language. Record classes help to model plain data aggregates with less ceremony than normal classes. This rule replaces the declarations of local classes, inner classes, and package private root classes with record class declarations.

Read more

Use Local Variable Type Inference

This rule replaces the types on the local variable declarations with the reserved word var introduced in Java 10.

Read more

Use Multi Catch

Java 7 introduced the possibility to merge multiple catch clauses into a single multi-catch clause. Merging is only possible if the catch statements are identical.

Read more

Use Offset Based String Methods

This rule avoids creating intermediate 'String' instances by making use of the overloaded offset based methods in the String API.

Read more

Use Optional::filter

Extracts an Optional::filter from the consumer used in Optional::ifPresent. This simplifies the lambda expression used with Optional operations.

Read more

Use Optional::ifPresent

The usage of 'Optional.get' should be avoided in general because it can potentially throw a NoSuchElementException (it is likely to be deprecated in future releases). It is often the case that the invocation of 'Optional.get' is wrapped by a condition that uses 'Optional.isPresent'. Such cases can be replaced with the 'Optional.ifPresent(Consumer<? super T> consumer)'.

Read more

Use Optional::ifPresentOrElse

It is common to have an else-statement following an Optional.isPresent check. One of the extensions of the Optional API in Java 9 is Optional.ifPresentOrElse, which performs either a Consumer or a Runnable depending on the presence of the value. This rule replaces an 'isPresent' check followed by an else-statement with a single 'ifPresentOrElse' invocation.

Read more

Use Optional::map

Extracts an Optional::map from the consumer used in Optional::ifPresent. This makes complicated code blocks easier to read and reuse.

Read more

Use Parameterized JPA Query

This rule prevents SQL injections by parameterizing vulnerable concats of a JPQL query string. Thus, vulnerable fragments of JPQL query string can only be considered as data and not as code.

Read more

Use Parameterized LDAP Query

This rule prevents LDAP injections by parameterizing vulnerable concats of LDAP search filters. Thus, vulnerable fragments of an LDAP search filter can only be considered as data and not as code.

Read more

Use Pattern Matching for Instanceof

This rule replaces instanceof expressions by Pattern Matching for instanceof expressions introduced in Java 16.

Read more

Use Portable Newline

It is generally preferable better to use "%n", which will produce the platform-specific line separator.

Read more

Use Predefined Standard Charset

This rule replaces invocations of 'java.nio.charset.Charset.forName(String)' by references to the respective constants declared in 'java.nio.charset.StandardCharsets'.

Read more

Use SecureRandom

This rule prevents vulnerabilities due to a pseudo-random number generator (PRNGs) by replacing it by a cryptographically strong random number generator (RNG).

Read more

Use Stream::collect

Replaces 'Stream::forEach' with 'Stream::collect' if the argument of the 'forEach' statement is only used for adding elements to a list. This simplifies adding elements to a list.

Read more

Use Stream::filter

This rule transforms an if-Statement (without an else statement), which wraps the whole execution block of a 'Stream::forEach' method into a call to 'Stream::filter' with a lambda expression (Predicate) as parameter. This lambda is constructed using the expression from the if-Statement.

Read more

Use Stream::map

Extracts a block from the body of the consumer of the 'Stream::forEach' method and introduces 'Stream::map' instead. This makes complicated code blocks easier to read and reuse.

Read more

Use String Join

Replaces stream Collectors that are used for concatenating values of a collection with StringJoiner.

Read more

Use String Literals

Removes all class instantiations from 'String' if its parameter is empty or a 'String'.

Read more

Use StringBuilder::append

Replaces the infix operator + on String concatenation by 'StringBuilder::append'

Read more

Use StringUtils Methods

Replaces various 'String' methods with their null-safe counterparts from 'StringUtils'.

Read more

Use Switch Expression

In Java 14, the switch expressions turned into a standard feature. This rule replaces the traditional switch-case statements with switch-case expressions. Thus, avoiding the fall-through semantics of control flow and at the same time, removing some boilerplate code.

Read more

Use Ternary Operator

This rule replaces if-statements by equivalent constructs using the ternary operator in cases where such a replacement is reasonable.

Read more

Use Text Block

This rule replaces String concatenation expressions by Text Block String literals which have been introduced in Java 15.

Read more

Use Try-With-Resource

This rule adds the try-with-resources statement introduced in Java 7. Closing statements are removed as the construct takes care of that.

Read more