Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

This example will make pre -increment and post increment clearer In pre-increment the value is incremented before the operation , in post increment it is done before the operation.

        arr[0]=1;
        int var1=arr[0]++;
        System.out.println(var1);
        arr[0]=1;
        int var2=++arr[0];      
        System.out.println(var2);

Here I am doing an assignment, if I have a post increment , the increment occurs after the assignment. If i have a pre increment the increment occurs before the assignment

The output

1
2
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top