3

I executed the below program

    int b = 0;
    b=+1;
    System.out.println(b);
    b=+1;
    System.out.println(b);
    b=+1;
    System.out.println(b);

and got output like 1 always. Why is the value of b incrementing in the first increment and why its not incrementing in the second and third incrementing operation?

robin
  • 1,893
  • 1
  • 18
  • 38

3 Answers3

4

Reverse the = and + symbols. Unary + isn't what you want.

b+=1;

or

b++;

or

++b;

Unary plus is b = (+1); or just b = 1.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
4

you are doing an assignment here with value +1

int literal allows leading + and - sign

you want

b += 1
jmj
  • 237,923
  • 42
  • 401
  • 438
2

b=+1 means b = +1 here + is unary operator and you are just giving sign to the digit (which indicates positive value) while you want add and assigment operator b += 1 means b = b +1 to increment the value.

akash
  • 22,664
  • 11
  • 59
  • 87