3

Can anybody explain the difference between the following two programs? They look equivalent to me but they generate different outputs. What's the reason?

Program 1: Outputs incorrect value; i=1

public class Test1{
    public static void main(String[] args) {
        int[] values = new int[] { 2, 3, 5, 1 };

        int i = 0;
        for (Integer integer : values) {
            i =+ integer.intValue();
        } // for loop ends
        System.out.println("i=" + i);
    }
} 

Program 2: Outputs expected value; i=11"

public class Test2{
    public static void main(String[] args) {
        int[] values = new int[] { 2, 3, 5, 1 };

        int i = 0;
        for (Integer integer : values) {
            i = i + integer.intValue();
        } // for loop ends
        System.out.println("i=" + i);
    }
} 
Raedwald
  • 46,613
  • 43
  • 151
  • 237
Drona
  • 6,886
  • 1
  • 29
  • 35
  • 10
    Who is voting all the correct answers down? – Alex Gittemeier Jul 05 '13 at 06:56
  • 2
    Yes, it's really annoying :-/ – JREN Jul 05 '13 at 06:56
  • 1
    Yeah that's some serious bull. – William Morrison Jul 05 '13 at 06:57
  • Program 1: Outputs incorrect value; prints "i=1" Program 2: Outputs expected value; prints "i=1" so you expect something different from Program 1? – Tator Jul 05 '13 at 06:57
  • @MatthiasG: The second program outputs 11. May have been a typo on the OP's part, though. – Makoto Jul 05 '13 at 06:59
  • 4
    You could have debugged this with a simple `System.out.println` or some time with a debugger or `javap -c` to really see what's going on. – jason Jul 05 '13 at 07:05
  • 1
    @AlexGittemeier It is one of the more unpleasant SO strategies; voting down all the answers but your own – Richard Tingle Jul 05 '13 at 07:06
  • 3
    Whoever approved [this minor edit](http://stackoverflow.com/review/suggested-edits/2446872)? Dammit people, it's _too minor_ and introduced same fake edits to even get through the minimum edit length – Tobias Kienzler Jul 05 '13 at 07:13
  • @TobiasKienzler, I was always wondering which technique do they use. How do they make this space to space change? – sasha.sochka Jul 10 '13 at 22:51
  • @sasha.sochka probably copy/paste-replacing some tabs by spaces or vice versa, I didn't check which way around. Nonetheless, those trivial edits are strongly discouraged per meta.SO – Tobias Kienzler Jul 11 '13 at 06:15
  • @sasha.sochka Hm, according to [this post](http://meta.stackexchange.com/a/82873/146482) whitespace changes actually do not even count towards the edit length, so they shouldn't help those [minor-edit]ors (not to be confused with minor editors) to bypass the minimum length limitation... – Tobias Kienzler Jul 11 '13 at 08:04
  • @TobiasKienzler, hm, but when reviewing I see whitespace-only changes very often. – sasha.sochka Jul 11 '13 at 08:05
  • @sasha.sochka Weird. Maybe Jeff only thought about spaces, or this limit was withdrawn. But you should file this as a [meta-tag:bug] at meta.SO, especially if you can link to such a suggested edit – Tobias Kienzler Jul 11 '13 at 08:07
  • @TobiasKienzler, ok, I'll do it if I see it once more. – sasha.sochka Jul 11 '13 at 08:08
  • @sasha.sochka You can also check [your suggest-edit reviews history](http://stackoverflow.com/review/suggested-edits/history), if you didn't reject too many other edits recently... – Tobias Kienzler Jul 11 '13 at 08:10
  • 1
    @TobiasKienzler, yeah, now I found one of the examples with deleted and returned spaces (or tabs) but there was also another edit - some words became bold. And that counts because you add non-whitespace symbols in markdown. – sasha.sochka Jul 11 '13 at 08:56
  • @TobiasKienzler: That edit improves the post, doesn't it? I would have approved it if it had come to me. – Tom Anderson Aug 12 '13 at 19:27
  • @TomAnderson Granted, I shouldn't have rolled it back, but it really doesn't improve anything, except that one misplaced " – Tobias Kienzler Aug 13 '13 at 06:26

8 Answers8

17

Obviously, the major difference is within this line:

i =+ integer.intValue();

Perhaps it was intended to use i += instead of i =+ in the first program. In your version the first program just assigns a value every iteration so it's final result it the last value in array (which is 1). Your second program does what it's supposed to do - it adds all the elements in the array and it's result is 11.

sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
10

You try to add and assign but you use the wrong operator.

 for (Integer integer : values) {
     i =+ integer.intValue();
 } // for loop ends

This translates to i = (+ integer.intvalue())

Correct would be:

for (Integer integer : values) {
     i += integer.intValue();
 } // for loop ends
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
ssindelar
  • 2,833
  • 1
  • 17
  • 36
5

You are using =+ instead of +=

You are probably only getting the last value in your array printed out in one, and the sum in the other right?

That's because you're just overwritting the value repeatedly in one, and actually summing the values correctly in the other.

William Morrison
  • 10,953
  • 2
  • 31
  • 48
4

i =+ integer.intValue(); is a reassignment of the unary operation +integer.intValue(). You're overwriting i with every value in the array. The last one is the final result.

Makoto
  • 104,088
  • 27
  • 192
  • 230
4

Because you are using unary operator '+', which operates on the sign of integer and does not do addition.

So basically what happens is that the variable i will contain the last value int the values array.

EDIT:

Use of Unary plus operator in Java

When the array value is negative, suppose -1 In this case due to the good old maths rule for sign

  • (+)(+) = (+)
  • (+)(-) = (-)
  • (-)(+) = (-)
  • (-)(-) = (+)

So when you do i = (+ (-1)) = -1. The answer remains -1.

So if you keep last value of the array -1 or some other negative value, you will get the same value.

Community
  • 1
  • 1
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
3

is there anything wrong in class test1 code.It seems it should be i + =integer.intValue() instead of =+

witrus
  • 297
  • 1
  • 3
  • 13
3

Always write operator (+,-,| etc...) before = if LHS is to be involved without writing LHS explicitly like

+= ,-=, |=

or as even comparison operators <=, >= ....

Bharat Gaikwad
  • 530
  • 2
  • 5
  • 16
0
    int[] values = new int[] { 2, 3, 5, 1 };
    int i = 0;
    for (Integer integer : values) {
        i =+ integer.intValue();// here i's value  2,3,5 and finally 1. then your out put is 1.
    } // for loop ends
    System.out.println("i=" + i);

But your next case you are adding current value of i with int values in array. So obviously you will get the some of int value in array for i.

    int[] values = new int[] { 2, 3, 5, 1 };
    int i = 0;
    for (Integer integer : values) {
        i = i + integer.intValue();
    } // for loop ends
    System.out.println("i=" + i);
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • well a comment with "Try with debug, you will learn more by your self." would have been sufficient and your "answer" could be narrowed down to this – Marco Forberg Jul 05 '13 at 07:19