Precedence in Strings in Java [duplicate] - java

This question already has answers here:
Java String Concatenation with + operator
(5 answers)
Closed 7 years ago.
what is the explanation of this precedence in strings in java?
public class PrecedenceInStrings {
public static void main(String[] args){
int x = 3;
int y = 5;
String s6 = x + y + "total";
String s7 = "total " + x + y;
String s8 = " " + x + y + "total";
System.out.println(s6 + "\n" + s7 + "\n" + s8);
}
}
output:
8total
total 35
35total

Java compiler processes operators + in your expressions left to right. When it comes to the first + in
x + y + "total"
it sees ints on both sides, so it performs an addition. When Java compiler processes the second +, it sees an int and a String, and interprets the operator as string concatenation.
In your second and third expressions the left-hand side of the + operator is a string, so all operators get interpreted as concatenations.
If you want to force a specific order of operations, use parentheses. For example, if you would like to get the total in your third example, parenthesize the addition, like this:
String s8 = " " + (x + y) + "total";

Related

How does string concatenation work when adding a string, a sum, and a product together? [duplicate]

This question already has answers here:
concatenating string and numbers Java
(7 answers)
Closed 6 months ago.
I came across this question, and I can vaguely tell it seems to be handling the number part as: A + B * C --> A * B + B * C
similarly, there are 3 more examples
1)
jshell> System.out.println("Sum is: " + 3 + 10*0.008);
Sum is: 30.08
jshell> System.out.println("Sum is: " + 33 + 10*0.008);
Sum is: 330.08
jshell> System.out.println("Sum is: " + 33 + 1000*0.8);
Sum is: 33800.0
According to String Concatenation, shouldn't it be:
is "Sum is: 3.8"
is "Sum is: 33.08"
is "Sum is: 33800"
but it's not.
I remember we can even easily turn numbers into String by simply doing "" + number; and if it was "" + number + number --> would be ""numbernumber, not ""2number
How are these results produced exactly?
This is a problem of associativity. + is left associative. a + b + c is ((a + b) + c).
Similarly, a + b + c * d is
((a + b) + (c * d))
not
(a + (b + (c * d)))
You can treat (c * d) as "one term" here because * has higher precedence than +.
Normally this doesn't make much difference if a, b, c are numbers, but in your case
("Sum is: " + 3) + (10 * 0.008)
The first + operates on a String and int, so it does string concatenation, which makes the first parenthesised expression a string. This makes the second + also do string concatenation.
On the other hand, if it were
("Sum is: " + (3 + (10 * 0.008)))
The second + operates on an int and a double, so it does numeric addition.

Quotes in Java Equations

Reading Java Headfirst found this example pls if someone can help me understand.
class Scratch {
public static void main(String[] args) {
int x = 0;
int y = 0;
while ( x < 2 ) {
y = y + x;
System.out.print(x + "" + y + " ");
x = x + 1;
}
}
}
I can't wrap my head around whats the function of quotes here in print statement the results vary a lot if you remove them.
The second one adds "Space" but the first somehow adds another integer?!
This is a common Java idiom to convert a number to a string:
int x = 1;
System.out.println(x + "" + x); // prints 11
In Java the + operator is overloaded to mean either addition or string concatenation, depending on the operand types.
What happens here is that x + "" is interpreted as a string concatenation rather than an addition.
x + "" -> 1 + "" -> "1"
"1" + x -> "1" + 1 -> "11"
Now there are some people who say that x + "" should be written as String.valueOf(x). They say that the latter is more efficient. In reality, it depends on how good the JIT compiler is at optimizing string concatenation expressions, and that varies with the Java version.

How is string concatenation working here? [duplicate]

This question already has answers here:
Java '+' operator between Arithmetic Add & String concatenation? [duplicate]
(3 answers)
Closed 3 years ago.
How does string concatenation work here?
As the return value is of type String here, so everything should be converted to string. But why is it printing "30Good3040morning" here, instead of "1020Good3040morning". Please Help.
class StringConcatinationWorking{
public static void main(String ...args){
String s1 = 10 + 20 + "Good" + 30 + 40 + "morning";
System.out.println(s1);
}
}
Remember that the + operator is left associative, so it "puts brackets" from left to right. String concatenation is only performed when at least one of the operands is a String.
Note that things like 10 and 30 are not Strings. They are int literals.
Your expression, after putting brackets, becomes:
(((((10 + 20) + "Good") + 30) + 40) + "morning")
If we evaluate step by step, starting from the innermost bracket, we get:
((((30 + "Good") + 30) + 40) + "morning") // 10 + 20
((("30Good" + 30) + 40) + "morning") // 30 + "Good"
(("30Good30" + 40) + "morning") // "30Good" + 30
("30Good3040" + "morning") // "30Good30" + 40
"30Good3040morning" // "30Good3040" + "morning"
Notice how we get a subexpression of 10 + 20, but not a subexpression of 30 + 40.
To get your expected result, just add a "" term before or after the 10 term, so that the brackets become:
((((((10 + "") + 20) + "Good") + 30) + 40) + "morning")
Rules of addition apply: Evaluate left to right, multiplication and division first.
10 + 20 + "Good" + 30 + 40 + "morning"
First 10 + 20 is seen, integer + integer. No String seen. Okay, make integer 30.
then a String is seen, integer + String. Change type to String "30" + "Good" = "30Good"
then all is seen with one String at least and converted to String.
To have everything as String, use a StringBuilder and put the values into that to get to a String.
Or add a "" in front of the concatenation list, to start out with a string to turn everything to String, with exception of possible multiplications or subtractions.
"" + 10 + 20 + "Good" + 30 + 40 + "morning"
Same rules of addition apply if you have a multiplication or division in there. Those precede addition or subtraction
10 + 20 + "Good" + 30 * 40 + "morning" == "30Good1200morning"
10 + 20 + "Good" + 30 / 40 + "morning" == "30Good0morning"
In cases like these I like to use a StringBuilder, that way you have fine grained control on what get's appended and you can just forget about the order of addition and multiplication rules that might apply by these mixed types, and the code becomes more readable and self documenting.
see it online
String newstr = new StringBuilder()
.append(10)
.append(20)
.append("Good")
.append(30)
.append(40)
.append("morning")
.toString();

How does this equal 105 instead of 15?

public class Review {
public static void main(String[] args) {
int x = 10, y = 5;
System.out.println(" " + x + y); // string + x + y
}
}
How does this equal 105 rather then 15?
What makes it different from the below code?
public class Review {
public static void main(String[] args) {
int x = 10, y = 5;
System.out.println(x + y); //Only x + y
}
}
" " + x + y means " " + x then + y
so the first code that you write we can divide into 2 steps:
1. " " + x => " " + 10 => "10"
2. "10" + y => "10" + 5 => "105"
But the second is just a number + number, so we get the number result.
I'm not a native English speaker, and I'm learning, sorry about my bad English, And I hope this is helpful.
The first answer the type is String because of the " " and you are using string concatenation by using the +
With the second one, the + is not being used to concatenate with a String.
When you mix a primitive data type with a String in System.out.println(), the Java compiler assumes that you want every data type to be converted to a String object. Adding brackets around your primitive data types allows you to calculate first before conversion as Jim Garrison suggested: System.out.println(" " + (x + y));

+ operator and strings

I'm just starting out in AP Comp sci in high school and I stumbled across a question regarding the + operator in strings
Why does
System.out.println ("number" + 6 + 4 * 5)
result in number620
whereas
String s = "crunch";
int a = 3, b = 1;
System.out.print(s + a + b);
System.out.print(b + a + s);
result in crunch314crunch?
Thanks
Depends on It's precedence order
When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition (+).
If you want to do any Math into System.out.println, wrap it with braces, because Java sees String at 1st place.
Try System.out.println ("number" + (6 + 4 * 5)).
For 2nd example use: System.out.print(s + (a + b));
in this case you have sum of a and b.
but in System.out.print(b + a + s); b and a stay at the 1st place. Compiler does a+b 1st and after add String, you don't need braces
"*" has a higher operator precedence than "+", this means the expression "4 * 5" is calculated before the String concatenation happens.
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
It has something to do with the operator precedence:
First, 4 * 5 = 20
Second, "number" is concatenated with 6, which is further concatenated with 20.
On your first example, since you used a multiplicative operator, 4 is being multiplied to 5 before concatenated to other string.
For the second example, you started with 2 integer before the String which will be calculated first before concatenated to a String.
Why does System.out.println ("number" + 6 + 4 * 5) result in number620
Because, * has higher precedence than +, so the result is number620.
String s = "crunch"; int a = 3, b = 1; System.out.print(s + a + b);
System.out.println(b + a + s); result in crunch314crunch?
Here, + is used as operator overloading not as binary operation. So, '+' do concat operation, not sum operation. So, the result is crunch314crunch.
It's about two things:
operator precedence
string concatenation vs addition
The + has the following rules:
int + int => int
int + string => String
String + int => String
String + String => String
That is, as soon as a String is involved, + means concatenation.
Operators with the same precedence are evaluated left to right. Therefore
String + int + int => String + int => String
but
int + int + String => int + String => String
The first case uses concatenation only, whereas the second uses addition in the first step.
In your first example, * has higher precedence than +, so the multiplication is performed first.
String + int * int => String + int => String
It's all about operator precedence and their associativity.
Your first example: "number" + 6 + 4 * 5
Acc. to operator precedence * is calculated first, so it becomes "number" + 6 + 20
Now, Associativity for + is Left -> Right (L->R), so + becomes a concatenation operator cause it is used with String, so the expression becomes "number6" + 20, and then "number620"
(Actually the int are converted to String before concatenation)
Similarly, your 2nd example:
Only + operator and start execution from L->R
"crunch" + 3 + 1 = "crunch3" + 1 = "crunch31"
1 + 3 + "crunch" = 4 + "crunch" = "4crunch"
According to your question and answer
explanation is
1.
A)System.out.println ("number" + 6 + 4 * 5);
B)System.out.println ("number6" + 4 * 5);
C)System.out.println ("number6" + 20);
D)System.out.println ("number620");
And it prints output like
number620
And Second one is
2.
A)System.out.print("crunch" + 3 + 1);
System.out.print(1 + 3 + "crunch");
B)System.out.print("crunch3" + 1);
System.out.print(4 + "crunch");
C)System.out.print("crunch31");
System.out.print("4crunch");
And it prints output with in a line, why because you have used print() statement
crunch314crunch

Categories

Resources