-3

I get different results, in the inner for loop for(j = i + 1...) and for(j = ++i...) in the code below. Please can anyone explain what happens in the for loop, during the initialization?

    public class DuplicateElementsInArray {

    public static void main(String[] args) {
            String[] names = {"Java", "Python", "C++", "JavaScript", "Java",  "Ruby", "C"};

            //This is a worst  Solution
            for(int i = 0; i < names.length; i++) {
                //for(int j = i++; j < names.length; j++) {
                //for(int j = ++i; j < names.length; j++) {
                for(int j = i + 1; j < names.length; j++) {
                    //System.out.println("j: " + j);
                    if(names[i].equals(names[j]))
                        System.out.println("duplicate element: " + names[i]);
                }
            }
        }
    }
Jim Mehta
  • 56
  • 2
  • 8
  • 1
    Possible duplicate of [What's the difference between i++ vs i=i+1 in an if statement?](https://stackoverflow.com/questions/30281042/whats-the-difference-between-i-vs-i-i1-in-an-if-statement) – GBlodgett Aug 31 '18 at 23:55
  • @GBlodgett no, it's not a duplicate of that. Note that the target of the assignment here is **`j`**, not **`i`** (i.e. a different variable on the left and right hand sides). – Andy Turner Sep 01 '18 at 06:46

2 Answers2

11

i + 1 leaves i's current value unchanged.

++i increments i, i.e. i's value is one greater after evaluating that expression.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
-1

The first method is simply setting j to i+1.

The second method is an example of pre incrementing, which returns the exact same value in this case.

Read this for more specific info and usage on incrementing a variable How do the post increment (i++) and pre increment (++i) operators work in Java?

faris
  • 692
  • 4
  • 18
  • Please explain why I am getting total different wrong result when I am using j = ++i? When I am using j = i + 1 I am getting correct result. – Jim Mehta Sep 01 '18 at 00:06
  • ++i changes the value of i while j = i + 1 does not. Thank you. – Jim Mehta Sep 01 '18 at 00:08
  • When you use j = ++i, the j value is set correctly however now you have also set i equal to itself + 1 which will skip every other iteration of the outer loop – faris Sep 01 '18 at 00:09