The precedence for the plus operator is listed only once in the java tutorial precedence table. However the following Java expressions:
String unexpected = "1 + 1 = " + 1 + 1;
String expected = "1 + 1 = " + (1 + 1);
System.out.println(unexpected);
System.out.println(expected);
result in this output:
1 + 1 = 11
1 + 1 = 2
Does this mean the plus operator has a higher precedence when used to concatenate Strings, or does it mean the plus operator's precedence is no different for Strings and Numbers, but that it is simply evaluated left to right?
It means it is evaluated left to right.
From jls SE8 15.18.1. String Concatenation Operator +: The + operator is syntactically left-associative, no matter whether it is determined by
type analysis to represent string concatenation or numeric addition. In some cases care is
required to get the desired result. For example, the expression:
a + b + c
is always regarded as meaning: (a + b) + c
Therefore the result of the expression: 1 + 2 + " fiddlers"
is: "3 fiddlers"
but the result of: "fiddlers " + 1 + 2
is: "fiddlers 12"
Another example: 1 + 1 + "" + 1 + 1
will result in : 211
That is why, for your context "1 + 1 = " + 1 + 1;
will result in string 1 + 1 = 11
But, "1 + 1 = " + (1 + 1); will result in 1 + 1 = 2
+ always flow from left to right
in your first example String unexpected = "1 + 1 = " + 1 + 1; , string comes first and then the int value so 1 is treated as string.
in your second example String expected = "1 + 1 = " + (1 + 1); , you are using () which is having higher precedence over + operator.(BODMAS)
consider another example:
String unexpected1 =1+1+ "1 + 1 = " ;
System.out.println(unexpected1);
output will be 21 + 1 =
here int value comes first so 1+1 =2 and then the string literal so 2 is concatenated with 1+1=
Using + in strings will trigger a concatenation rather than summation.
But when you use (1+1) and sum it to "1+1=" using a +, the expression inside the parentheses will be evaluated first then concatenated to the rest of the string. Evaluating the inside of the parentheses works independently from the String, thus 1 and 1 will be considered two integers being added to each other.
And when using same operators, everything is evaluated from left to right.
There is an order of evaluation for operators that you can find here
Related
I was just experimenting with the fusion of the strings in Java (I don't know what we call them so I'm saying fusion)
int sum = 11+13;
int sum2 = 12+4;
So then I started to print them with different fusion of strings like:
System.out.println( "Answer is " + sum + sum2 ); //Answer is 2416
System.out.println( "Answer is " + sum + ' ' + sum2 ); //Answer is 24 16
System.out.println( "Answer is " + (sum+sum2) ); //Answer is 40
System.out.println( "Answer is " + (sum + ' ' + sum2) ); //Answer is 24 16
It worked fine with the 1st, 2nd and 3rd statements. But in the 4, it's output was
Answer is 72
But why is it coming? I thought the output should be
Answer is 24 16
as first we are outputting the string "Answer is " and then we are outputting this- (sum + ' ' + sum2) and as there is a string between the sum and sum 2, they shall become a string too. But instead it's giving the output 72.
Also, I'm using IntelliJ to run this programm if it will help.
One last thing, this works perfectly fine if I replace the ' ' with " ", but why? It works fine with the 2nd statement.
Because ' ' in (sum + ' ' + sum2) is considered as a character code which is 32.
int b = ' ';
System.out.println( "Answer is " + b ); //Answer is 32
So, 24 + 32 + 16 = 72
Because ' '(space)is char, not String, and char is used in operations with int, often using ascii code, the ascii code of ' '(space) is 32, so 24 + 32 + 16 = 72. When you use System.out.println( "Answer is "+ (sum +" "+ sum2) ), you will get the answer "Answer is 24 16"
In addition to the already provided answers: The difference here is that when the subexpression x + ' ' is evaluated in the second case the x is of type String, while in the fourth case it is of type int. So in the second case the + means string concatenation, while in the fourth it is addition.
Parantheses + ASCII code gives the 72.
Parantheses makes the integers sum up. You're assuming that output should be 24 16 but within paranthese the values are not strings. sum and sum2 are int. So, all the values are added. As explained by others, space holds a value of 32. This ensures, that the output is 72.
Note: If you want to get 24 16, you'd have to use String.valueOf().
System.out.println("Answer is " + (String.valueOf(sum) + ' ' + String.valueOf(sum2)) );
Anything enclosed inside '' is considered as a character literal. The character literal space is dec 32.
On the other hand statement inside () is evaluated as an addition operation with values considered as 24 + 32 + 16, hence you get an answer as 72.
Similarly (sum + '!' + sum2) would have produced 73.
String s1 = "six" + 3 + 3;
String s2 = 3 + 3 + "six:";
System.out.println(s1);
System.out.print(s2);
Output :
six33
6six:
Why is 3+3 not added in the first one but is added in the second one?
The order of the operation is important
In the first one the concatenation works like so :
String s1 = "six" + 3 + 3;
"six3" + 3 // string plus int return string
"six33" // string plus int return string
In the second one :
String s2 = 3 + 3 + "six:";
6 + "six" // int plus int return int
"6six" // int plus string return string
For more details read documentation of Operators and 15.7. Evaluation Order
All binary operators except for the assignment operators are evaluated
from left to right; assignment operators are evaluated right to left.
In S1, the compiler reads (six) characters, then reads and reads. The numerical value of number 3 cannot be summed with text (six), as a character and added after x, then reads 3 and added after the first 3.
In s2 he reads 3 and then 3 can execute the process collected by the compiler and prints 6 directly and then reads (six) can not be collected will be printed after the number 6
Order is important. In second case firstly it does arithmetic operation and string concatenation so it results in 6six
This question already has answers here:
Java String Concatenation with + operator
(5 answers)
Closed 3 years ago.
Consider the below code snippet -
public class Student {
public static void main(String args[]) {
int a = 3;
int b = 4;
System.out.println(a + b +" ");
System.out.println(a + b +" "+ a+b);
System.out.println(""+ a+b);
}
}
The output for the above snippet is coming as -
7
7 34
34
It is clear from the output that if we use String at first in the print statement then the integers are concatenated. But, if we use integer at first then the values are added and displayed.
Can someone please explain why is this behavior?
I even tried to look at the implementation of println() method in PrintStream class but could not figure out.
Actually it's not println() implementation who's causing that, this is Java way to treat the + operator when dealing with Strings.
In fact the operation is treated from left to right so:
If the string comes before int (or any other type) in the operation String conversion is used and all the rest of the operands will be treated as strings, and it consists only of a String concatenation operation.
If int comes first in the operation it will be treated as int, thus addition operation is used.
That's why a + b +" " gives 7 because Stringis in the end of the operation, and for other expressions a + b +" "+ a+b or ""+ a+b, the variables a and b will be treated as strings if the come after a String in the expression.
For further details you can check String Concatenation Operator + in Java Specs.
It has nothing to do with the implementation of println. The value of the expression passed to println is evaluated before println is executed.
It is evaluated left to right. As long as both operands of + are numeric, addition will be performed. Once at least one of the operands is a String, String concatenation will be performed.
System.out.println(a + b + " ");
// int + int int + String
// addition, concatenation
System.out.println(a + b + " " + a + b);
// int + int int + String Str+Str Str+Str
// addition, concat, concat, concat
System.out.println("" + a + b);
// String+int String+int
// concat, concat
First case:
System.out.println(a + b +" ");
In this order, a + b will first be evaluated as a int sum, then converted to a string when adding the space (the second + here is for string concatenation).
Second case:
System.out.println(a + b +" "+ a+b);
Here the first part will be int sum operation then converted to a string as we add the space (the 2nd + is for string concatenation), the rest will be string concatenation as the left operand is already a string.
Third case:
System.out.println(""+ a+b);
Same as 2nd.
Notes:
In order to change this behavior, just add parenthesis to force the int sum before the string concatenations.
public class Test2 {
public static void main (String[] args){
System.out.println("3 + 6");
System.out.println(3 + 6);
System.out.println(3 + 6 + "buffer");
System.out.println("buffer" + 3 + 6);
System.out.println("buffer " + (3 + 6));
}
}
the output for
System.out.println(3 + 6 + "buffer");
is
9 buffer
and
the output for
System.out.println("buffer" + 3 + 6);
is
buffer 36
why the difference? and why
System.out.println(3 + 6);
output is
9
?
The arithmetic operator resolves from left to right. And when you do + With string it's append as a string.
System.out.println(3 + 6 + "buffer");
That becomes
System.out.println( 9 + "buffer");
And when you do
System.out.println("buffer" + 3 + 6);
that evaluates as
// "buffer3" + 6
// "buffer36"
and
System.out.println(3 + 6)
There is no string concatenation. So direct integer addition happend.
In case of
System.out.println("buffer " + (3 + 6));
You added parenthesis to 3+6. Due to the higher precedence that expression in parenthesis evaluates first. Hence that becomes
System.out.println("buffer " + 9);
The expressions passed to println are evaluated before being passed.
They are evaluated from left to right.
If the first (left) operand in the expression is a String, + performs String concatenation, so "buffer" + 3 + 6 becomes "buffer3" + 6 which becomes "buffer36".
If the first and second operands are numbers, + performs addition, so 3 + 6 + "buffer" becomes 9 + "buffer" which becomes "9buffer".
If some of the operands are surrounded by brackets, the operator between them is applied first, so "buffer " + (3 + 6) is equivalent to "buffer " + 9.
Expressions are evaluating left to right direction.
So System.out.println(3 + 6 + "buffer"); in this line firstly evaluating sum of integer numbers and System.out.println("buffer" + 3 + 6); here is the first type is string and evaluating type conversion according to string type to the right.
The expression you pass is first evaluated starting from left to right. Here in case of 3+6+"buffer" the first two parameters are integer so the + operator adds them and sum is 9 and when it gets the third parameter "buffer" which is a string, it converts the result to string and prints it. Hence you get the string "9buffer" as result.
However in the second case "buffer"+3+6 first parameter is string and second is integer so second param is converted to string first and then + operator concatenates them. Similar is the case when it reaches the third operator it does "buffer"+6 and again concatenates it and hence result becomes "buffer36".
if you are using + sign for String, the java compiler take it as concatenate and automatically call toString to other object.
So when you are trying to print 3+6+"stuff" it means int+int+contate to String so first it add two number and after that converts it to string and concate it with "stuff".
And if you call "stuff"+3+6 it will print stuff36
In the first one (3+6+"buffer") when the program is run java reads your program from left so it takes 3 and 6 as integer and their sum is 9 then it reads a string so it joins it with the string and result is "9buffer".
In the second one ("buffer"+3+6) it reads string first so it joins the other to with it
and result is buffer36.
In the third one (3+6) it takes them integers because no string is present before them
so it gives 9.
This question already has answers here:
Java: sum of two integers being printed as concatenation of the two
(10 answers)
Closed 7 years ago.
Why does the expression x+x not print the same result in the two places it appears?
String s = args[0];
System.out.println("Hello "+s);
int x = 40;
System.out.println(x);
System.out.println(x+x);
System.out.println(s+" "+x+x);
The result of this code is when I execute in cmd java EG1 kaan
Hello kaan
40
80
kaan4040
why is the last result of the print displaying kaan4040 and not kaan80?
Because of automatic conversion to String.
On this line you "start printing" an integer, so adding another integer to it will again produce integer that is then converted to String and printed out:
System.out.println(x + x); // integer + integer
However on this line you "start printing" a String, so all other values you add to it are at first converted to String and then concatenated together:
System.out.println(s + " " + x + x); // String + String + integer + integer
If you want the two integers to be added together before the concatenation is done, you need to put brackets around it to give it a higher priority:
System.out.println(s + " " + (x + x)); // String + String + integer
In your last print statement, you are doing a string concatenation instead of an arithmetic addition.
Change System.out.println(s+" "+x+x) to System.out.println(s+" "+(x+x)).
Make changes System.out.println(s+" "+x+x); to System.out.println(s+" "+(x+x)); Because it need to add the value and then string concatenation
Because java does some work with your code. When you do System.out.println(x+x);, it sees x+x as an expression with two ints and evaluates it (which is 80). When you do ""+x+x, it sees 3 String, and thus evaluates this expression as a String concatenation.
(btw, by it, I mean javac, and "sees", I mean, well "reads")
Or change print code to System.out.println(x +x+" " +s );
You are performing concatenation instead of addition
Whenever you append anything to string then it will result to string only. You have appended x+x to " " which will append 40 after name. You can use System.out.println(s+" "+(x+x)).
On the last print statement:
System.out.println(s+" "+x+x);
s is a string and is concatenated with " ", from left to right the expression formed by concatenation with s and " ", is then concatenated with x and then ( s + " " + x ) is concatenated with x, yielding kaan4040.
If the + operator is used with:
2 Strings, concatenation occurs
1 String and 1 int, concatenation occurs
2 ints, arithmetic addition
Consider the following scenario:
System.out.println(x + x + " " + "hello");
In this example 80Kaan is printed as arithmetic addition occurs between x and x, then the resulting value (80) is concatenated with the space and hello.
Read from left to right.
int x = 40;
System.out.println(x);
System.out.println(x + x);
System.out.println("" + x + x);
40
80
4040
40 is int 40
80 is int 40 + int 40 (Maths)
4040 is String 40 concat String 40 (because add "" String)
String s = args[0];
System.out.println("Hello "+s);
int x = 40;
System.out.println(x); //1st statement
System.out.println(x+x); //2nd statement
System.out.println(s+" "+x+x); //3rd statement
The first statement simply converts x into String
The second satatement added the numbers because there aren't strings, the compiler thinks of plus sign as addition of two numbers.
the third one sees that there is a string so the compiler thinks like:
print the value of s, add space(" "), add the value of x (convert x into string), add the value of x (convert x into string ).
Hence, Kaan4040.
If you want to print 80, you can do it in two ways:
int sum = x+x;
System.out.println(s+" "+sum); //more readable code
or
System.out.println(s+" "+ (x+x) ); //may confuse you
the compiler will think of x+x as integers since it doesn't find any string inside the parenthesis. I prefer the first one though. :)
why is the last result of the print displaying kaan4040 and not kaan80?
This is because this is how String behaves when used with the + symbol. and it can mean differently when used in a println method.
It means String concatenation when you use it with a String
The 5 even though being an integer will be implicitly converted to String.
E.g:
System.out.println("Hello" + 5); //Output: Hello5
It become mathematical operation:plus when used within a pair of brackets because the brackets will be operated first (add first), then convert to String.
The 1st + is concatenation, and 2nd + is add (Refer to codes below).
E.g:
System.out.println("Hello" + (5+7)); //Output: Hello12
If any one of the '+' operator operand is string, then java internally create 'StringBuilder' and append those operands to that builder. for example:
String s = "a" + 3 + "c";
it's like
String s = new StringBuilder("a").append(3).append("c").toString(); //java internally do this