GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Container size compared to zero — CodeQL query help documentation

Container size compared to zero¶

ID: java/test-for-negative-container-size
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
   - logic
Query suites:
   - java-code-quality.qls
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

A map, collection, string or array will always have size of at least zero. Checking that an object of one of these types has size greater than or equal to zero will always be true, while checking that it has size less than zero will always be false.

Recommendation¶

For collections, maps and strings, if the intention was to check whether the object was empty, is it preferred to use the isEmpty() method. For arrays, check that the length field is greater than (not equal to) zero.

Example¶

The following example shows creation of a file guarded by comparison of a string length with zero. This can result in the attempted creation of a file with an empty name.

import java.io.File;

class ContainerSizeCmpZero
{
    private static File MakeFile(String filename) {
    if(filename != null && filename.length() >= 0) {
        return new File(filename);
    }
    return new File("default.name");
    }
}

In the following revised example, the check against zero has been replaced with a call to isEmpty(). This correctly guards against the attempted creation of a file with an empty name.

import java.io.File;

class ContainerSizeCmpZero
{
    private static File MakeFile(String filename) {
    if(filename != null && !filename.isEmpty()) {
        return new File(filename);
    }
    return new File("default.name");
    }
}

References¶

  • Java API Specification: Collection.isEmpty(), Map.isEmpty(), String.isEmpty().

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.