In: Computer Science
Explain why the value of the expression 2 + 3 + "test" is the string "5test" while the value of the expression "test" + 2 + 3 is the string "test23".
What is the value of "test" + 2 * 3 ?
Case 1
2 + 3 + "test" will give the string "5test"
When the + operator is used with String,it can concatenate the strings
Here first 2+3 (2 and 3 are integers) is evaluated which gives us 5, now 5+"test" needs to be executed
Since when we add a number and a string using a + operator it gives us a String
Therefor our output is "5test"
case 2
"test" + 2 + 3 will give the output as "test23"
Firstly "test" + 2 is evaluated, which returns test2 because a string + number is a string.
Now we have string "test2" which has to be added with 2
"test2" + 3 will return "test23" since adding a string with a number will return a string.
"test" + 2 * 3
The value of expression will be test6
Since the precedence of * is more than + operator,So first 2*3 is evaluated which gives us 6.
Now we have "test" + 6 which will return "test6",as we already know that on adding a String with number will always return a String