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
Related
The code is
String veggie = "eggplant";
int length = veggie.length();
char zeroeth = veggie.charAt(0);
char third = veggie.charAt(4);
String caps = veggie.toUpperCase();
System.out.println(veggie + " " + caps);
System.out.println(zeroeth + " " + third + " " + length);
System.out.println(zeroeth + third + length);
The output reads:
eggplant EGGPLANT
e 1 8
217
This doesn't make sense to me. Referencing a charAt outputs numbers instead of characters. I was expecting it to output the characters. What did I do wrong?
The second line should actually be:
e l 8
(note that the second value is a lower-case L, not a 1) which probably doesn't violate your expections. Although your variable is confusingly called third despite it being the fifth character in the string.
That just leaves the third line. The type of the expression
zeroeth + third + length
is int... you're performing an arithmetic addition. There's no implicit conversion to String involved, so instead, there's binary numeric promotion from each operand to int. It's effectively:
System.out.println((int) zeroeth + (int) third + (int) length);
It's summing the UTF-16 code units involved in 'e', 'l' and 8 (the length).
If you want string conversions to be involved, then you could use:
System.out.println(String.valueOf(zeroeth) + third + length);
Only the first addition needs to be a string concatenation... after that, it flows due to associativity. (i.e. x + y + z is (x + y) + z; if the type of x + y is String, then the second addition also becomes a string concatention.)
The compiler interprets all variables as values rather than a string.
Try System.out.println("" + zeroeth + third + length);
This line is doing integer arithmetic:
System.out.println(zeroeth + third + length);
In other words, it is adding the unicode values of each character (i.e. e is 101, l is 108, 8 is 8). To do String concatenation, you can add an empty String to the front:
System.out.println("" + zeroeth + third + length);
Since it is evaluated left-to-right, it will first do String concatenation (not addition). It will continue to do this for third and length. Adding "" at the end won't work, because addition will occur first.
You can use the method of the wrapper class Character to display the string values of char variables:
System.out.println(Character.toString(zeroeth) + Character.toString(third) + length);
This way, you always work with String values and there are no possibilities for the numeric values of the chars to be displayed or added and you don't need to concatenate with empty strings ("") to convert the char variables to String values.
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.
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
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
Given the following code snippet:
int i = 0;
int y = + ++i;
System.out.println(y);
The result is 1. Why is this a valid declaration? Can anyone explain what is =+?
int y = + ++i;
The first + in this line is simply the unary + operator (see: Assignment, Arithmetic, and Unary Operators). It does nothing. It's similar to the unary - operator. The line above is equivalent to:
int y = ++i;
which increments i and then assigns the new value of i to y.
Here + indicates the value is positive or not,i.e. unary operator and if you changes the value to - then the answer will be -1. i.e. int y = - ++i; will give -1.
The first plus after the equals sign is the sign of the value.
So it means it is a positive number.
int y = - ++i; would return -1
Java guarantees that it will be evaluated left-to-right. Specifically, ++ has higher precedence than +. So it first binds those, then it associates the addition operations left to right