Hey,
I have the following two lines of code:
result[i] = temp[i] + temp[i + 1] + " " + temp[i + 2];
i += 2;
I am wondering if this line of code would do the same:
result[i] = temp[i] + temp[i++] + " " + temp[i++];
Can I be sure, that EVERY VM would process the line from the left to the right?
Thanks,
Tobi
From Java language specification:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.
It should be
result[i] = temp[i] + temp[++i] + " " + temp[++i];
if I am not wrong, so that the indexes are computed after each incrementation.
Apart from that it should work.
Let's just try actually quoting the source.
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.
It looks like someone found a link to the spec as well.
No it's not the same. When you put the ++ after i it implies that it is postfix, i.e. i will first be used and THEN incremented.
So:
result[i] = temp[i] + temp[i++] + " " + temp[i++];
would be the same as the below if i = 1:
result[1] = temp[1] + temp[1] + " " + temp[2];
and after this statement i would be sitting with value of 3.
For it to be the same as:
result[i] = temp[i] + temp[i + 1] + " " + temp[i + 2];
You should use the prefix increment operator, i.e:
result[i] = temp[i] + temp[++i] + " " + temp[++i];
i++ will output the value and increment
++i will increment the value and output.
Related
Operator precedence of ++ and -- is higher than + and has associativity right to left. So I think output of x should be (++i+4 then 5+4) 9 and output of y should be (i+++5 then 5+5) 10. For both it print 11 as output.
class First {
public static void main(String[] args) {
int i = 5;
int x = ++i + --i;
int y = i++ + i--;
System.out.println("x="+x);
System.out.println("y="+y);
}
}
Let's translate this:
int i = 5;
int x = ++i + --i;
int y = i++ + i--;
System.out.println("x=" + x);
System.out.println("y=" + y);
Into (step by step):
int i = 5;
int x = ++i + --i;
// ^
// (i = i + 1) + --i
// (i = 5 + 1) + --i
// (i = 6) + --i
// ^
// 6 + (i = i - 1)
// 6 + (i = 6 - 1)
// 6 + (i = 5)
// 6 + 5
// x = 11
int y = i++ + i--;
// ^
// (i = 5) + i--
// 5 + i--
// i = i + 1 // post evaluation, after i was evaluated to 5, now i increments its value and it is 6
// 5 + (i = 6)
// 5 + 6
// y = 11
// i = i - 1 // post evaluation, after i was evaluated to 6, now i decrements its value and it is 5
System.out.println("x=" + x); // x=11
System.out.println("y=" + y); // y=11
Section 15.7 of the JLS is clear on this:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.
Whenever assignment operators and other binary operators are mixed in with increment or decrement operators, evaluating the expression is not intuitive, and one should never write such confusing code.
Even if the increment and decrement unary operators are right-to-left associative, the values of an expression are evaluated left-to-right.
int x = ++i + --i;
Here, ++i increments i to 6 and returns 6, then --i decrements i to 5 and returns 5, and the sum of 6 and 5 is 11.
int y = i++ + i--;
Here, i++ returns 5 and increments i to 6, then i-- returns 6 and decrements i to 5, and the sum of 5 and 6 is 11.
With these expressions, the right-to-left associativity does not figure into the order of operations, because associativity only controls which operations are executed first among operators of the same precedence. You have a + operator of lower precedence between them, so the associativity doesn't matter here.
Associativity dictates how operators with the same precedence are parsed.
For example, the Unary Minus (- ...) and Unary Bitwise NOT (~ ...) operators have the same precedence and have right-to-left associativity. Therefore:
int i = ~-1; // == 0
int j = -~1; // == 2
while practicing, I have accidentally written for loop as below
for (int i = 1; i <+ 100000; i++) {
System.out.println("Iam lazy thread" + i);
}
loop just worked ignoring the plus sign in the condition.
The Java Language Specification includes an unary + operator (ยง15.15.3) which can be used to explicitly express the sign of a numerical value as explained here.
So the expression
i <+ 100000
is parsed as
i < + 100000
It is not a compiler error because + symbol just denotes the positivity of any number later to it.
As same in the math ,
a = 5 and a = +5 are same. You wrote the + which is not necessary as 100000 is already positive. You see the functional difference when you write i < -100000;
It is same as writing
int k = +10000;
or
int k = -10000
"+" determines that 100000 is a positive number. You can try this one
int i = 0;
System.out.println("i <+ :" + (i <+ 10000));
System.out.println("i <- :" + (i <- 10000));
System.out.println(info + ": " + ++x);
is this statement equivalent to
x++;
System.out.println(info + ": " + x);
and
System.out.println(info + ": " + x++);
is equivalent to
System.out.println(info + ": " + x);
x++;
As JVM can only process one statement at a time, does it divides these statements like this?
Yes and yes.
++x will be executed before the containing statement, ie the value of x will be incremented before it's used.
x++ will be executed after the containing statement, ie the value will be used and then the variable x incremented.
To be clear: in both cases the value of variable x will be changed.
int i = 0;
int k = Integer.parseInt("12");
int j = k;
System.out.println(i+1 + " " + j+1);
Strangely the output received is
1 121
I can not figure out this basic difference. Please help me.
Use brackets as follows
System.out.println((i+1) + " " + (j+1));
From the docs
The + operator is syntactically left-associative, no matter whether it
is later determined by type analysis to represent string concatenation
or 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
Extending this to your scenario
i+1 + " " + j+1
it becomes
(((i + 1) + " ") + j)+1
Since i is an int so (i + 1) = 1 , simple addition
" " is a String hence ((i + 1) + " ") = 1 WITH SPACE (String concatenation)
Similarly when j and last 1 is added, its being added to a String hence String concatenation takes place, which justifies the output that you are getting.
See
JLS 15.18.1 String Concatenation Operator +
that is beacuse of " ".
whenever a String comes, java doesnt do any calculations after that and just append it as string.
So in your case, i+1 is computed to 1, but " " + j+1 has string in it. So, it just appended together to form 121
The reason you see this behavior is that the sequence of + operators is evaluated left-to-right. So it is evaluated as if parenthesized:
System.out.println((((i + 1) + " ") + j) + 1);
The first operator adds two int values and produces an int value. The next + adds an int to a String and produces a String. After that, everything is string concatenation. You can introduce your own parentheses to get the result you want.
int i = 0;
int k = Integer.parseInt("12");
int j = k;
System.out.println(i+1 + " " + (j+1));
basically when you put + " " + after this java just appends values as string.
and when you put (j+1) in brackets then its precedence gets higher and it is executes it first and perform sum operation.
When you use " " The expression after that gets evaluated as string.
Using brackets ( and ) around an expression can solve the problem in hand.
System.out.println(i+1 + " " + (j+1));
+ operator is overloaded for addition and String concatenation what you're doing is String concatenation and not addition.. Use brackets for performing addition.
parseint will basically return int (Look at Java API), and there is only one int type in Java. in this example you used " ", where java will treat it as string. in any operation make sure you dont mix up strings with calculations. Always use parenthesis to separate String from calculations.
It happens because the + operator has left associativity and has an overloaded function with strings, so when you have this
int i = 0;
int k = Integer.parseInt("12");
int j = k;
i+1 + " " + j+1
it first sums
i + 1 which gives 1 then it sums 1 + " ", which uses the overloading function of it to concatenate 1 and " " so it gives a string with the value of "1 ". After that it sums "1 " + j and since one of the operands is a string, it does the same behavior and so on.
Interger.parseInt (String str) is a wrapper class method which is used to convert String obj type to primitive data type (int). this are generally used in collection frame work for converting primitive data type to object and vice versa
I was solving some programming exercises in java. Everything was perfectly fine until my mind kind of froze a bit on the N Queens exercise.
Perhaps there is something wrong with the thing that is returned by s.get(x)? Since
s.showAll()
says that there is stuff in the stack, it is strange that
(s.get(x)==y)
is always false. You could try inserting:
for (int x=1; x<=boardSize; x++){
for (int y=1; y<=boardSize; y++){
System.out.println("(" + x + ", " + y + "): " + s.get(x) + " == " + y + " -> " + (s.get(x) == y));
}
}
at the end, to check whether the results of s.get(x) agrees with s.showAll().
The rest of the code here looks fine.