Compilation error: j is already defined basically (java.lang.String [])

I am trying to compile the following code:

class Looping {
    public static void main(String ar[]) {
        long j;
        for (int i = 0, j = 3; i <= 10; i++, j++) {
            System.out.println(j);
        }
    }
}

I get the following compilation error:

j is already defined basically (java.lang.String [])

Error on line with loop for. How is this caused and how can I solve it?

+3
source share
4 answers

You actually declare two variables j in this way. Your solution is not to re-declare j in the loop, but to declare it once as long before the loop or once as an int in the initial state of the for loop (as you do). For example, you can try:

  long j = 3;
  for (int i = 0; i <= 10; i++, j++) {
     System.out.println(j);
  }
+6
source

When you write:

long j;
for(int i=0, j=3;i<=10;i++,j++)
{
    System.out.println(j);
}

This is basically equivalent to:

long j;
int i = 0, j = 3;
while (i <= 10)
{
    System.out.println(j);
    i++, j++;
}

, j int, . j long, . long j; long j = 3;, .

+5

:

class Looping {
    public static void main(String ar[]) {
      for(int i=0, j=3;i<=10;i++,j++) {
        System.out.println(j);
      }
    }
}

class Looping {
    public static void main(String ar[]) {
       long j=3;
       for(int i=0;i<=10;i++,j++) {
        System.out.println(j);
      }
    }
}

: (,) int i=0 , : Define an integer i with value 0 AND a integer J with value 3

0
int i = 0, j = 3; is the same thing as
int i = 0;
int j = 3;

, j. .

0

All Articles