简体   繁体   中英

Unused local variable false positive

While using sonar lint version 6.3.0.39716, it reports the following variable as unused.

void read() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String s; // unused local variable 's'
        while ((s = reader.readLine()) != null) {
        }
}

But the variable s is used in the next line, should this be considered as unused as s is just assigned a value?
Edit- This is not considered an unused local variable.

void read() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String s; // ok
        s = reader.readLine();
        while (s != null) {
            s = reader.readLine();
        }
}

Here also s is just assigned value apart from being used in a boolean condition which it is used in the above case also.

For this code

void read() throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String s; // unused local variable 's'
    while ((s = reader.readLine()) != null) {
    }
}

The variable s can be removed completely without side effects as shown below.

void read() throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    while ((reader.readLine()) != null) {
    }
}

This is why these code analyzers will point out that the variable in question is never used. Setting a value in a variable is not enough to deem a variable as "used". In the second snippet, the variable s can't be removed because it is used to make a decision:

    while (s != null) {...}

Because of the line above, removing the variable will result in a compilation error. Therefore, the variable is an important part of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM