I wonder why first code output is 000 while the second one is 123
first one:
int z=0;
while(z<4)
{
z=z++;
System.out.print(z);
}
second one :
int z=0;
int x=0;
while(z<5)
{
x=z++;
System.out.print(x);
}
what is the different between these two codes , why the first block do not increase the value of the z ?
== operator is a type of Relational Operator in Java used to check for relations of equality.
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.
Remember this, Java evaluates your expressions right to left (just like C and C++),
So if your code reads
z = z++
then if z is 0 before this line is executed, what happens is:
z++
is evaluated as an expression, returning the value 0z
is incremented because of the ++ operator, and it has the value 1.z
on the left is assigned a value z = (value returned by z++)
z++
was 0, z
is reset to 0.The important thing to note is that the result of the assignment inherent in z++
is evaluated before the z
variable on the left is updated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With