0

I'm curious about one little thing. code like this:

    String test = "test";
    char[] test2 = {'a', 'i'};
    int i=0;
    test += test2[i] + "";
    System.out.println(test);

Works as we suspect, the output is "testa", but what is happening when we change operand "+=" to "=+"? Now the output is "97" and it's ascii code for an a letter, it's simple, but what happened with the whole string test? Thanks from advice.

mlethys
  • 436
  • 9
  • 29
  • http://stackoverflow.com/questions/4221225/converting-chars-to-ints-in-java/4221265#4221265 – Scott Mar 31 '14 at 21:33

4 Answers4

11

The "=+" version:

test =+ test2[i] + "";

is parsed as

test = (+test2[i]) + "";

The unary plus converts the char ('a') to an integer (its ASCII code, 97), which is then converted to a string ("97") by the concatenation with an empty string. The end result is the string "97".

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
10

... += A means increase by A.
... =+ A means assign to positive A.

If you didn't notice the difference: a =+ b can be rewritten as: a = +b. There is no =+ operator. Where, in this case: +'a' gets converted to an int, because of the + operator.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
0

As demonstrated here: https://ideone.com/fCtLyB

int CONST = 75;
int method1 = 5;
int method2 = 5;
method1 += CONST; //Adds the value to method1 variable
method2 =+ CONST; //Sets method2 variable to CONST
System.out.println(method1 + ", " + method2 + ", " + CONST);

It's like doing a=-5 which is really a=0-5, except here it's a=+5 or a=0+5.

Shahar
  • 1,687
  • 2
  • 12
  • 18
0

+= is a common operator, you know what it means. On the other hand, when you put =+ you do an assigment and converting right side to integer, sto you get integer (97).

vanste25
  • 1,754
  • 14
  • 39