Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array[i]++ vs ++array[i]

I have an array of ints:

private int array[];

If I also have a method called add, then what's the difference between the following:

public void add(int value) {
   array[value]++; VS ++array[value];
}

p.s. on a separate note, what's the difference between int array[] vs int[] array ? Thanks

like image 870
atoregozh Avatar asked Mar 12 '26 09:03

atoregozh


1 Answers

what's the difference between int array[] vs int[] array ?

There is none. It's just java convetion to create arrays like int[] array, it's more clear.

If I also have a method called add, then what's the difference between the following:

   public void add(int value) {
       array[value]++; VS ++array[value];
    }

In this code, there is not any difference. But the difference in general is:

int x = 5, y = 5;

System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6

System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6

//EDIT

As Vince Emigh mentioned in comments below, this should be in answer too ...

As you know, ++ increments the number by 1. If you call it after the variable, your program will increment the number, and if needed imediately (like when you increment inside the println params), returns what the value was BEFORE incrementing (resulting in your 5). Adding it before your var will result in your program increasing the value right away, and returns the incremented value. If you dont use the variable imediately, like you do when youre printing it out, then it really doesnt matter, since they both increment.

like image 100
Matej Špilár Avatar answered Mar 13 '26 23:03

Matej Špilár



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!