1

I am try to execute one simple for loop with iteration done by method. Its return value is not assigned

    public class DefaultC {

    public static void main(String[] args) {
        int i = 1;
        for(i= 10;i<=50; i=method(i)){
            System.out.println(i);
        }
    }

    static int method(int i){
        return i++;
    }
}
karthick
  • 31
  • 6

4 Answers4

5

++i increments and then returns i.

i++ returns i and then increments it.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
marco
  • 671
  • 6
  • 22
3
static int method(int i){
        return i++;
    }

This method is doing post-increment, which means it will return the value of i as it is which is being passed as the method argument, after that it increments the value of i which is now not useful at all since the scope of the variable i is only up to this method.

Try doing pre-increment instead.

return ++i;

EDIT: As per OP's comment

@Prashant by i++ it works, but why i = method(i) cant?

for(i= 10;i<=50; i++){ <-- Here post increment happens 
  System.out.println(i); <-- At this point value is already being incremented so you can utilize it.
}

Where as

for(i= 10;i<=50; i=method(i)){ <-- Here post increment happens inside method and the value it returns is still `10` not `11` 
      System.out.println(i); <-- At this point value is same as the previous loop
    }
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
1

The reason i++ works but increment(i) doesn't is because of the difference in the variable you are incrementing.

  • i++ is incrementing a local variable, so you see the changes to its value;
  • increment(i) is copying i to a new variable, which happens also to be named i, and increments that, and after taking its value for the return statement.

    The variable local to the loop is left unchanged by the ++, just as int j = i; j++; doesn't change the value of i.

In Java, method parameters​ are always passed by value.

But it is also important to note that even if Java did pass method parameters by reference, there is still a semantic difference between i++ and i = i++ (which is like the i = increment(i) case). The other answer have already covered why i = i++ doesn't work.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

i++ returns the value of i and later it do increment. What you need to do is, to use ++i;

Given Example shows how,

public class DefaultC {

public static void main(String[] args) {
    int i = 1;
    for(i= 10;i<=50; i=method(i)){
        System.out.println(i);
    }
}

 static int method(int i){
    return ++i;
 }
}

Here ++i will do increment first and returns later

Vigneshwaran
  • 387
  • 1
  • 2
  • 14