This question already has answers here:
What is the precedence of the + (plus) operator in Java?
(4 answers)
Closed 9 years ago.
Why do i get 10 2030 as the out put? I cant figure out why it doesnt output it as 10 50 ?
public class Testing1 {
public static void main (String args[]){
int num1=10,num2=20,num3=30;
System.out.println(num1+" "+num2+num3);
}
}
Operator precedence
System.out.println(num1+" "+(num2+num3));
While evaluation expressions,
Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence.When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from **left to right**; assignment operators are evaluated right to left.
System.out.println(num1+" "+num2+num3);
--------------------10-----------------num1
--------------------10 -----------------num1+" "
--------------------10 20-----------------num1+" "+num2
--------------------10 2030-----------------num1+" "+num2+num3
So, now you come to know that why you got that output.
Let see how the below statement gives you desired output:
System.out.println(num1+" "+(num2+num3));
Again based on the precedence, parentheses have the high precedence than +. So
(num2+num3)
evaluates first and the rest is same.
This does not work because the expression is interpreted from left to right taking into account operator precedence
Walk through it.
System.out.println(num1+" "+num2+num3);
First you take your num1 and concat a space onto it, you now have "10".
Second you concat num2 onto that string, you have "10 20".
Third you concat num3 onto that, you have "10 2030".
In fact, what you are doing is this:
String s = num1 + " ";
s += num2;
s += num3;
Use this:
System.out.println(num1 + " " +(num2 + num3));
If you're writing (num1 + " " + num2 + num3) Java will make a String from num1 add the String " " to it, add the String made from num2 to it and then add the String made from num3 to it.
The plus first gets evaluated as String concatenation and not the math + sign.
make it System.out.println(num1+" "+ (num2+num3));
When you introduce any string when performing operations, then the concatenation happens instead of actual operation.
So if you do System.out.println(num1+num2+ " " +num3);. You will get the output as 30 30 This is because your operations are performed before string concatenation is introduced in it. and hence the operation result is produced.
Keep in mind that all operands will be treated as string AFTER the first concatenation has occurred.
Before the concatenation, all operations will be evaluated.
The reason for that output is that the + in this context (num1 + " " happens first) is treated as a concatenation operator and the rest is then concatenated too. The other answers suggest parentheses to ensure the num2 and num3 are added first before the string evaluation.
Beacause Precedence wise i.e left to right:
num1+" " will be evaluated making a string of 10
num2+num3 will simply be appended to that string because of + operator in-between
num1+" " and num2+num3 forming 10 2030
try this way
System.out.println(num1+" "+(num2+num3));
For more about precedence and their associativity : http://www.cis.upenn.edu/~palsetia/java/precedenceTable.html
Related
If d1 and d2 are doubles with valid values, what is wrong with the following expression?
"answer = " + d1 < d2
The Java operators page shows that "additive" (+) operator are evaluated before "relational" (<) operators.
So the statement String + double < double will be seen like :
String + double < double == (String + double) < double --> String < double
The result will be String < double, that operation is not supported in java. So it will not compile.
Check the operator precedence array to find the exact order.
The closer to the top of the table an operator appears, the higher its precedence
Operators with higher precedence are evaluated before operators with relatively lower precedence
When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first :
All binary operators except for the assignment operators are evaluated from left to right;
assignment operators are evaluated right to left.
Example:
System.out.println("the investment doubled after "+year+" years.");
Can someone please explain why the int variable year is inside quotations and pluses?
Adding some spacing around the operators may make this statement clearer:
System.out.println("the investment doubled after " + year + " years.");
This statement prints the result of a concatination of three strings, achieved by the two + operators:
"the investment doubled after "
The implicit conversion of the int variable year to a string
" years."
It is like this. And + is used for String concatenation. In this year is converted into String from int implicitly.
"the investment doubled after " + year + " years."
^-------inside quotes-------^ ^-----^Inside quotes
Your variable year is not inside quotes, it's actually outside of quotes. It is in between of + sign because you are concatenating it.
Here you are using the public void println(String x); method. Which means the integer will concatenated to the string when you append the years to the string, that is the reason we are using the + operator.
Can a variable String accept integer value as well. Or can we concat integer with a string ?
Example:
public class TestString1 {
public static void main(String[] args) {
String str = "420";
str += 42;
System.out.print(str);
}
}
I was expecting compilation error over here because String was getting concatenated with an integer.
JLS documentation on String concatination operator(+)-
15.18.1 String Concatenation Operator +
If only one operand expression is of type String, then string
conversion is performed on the other operand to produce a string at
run time. The result is a reference to a String object (newly created,
unless the expression is a compile-time constant expression
(ยง15.28))that is the concatenation of the two operand strings. The
characters of the left-hand operand precede the characters of the
right-hand operand in the newly created string. If an operand of type
String is null, then the string "null" is used instead of that operand
That is why String + int does not produce any error. And it prints 42042
None of the other answers have explained what's actually being executed here.
Your code will be converted to something like:
String str = "420";
// str += 42;
StringBuilder sb = new StringBuilder(str);
sb.append(42); // which internally does something similar to String.valueOf()
str = sb.toString();
System.out.print(str);
Anything that is given in double quotes is String and + is for concatenating string with an any value(int value).
So the integer value will be appended to the string.
Here
String str = "420";
str += 42; // 42 will be appended to 420 and result will be 42042
Adding an int to a String appends the int to the string, thus converting the int into a string.
x=20 y=10
I am showing the Order of precedence below from Higher to Low:
B - Bracket
O - Power
DM - Division and Multiplication
AS - Addition and Substraction
This works from Left to Right if the Operators are of Same precedence
Now
System.out.println("printing: " + x + y);
"printing: " : Is a String"
"+" : Is the only overloaded operator in Java which will concatenate Number to String. As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.
So the output is 2010.
System.out.println("printing: " + x * y);
Here the
"*": Has higher precedence than +
So its x*y first then printing: +
So the output is 200
Do it like this if you want 200 as output in first case:
System.out.println("printing: "+ (x+y));
The Order of precedence of Bracket is higher to Addition.
I have the following example code:
int pay = 80;
int bonus = 65;
System.out.println(pay + bonus + " " + bonus + pay);
could someone please explain to me why I get the following output:
145 6580
Your code is interpreting the expression from left to right.
pay + bonus is interpreted as a mathematical function, so it adds the values to make 145. The + here is a plus operator.
The moment you concatenate the " ", Java converts the expression into a String. The + here is a concatenate operator.
Performing + pay converts pay to a String and concatenates it, because the expression is a String.
Also doing + bonus converts bonus to a String and concatenates it, also because of the previous expression.
Because, this is operator overloading issue. Here, First + is plus operator and last + is concat operator.
System.out.println(pay + bonus + " " + bonus + pay);
| |
(plus) (concat)
First it adds the two variables and at last it concatinates as string because the integers are converted into strings
For concatenation, imagine a and b are integers:
"" + a + b
This works because the + operator is overloaded if either operand is a String. It then converts the other operand to a string (if needed) and results in a new concatenated string. You could also invoke Integer.toString(a) + Integer.toString(b) for concatenation
bonus and pay are both ints, and therefore going to be combined into a single int result.
You need to insert an empty string between them.
first is plus operator and last is concat operator
The 1st pay and bonus in the println returns an integer. So it computes pay+bonus and returns it as an integer before printing it out.
However, after the "". The + operation then becomes a concatenation of strings and everything after that is returned as a concatenated string. Hence, ("" + bonus + pay) would be returned as "6580".
before " ",pay and bonus as integer, added result is 145.
after " ",bonus and pay as String,result is "6580"
As the others are saying the compiler is first adding the integer values and then printing the result, after " " the total value is changed to String type and after that + operator is functioning as a concat action. To not get that output, you can do this:
System.out.println(String.valueOf(pay) + String.valueOf(bonus) + " " + String.valueOf(bonus) + String.valueOf(pay));
what is surrounded by " " is referred to as a 'literal print' and gets printed exactly. The "+" sign is the concatenator operator and concatenates the string with the value that is stored in the variables. pay and bonus are declared as int, but is automatically converted to a String for the purpose of printing out.
You can print an arithmetic expression within a System.out.print statement. Use parentheses around the arithmetic expression to avoid unexpected problems.
System.out.println("ex" + 3 + 4); // becomes answer 34
System.out.println("ex" + (3 + 4)); // becomes answer 7
Why is the output different in these cases ?
int x=20,y=10;
System.out.println("printing: " + x + y); ==> printing: 2010
System.out.println("printing: " + x * y); ==> printing: 200
Why isn't the first output 30? Is it related to operator precedence ? Like first "printing" and x are concatenated and then this resulting string and y are concatenated ? Am I correct?
Its the BODMAS Rule
I am showing the Order of precedence below from Higher to Low:
B - Bracket
O - Power
DM - Division and Multiplication
AS - Addition and Substraction
This works from Left to Right if the Operators are of Same precedence
Now
System.out.println("printing: " + x + y);
"printing: " : Is a String"
"+" : Is the only overloaded operator in Java which will concatenate Number to String.
As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.
So the output is 2010.
System.out.println("printing: " + x * y);
Here the
"*": Has higher precedence than +
So its x*y first then printing: +
So the output is 200
Do it like this if you want 200 as output in first case:
System.out.println("printing: "+ (x+y));
The Order of precedence of Bracket is higher to Addition.
Basic math tells you that adding numbers is done each at a time.
So "printing: " + x is computed first. As it s a string + int the result is "printing: 20". Then you add y so "printing: 20" + y equals "printing: 2010".
In the second case, multiplying is prioritary. So first x * y is calculated and equals 200. Then "printing: " + 200 equals "printing: 200".
The results that you observe are certainly related to operator precedence and also the order of evaluation. In the absence of another rule, i.e. an operator of higher precedence, operators are evaluated in order from left to right.
In the first expression, all operators have the same precedence, because they're the same operator: +, and so the first operation is evaluated. Since it involves a String, it is String concatenation, and the result is a String; similarly for the following +.
In the second expression, one of the operators is *, which has higher precedence than +, and so is evaluated first. You get the result of the multiplication, an integer, and then the concatenation of a String and an int due to the +.
This will print 30:
System.out.println("printing: " + (x + y))
You need the parentheses to express the precedence you wish for.
It is for operator precedence
System.out.println("printing: " + x * y);
here * operator has more precedence than + so first it calculate x * y.
System.out.println("printing: " + x + y);
Where as here all are same operator and it will be treated as String concatenation operation as there is one string value is there.
if you involve bracket into this - System.out.println("printing: " + (x + y));
Then bracket ( operator has more precedence than + so first it will calculate (x + y) and will print 30
check detail operator precedence order
In the first printing line, the + operator is applied first between the String and the int and the result is a String which is again concatenated with another int resulting a String.
In the second line, the order of the operations is: first the multiplication and the resulted int concatenated to the String.
System.out.println("2*("+a"+"+b"*"+c")")
How to print this