SonarSource Rules
  • Products

    In-IDE

    Code Quality and Security in your IDE with SonarQube Ide

    IDE extension that lets you fix coding issues before they exist!

    Discover SonarQube for IDE

    SaaS

    Code Quality and Security in the cloud with SonarQube Cloud

    Setup is effortless and analysis is automatic for most languages

    Discover SonarQube Cloud

    Self-Hosted

    Code Quality and Security Self-Hosted with SonarQube Server

    Fast, accurate analysis; enterprise scalability

    Discover SonarQube Server
  • SecretsSecrets
  • ABAPABAP
  • AnsibleAnsible
  • ApexApex
  • AzureResourceManagerAzureResourceManager
  • CC
  • C#C#
  • C++C++
  • CloudFormationCloudFormation
  • COBOLCOBOL
  • CSSCSS
  • DartDart
  • DockerDocker
  • FlexFlex
  • GitHub ActionsGitHub Actions
  • GoGo
  • HTMLHTML
  • JavaJava
  • JavaScriptJavaScript
  • JSONJSON
  • JCLJCL
  • KotlinKotlin
  • KubernetesKubernetes
  • Objective CObjective C
  • PHPPHP
  • PL/IPL/I
  • PL/SQLPL/SQL
  • PythonPython
  • RPGRPG
  • RubyRuby
  • RustRust
  • ScalaScala
  • ShellShell
  • SwiftSwift
  • TerraformTerraform
  • TextText
  • TypeScriptTypeScript
  • T-SQLT-SQL
  • VB.NETVB.NET
  • VB6VB6
  • XMLXML
  • YAMLYAML
Java

Java static code analysis

Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your JAVA code

  • All rules 733
  • Vulnerability60
  • Bug175
  • Security Hotspot40
  • Code Smell458

  • Quick Fix 65
Filtered: 35 rules found
performance
    Impact
      Clean code attribute
        1. Hash-based collections with known capacity should be initialized with the proper related static method.

           Code Smell
        2. "String#replace" should be preferred to "String#replaceAll"

           Code Smell
        3. "ThreadLocal" variables should be cleaned up when no longer used

           Bug
        4. "read(byte[],int,int)" should be overridden

           Code Smell
        5. String offset-based methods should be preferred for finding substrings from offsets

           Code Smell
        6. "write(byte[],int,int)" should be overridden

           Code Smell
        7. Functional Interfaces should be as specialised as possible

           Code Smell
        8. Regex patterns should not be created needlessly

           Code Smell
        9. Collection contents should be used

           Code Smell
        10. Java 8's "Files.exists" should not be used

           Code Smell
        11. "Arrays.stream" should be used for primitive arrays

           Code Smell
        12. Factory method injection should be used in "@Configuration" classes

           Code Smell
        13. "StringBuilder" data should be used

           Code Smell
        14. Multiple loops over the same set should be combined

           Code Smell
        15. ".isEmpty" should be used to test for the emptiness of StringBuffers/Builders

           Code Smell
        16. Arguments to "append" should not be concatenated

           Code Smell
        17. "entrySet()" should be iterated when both the key and value are needed

           Code Smell
        18. "DateUtils.truncate" from Apache Commons Lang library should not be used

           Code Smell
        19. Inner classes which do not reference their owning classes should be "static"

           Code Smell
        20. "Preconditions" and logging arguments should not require evaluation

           Code Smell
        21. "deleteOnExit" should not be used

           Code Smell
        22. "wait(...)" should be used instead of "Thread.sleep(...)" when a lock is held

           Bug
        23. Collection methods with O(n) performance should be used carefully

           Code Smell
        24. "ResultSet.isLast()" should not be used

           Code Smell
        25. Methods of "Random" that return floating point values should not be used in random integer generation

           Code Smell
        26. Objects should not be created only to invoke "getClass"

           Code Smell
        27. Parsing should be used to convert "Strings" to primitives

           Code Smell
        28. Constructors should not be used to instantiate "String", "BigInteger", "BigDecimal" and primitive-wrapper classes

           Code Smell
        29. "URL.hashCode" and "URL.equals" should be avoided

           Code Smell
        30. Strings should not be concatenated using '+' in a loop

           Code Smell
        31. Sets with elements that are enum values should be replaced with EnumSet

           Code Smell
        32. Maps with keys that are enum values should use the EnumMap implementation

           Code Smell
        33. Primitive wrappers should not be instantiated only for "toString" or "compareTo" calls

           Code Smell
        34. Case insensitive string comparisons should be made without intermediate upper or lower casing

           Code Smell
        35. Synchronized classes "Vector", "Hashtable", "Stack" and "StringBuffer" should not be used

           Code Smell

        "Preconditions" and logging arguments should not require evaluation

        intentionality - efficient
        maintainability
        Code Smell
        • performance

        Why is this an issue?

        Some method calls can effectively be "no-ops", meaning that the invoked method does nothing, based on the application’s configuration (eg: debug logs in production). However, even if the method effectively does nothing, its arguments may still need to evaluated before the method is called.

        Passing message arguments that require further evaluation into a Guava com.google.common.base.Preconditions check can result in a performance penalty. That is because whether or not they’re needed, each argument must be resolved before the method is actually called.

        Similarly, passing concatenated strings into a logging method can also incur a needless performance hit because the concatenation will be performed every time the method is called, whether or not the log level is low enough to show the message.

        Instead, you should structure your code to pass static or pre-computed values into Preconditions conditions check and logging calls.

        Specifically, the built-in string formatting should be used instead of string concatenation, and if the message is the result of a method call, then Preconditions should be skipped altogether, and the relevant exception should be conditionally thrown instead.

        Noncompliant code example

        logger.log(Level.DEBUG, "Something went wrong: " + message);  // Noncompliant; string concatenation performed even when log level too high to show DEBUG messages
        
        logger.fine("An exception occurred with message: " + message); // Noncompliant
        
        LOG.error("Unable to open file " + csvPath, e);  // Noncompliant
        
        Preconditions.checkState(a > 0, "Arg must be positive, but got " + a);  // Noncompliant. String concatenation performed even when a > 0
        
        Preconditions.checkState(condition, formatMessage());  // Noncompliant. formatMessage() invoked regardless of condition
        
        Preconditions.checkState(condition, "message: %s", formatMessage());  // Noncompliant
        

        Compliant solution

        logger.log(Level.DEBUG, "Something went wrong: {0} ", message);  // String formatting only applied if needed
        logger.log(Level.SEVERE, () -> "Something went wrong: " + message); // since Java 8, we can use Supplier , which will be evaluated lazily
        
        logger.fine("An exception occurred with message: {}", message);  // SLF4J, Log4j
        
        LOG.error("Unable to open file {0}", csvPath, e);
        
        if (LOG.isDebugEnabled()) {
          LOG.debug("Unable to open file " + csvPath, e);  // this is compliant, because it will not evaluate if log level is above debug.
        }
        
        Preconditions.checkState(arg > 0, "Arg must be positive, but got %d", a);  // String formatting only applied if needed
        
        if (!condition) {
          throw new IllegalStateException(formatMessage());  // formatMessage() only invoked conditionally
        }
        
        if (!condition) {
          throw new IllegalStateException("message: " + formatMessage());
        }
        

        Exceptions

        catch blocks are ignored, because the performance penalty is unimportant on exceptional paths (catch block should not be a part of standard program flow). Getters are ignored as well as methods called on annotations which can be considered as getters. This rule accounts for explicit test-level testing with SLF4J methods isXXXEnabled and ignores the bodies of such if statements.

          Available In:
        • SonarQube IdeCatch issues on the fly,
          in your IDE
        • SonarQube CloudDetect issues in your GitHub, Azure DevOps Services, Bitbucket Cloud, GitLab repositories
        • SonarQube Community BuildAnalyze code in your
          on-premise CI
          Available Since
          9.1
        • SonarQube ServerAnalyze code in your
          on-premise CI
          Developer Edition
          Available Since
          9.1

        © 2008-2025 SonarSource SA. All rights reserved.

        Privacy Policy | Cookie Policy | Terms of Use