Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - dead code in for loop

I'm getting a dead code warning in a for loop at i++. Why do I get that, and how do I solve this problem?

public static boolean Method(int p) {
    for(int i = 2; i < p; i++) {  // here is the problem, at i++
        if(p % i == 0);         
            return false;
    }
    return true;    
}
like image 753
user1926550 Avatar asked Dec 24 '12 11:12

user1926550


People also ask

How do you fix a dead code in a loop in Java?

Solution 1 First thing you need to do is move the length test outside of the loop. If only letters and numbers are valid it would be easier to just test to see if each of the characters in the pass string is alphabetic or numeric using the isLetterOrDigit function.

Why do I get dead code in Java?

What is dead Code. The unreachable code in method 2 is called “Dead code“. This is purely Eclipse compiler reported error, and if you will compile above class with “javac“, Java inbuilt compiler will only complain for other two methods.

Why is my code dead code?

Dead code is code that is never executed. This can be a method that's no longer called, a commented out block of code, or code appearing after a return statement that's unreachable. In any case, it often reflects functionality that no longer exists in the software and offers no value.

Can we use && in for loop in Java?

Yes you can use two condition in while using logical &&, || . As in above statement two conditions are being checked that is while loop will run either when strength is less than 100 or ht should be greater than 10. We can also use and (&&) as per the situation.


2 Answers

You always exit the loop immediately, hence i never gets incremented.

    if(p % i == 0);         
        return false;

should be

    if(p % i == 0)       
        return false;

In the first version you have an empty clause following the if statement (due to the first semi-colon). Consequently the return false always executes. You exit the method, and the i++ never executes.

like image 169
Brian Agnew Avatar answered Nov 11 '22 08:11

Brian Agnew


Remove the semicolon after your if statement.

like image 23
fge Avatar answered Nov 11 '22 10:11

fge