1

Consider:

int[] aryNums=new int[5];

for (int i=0; i<=5; i++)
{
    aryNums[i] = i++;
    System.out.println(aryNums[i]);
}

Why doesn't this give me the values in the array as 1, 2, 3, 4, 5? Instead, it gives an exception like 0,0 and error.

And also if I change

aryNums[i] = i++;  \to

aryNums[i] = i+1;

I get the value {1,2,3,4,5} in the array. What is the diff between i++ and i+1 here?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
adus
  • 79
  • 7

3 Answers3

7

++ is an operator that changes the value of 'i' by 1. It's a shorthand notation of i = i + 1.

i + 1 is an addition statement that returns what it normally would, but it doesn't change the value of i because i is not reassigned.

The reason you're getting errors is because i++ uses i before incrementing it, whereas if you wanted to use it after incrementing, you'd need to use ++i (increment, then use). Since i++ is also incrementing your counter, some values will be skipped.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • The third paragraph is a very important supplement to the first, as it explains the difference between pre- and post- increment operators. – nasukkin Jul 12 '16 at 00:29
3

a = i++; equals to a = i; i = i + 1;

int[] aryNums=new int[5]; //array index starts from 0, so last index is "4"

for (int i=0; i<=5; i++) // 0, 1, 2, 3, 4, "5" -> out of bounds
{
    aryNums[i]=i++; //i++ -> first put the i to arrNums[i], "then" increase i
    System.out.println(aryNums[i]);
}

Solutions:

  • Remove = from i <= 5
  • Change aryNums[i]=i++ to aryNums[i] = i + 1
Chalk
  • 66
  • 5
2

In the first one you are incrementing i inside the loop as well as part of the loop update. In the second, you are simply creating a new integer when you call i+1 without affecting the value stored at i.

The expression i++ updates the value stored at i, whereas the expression i+1 returns a new value without affecting the value stored at i.

Nick Larsen
  • 18,631
  • 6
  • 67
  • 96