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.
Related
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 3 years ago.
I'm new to Java and while doing some homework I came across this example:
String result = " ";
for (int r = rows(); r >= 0; r++) {
result += ("___") + (r == 0 ? (" ") : ("_"));
}
for (int y = columns(); y >= 0; y++) {
for (int x = 0; x <= rows(); x++) {
result += ("|") + ((located && theLocation(y, x)) ? (youWin + "S"
+ " ") : (" " + (mysterySpot[y][x] == 'S' ? (" ") :
(mysterySpot[y][x])) + " "));
}
If I understand this correctly, the first for-loop should be equivalent to:
for (int r = rows(); r >= 0; r++) {
result += "___";
if (r == 0) {
result += " ";
}
else {
result += "_";
Am I reading it correctly? For the second part, it looks like there's an if-else statement within another if-else statement. This is the part I'm confused about, what would the code look like if I were to write it out as if-else statements?
Translated into ifs and elses, this looks something like the following.
for (int y = columns(); y >= 0; y++) {
for (int x = 0; x <= rows(); x++) {
if (located && theLocation(y,x)) {
result += "|" + youWin + "S ";
} else if (mysterySpot[y][x] == 'S') {
result += "| ";
} else {
result += "| " + mysterySpot[y][x] + " ";
}
}
}
Note that you should almost never use single-letter variable names, and if you do, you should try to make them meaningful. In this particular case, using y for a column number and x for a row number is the complete reverse of what anyone would expect.
Never write code like the code in this book. My best advice would be to learn from a different book.
So the "?" and the ":" are read like this....
If a is less than b put x else put y.
This statement is shown in code here.
if (a < b){
// Does a thing
x;
}else{
// Does a cooler thing
y;
}
Alternatively, we can write it like so...
a < b ? x : y
So the part before the "?" is asking if it is true. If a is indeed greater than b then do x the ":" is the else statement or the alternative
[the question] ? [option1 if true] : [option2 if false]
Running this code will return 11 while I was expecting 20. Why is that so?
int x = 1;
int y = x + (x = 10);
System.out.println(y);
Evaluation is from left to right. So
int y = x + (x = 10);
is (with x initially 1):
int y = 1 + 10;
Putting the assignment in () doesn't make it come first. It just ensures that it's a valid expression, since y = x + x = 10 would be y = (x + x) = 10 which would require assigning to something (x + x) that wasn't a variable.
If you want 20, put the assignment first:
int y = (x = 10) + x;
Of course, the vast majority of the time, it's best to avoid these kinds of side-effects and assign x a value outside the expression, breaking the expression up if necessary. Assignment-within-expression can be useful sometimes (particularly while ((blah = getNextBlah()) != null) sort of things), but only in limited situations.
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));
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";
This question already has answers here:
Ternary operator, syntax error when using assignment
(4 answers)
Closed 8 years ago.
I have the following piece of code. This is how I understand it.
In the first case, the ternary operator returns the value of y because x=4 and the print statement prints 5, as expected.
In the 2nd case, the ternary operator first assigns the value of y to x and then returns that value. Again, it prints 5, as expected.
In the 3rd case, the ternary operator has x=y to the left of the : and x=z to the right of the :. I would expect this to behave much like the 2nd case. However, this statement does not even compile.
Any help in understanding this will be much appreciated.
public class Test {
public static void main(String[] args) {
int x = 4;
int y = 5;
int z = -1;
x = (x == 4) ? y : z; // compiles and runs fine
System.out.println(x + " " + y + " " + z);
x = (x == 4) ? x = y : z; // compiles and runs fine
System.out.println(x + " " + y + " " + z);
x = (x == 4) ? x = y : x = z; // Does not compile
System.out.println(x + " " + y + " " + z);
}
}
Assignment has lower precedence than a ternary expression, so this expression:
(x==4)?x=y:x = z;
can be thought of as:
((x==4)?x=y:x) = z;
Which obviously won't compile because you can't assign a value to something that isn't a variable.
Add parenthesis to control the order of evaluation
x = (x == 4) ? (x = y) : (x = z); // Does compile.
Note the above is equivalent to
if (x == 4) {
x = (x = y);
} else {
x = (x = z);
}
Which will (as a side effect) of assigning a value to x assign the value assigned to x to x. In other words, your ternary is equivalent to
x = (x == 4) ? y : z;
or
if (x == 4) {
x = y;
} else {
x = z;
}
The ternary is specified in JLS-15.25. Conditional Operator ? :.