False positive in SonarJava: Conditionally executed blocks should be reachable (squid:S2583)

java
sonarlint

(Christoph Kaser) #1

I use SonarLint for Eclipse v4.0.0.201810170711.
With the following sample code (simplified from my actual code) I get a false positive with the message Change this condition so that it does not always evaluate to “false” (squid S2583).

public static void main(String[] args) {
	Random random = new Random();
	boolean flag1 = random.nextBoolean();
	boolean flag2 = false;
	int c = random.nextInt();
	while (true) {
		if (random.nextBoolean()) {
			if (flag2 && c == 5) { // here I get the linter warning 'Change this condition so that it does not always evaluate to "false"'
				flag1 = false;
			}
		} else {
			flag2 = true;
			if (!flag1 && !random.nextBoolean()) {
				return;
			}
		}
		c = random.nextInt();
	}
}

I do not see what causes SonarJava to think that flag2 is always false - it seems like it does not see the while loop around the condition.


(Alexandre Frigout) #2

Hello,

Even if you have a why looping around the condition, random.nextBoolean() will always be true and the flag2 will never be set to true as it is initialised with a false value.
Then maybe c will be 5 at some point but flag2 will remain false.

Alex.


(Christoph Kaser) #3

Hi Alexandre,

random.nextBoolean is randomly true or false - I don’t get why it should always be true. Am I missing something here?
(BTW, my original code does not contain randomBoolean, this was only used to reproduce the issue).

Best regards,
Christoph


(Alexandre Frigout) #4

Indeed Christoph, sorry for the confusion. I was thinking about nextInt(), sorry again for the misunderstanding. we will check your use case.