understanding the java string with add operator -


i trying understand how compiler views following print statements. simple yet bit intriguing.

this prints added value. convincing enough.

system.out.println(1+2); //output: 3

the output following looks convincing well:

system.out.println(1+2+"3");//output: 33

my question (based on behavior above) here.

system.out.println("1"+2+3);//should 15 right? no. 123.

i tried few other such statements along same lines. able see 1 2 clear behaviors.

  • if integers @ front, without quotes, added , subsequent integers appended suffix added values front.

  • if statement starts string, under quotes, other subsequent elements appended suffix.

is somewhere in java api docs? or obvious string or add operator behavior not seeing. of valuable insights appreciated.

here code snippet:

public static void main(string[] args) {     system.out.println(1+2);     system.out.println(1+2+"3");     system.out.println("1"+2+3);      system.out.println("1"+2+"3");     system.out.println("1"+2); } //   console output: //      3 //      33 //      123 //      123 //      12 

i guess java specification explains best:

the + operator syntactically left-associative, no matter whether determined type analysis represent string concatenation or numeric addition. in cases care required desired result. example, expression:

a + b + c

is regarded meaning:

(a + b) + c

so, if a string, concatenates b. result of string type, hence continues concatenate c.


Popular posts from this blog