-1

While coding with eclipse, the code i++ is shown as a dead code. What does that mean? Why is it being a dead code?

public class ScoreCalculator{
public static void main(String[] args) {

        int ScoreCard[] = {70,102,198, 60};
        String PlayersList[] = {"Mukesh","Suresh","Shardul","Nandan"};
        System.out.println(DisplayScore(ScoreCard, PlayersList));

    }

    public static String DisplayScore(int[] Scores, String[] Players){

        for( int i=0; i <= 3; i++){

            if(Scores[i]>100 && Scores[i]<=200){

                System.out.println("\n******Players who moved to next level******");
                return Players[i] + "\n";
            }
            else
            {
                System.out.println("\n******Players in Danger Level******");
                return Players[i] + "\n";
            }

        }
        return "\n";
    }
}
Monisha Mohan
  • 23
  • 1
  • 2

2 Answers2

3

In all possible flows you exit the loop before performing that i++. There are three different possible flows:

  1. You don't enter the loop (just theoretical - in your case you enter).
  2. You enter and the condition is true - immediate return in if block.
  3. You enter and the condition is false - immediate return in else block.

In all cases, you don't finish the single loop, so the code which is evaluated after each iteration, isn't reachable.

And the for loop works as the following:

for (A; B; C)
    ^^ - executes before the loop starts (before first iteration
        ^^ - is evaluated before each iteration
           ^^ is evaluated after each full iteration, so is executed in case the loop executes
              at least once

Personally, I'm really impressed that the IDE has spotted it.

xenteros
  • 15,586
  • 12
  • 56
  • 91
0

The first iteration of a loop will return a value, breaking from the method. Thus, increment never happens.

This loop is equivalent to it's first iteration:

if(Scores[0]>100 && Scores[0]<=200){
    System.out.println("\n******Players who moved to next level******");
} else {
    System.out.println("\n******Players in Danger Level******");
}
return Players[0] + "\n";
default locale
  • 13,035
  • 13
  • 56
  • 62