Weird Java Syntax - java

I was doing a practice Computer Science UIL test form when I came across this problem:
What is output by the following?
int a = 5;
int b = 7;
int c = 10;
c = b+++-c--+--a;
System.out.println(a + " " + b + " " + c);
I put down the answer "No output due to syntax error" but I got it wrong. The real answer was 4 8 1! (I tested it out myself)
Can someone please explain to me how line 4 works?
Thanks

I added some parentheses:
int a = 5;
int b = 7;
int c = 10;
c = (b++) + (-(c--)) + (--a);
System.out.println(a + " " + b + " " + c);
b++ :
b = b + 1 after b is used
c-- :
c = c - 1 after c is used
--a :
a = a - 1 before a is used

Look at it like this:
(b++) + (-(c--)) + (--a)
That should make more sense!
Look at Operator Precedence to see why it works this way.

Look at initialization of c like this, c = (b++) + (-(c--)) + (--a);
They had it compressed and intentionally confusing for your learning purposes. The code is essentially saying this, c = (b + 1) + (-(c - 1)) + (a - 1);

Break up the statement a bit. It's intentionally obfuscated.
c = b++ + -c-- + --a;
What this means:
The variable c is assigned the result of...
b (incrementation will take effect after this line), plus
the unary operation - of c (decrementation will take effect after this line), plus
a (decrementation takes immediate effect).
Replace the variables with the values, and you get:
c = 7 + (-10) + 4
c = 1
...and the result of your print statement should be:
4 8 0

Let's slow down, and look hard at the equation. Think about this carefully.
int a = 5;
int b = 7;
int c = 10;
c = b+++-c--+--a;
b++ means increment b after assignment, so b stays equal to its original value in the equation, but will be incremented afterward the equation.
Then there's a +.
Then a negated c--. c gets decremented but will remain the same for the equation.
Then add that to --a, which means a gets decremented immediately.
So the variables values at the print statement will be:
c = 7 + -10 + 4 = 1
a = 4
b = 8
May I add that in my opinion this is a bad question for a test. All its really asking is if you understand i++ vs ++i.

Related

Tricky basic java operations [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 3 years ago.
I got these 2 different codes in Java that I can't understand how they produce these specific outputs.
They seemed to work in 2 different logic and I can't figure it out!
int a = 5;
int b = 4;
a -= (b++) + ++a; // For more confusing results replace -= with += and see how the logic changes.
System.out.println(a); // Output: -5
and
int c = 8;
c += ++c;
System.out.println(++c); // Output: 18
How does each situation work and how are they producing these specific outputs?
The major difference here is what post and pre increment are. These determine whether the value is increased before evaluation, or afterward.
Here is how the first case breaks down mathematically:
a = 5 - (4 + 6), which reduces to -5.
Note that a is increased from ++a AKA preincrement before the math is done, however b is calculated as 4. Another thing to note is the a used from the -= uses the original a value, regardless of post or pre increment.
The second equation reduces to this mathematically:
c = 8 + 9 which reduces to 17.
The output prints 18 because your System.out.print(++c) increments it one more time before output due it being preincrement. Note if the print statement used c++, the value would print to 17.
The chart for operator precedence can be found here. Note that assignment has lower precedence than the unary/postfix operators.
It's all about the Operator Precedence in Java. Check that table and figure out which operation takes place first and which last.
It is equivalent to:
int a = 5;
int b = 4;
a -= (b++) + ++a; // => 5 -= (4) + 6
int c = 8;
c += ++c; // => 9 += 9
The main diff is thet:
++a and ++c increments the value and immediately returns it.
b++ returns the value and then increments it.
There is a difference in the order of ++. While both increase the variable, ++a will pass the original value to the operation chain your in middle of; while a++ would pass the new value. So for your first example:
++a --> a is now 6; but the equation is using 5:
a -= (b++) + 5;
b++ --> b is now 5;
a -= 5 + 5;
a -= 10;
? = 5 - 10;
a = a - 5 + 5;
a = 5 - 5 + 5;
a = -10;
(You should have enough to trace the second example).
For a list of operations try this. Some more increment examples are here.
A minimal example is `
int x=3,y=3;
x += ++x;
y+= y++;
at the x x is 7 and y is 6. Precedence alone is not enough to explain the behaviour. Using precedence the second line would be x += (++x), i.e. increment x and return its value, (x is now 4); next we have x+=4 which would return 8.
Instead, it seems better to treat x += w as a short hand for x = x + w, this rewriting happens before evaluation. In our case the rewriting is x = x + ++x interpreted as x = (x + (++x)). So interpreted as
x = ( 3 + (++x))
x = ( 3 + 4 ) x is 4
x = 7 x is 7
A simlar system works to the y equation giving y = 6 at the end.

What is really happening here? This is a code for swapping two variables

a = b-(a-(b = a)); //swapping a and b
also, if a=20,b=10 why does
System.out.println(b = a);
give 20 as result?
a = b-(a-(b = a)); //swapping a and b
It's a way of swapping numeric types without the need of a support variable.
They usually ask you this in interviews.
It is particularly unreadable as it's written in one line, but consider this step by step:
int a = 5;
int b = 2;
a = b - a; // <- -3
b = b - a; // <- 2 - ( - 3) <- 5
a = a + b; // <- (- 3) + 5 = 2
You still can't swap non-numeric types without a temporary variable.
With
System.out.println(b = a);
I guess you wanted to check if b equals a, in which case you should have written System.out.println(b == a), which evaluates to a boolean result.
With b = a, you are assigning a's value to b and then print its result.

difference between + and += in java? [duplicate]

This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 7 years ago.
Could explain me why there is a difference when I want to sum some numbers?
int a = 4;
int b = 6;
int e = 10;
int wynik1 = a += b += e; //so it is 20.
System.out.println(wynik1);
int wynik2 = a + b + e;
System.out.println(wynik2); // so it is 46....
Should I just use always += instead of +?
I'm confused because when I was learning, for example, loops, I was using for (int p = 20; p<40; p=p+ 5) and it was working fine.
Why is it 46?
In most cases (exception) a += b as equivalent of a = a + b
So
int wynik1 = a += b += e; //so it is 20.
is same as
int wynik1 = (a = a + (b = b + e)); // so it is 20.
which means that
first b = b + e will be executed making b 6 + 10 = 16
then since b is 16 a will be assigned with result of 4 + 16 = 20
which finally will be assigned to wynik1.
So after that line (a = a + (b = b + e)) (or in your case a += b += e;) our variables will hold these values:
a = 20
b = 16
e = 10 (e didn't change since there was no e=.. in our code)
This should explain why
int wynik2 = a + b + e; //20 + 16 + 10
is 46.
+= is way different from +.
a+b means add a and b and do something with the result.
a += b means add a and b and assign the result back to a.
In your example I don't think you want to have that kind of side effect in the first expression as you probably want to use the original values in the next expression.
The += operator is distinct from the + operator in that it also assigns the result back to the variable.
a = a + 5;
a += 5;
Are equivalent.
In your example,
int wynik1 = a += b += e;
Not only is wynik1 equal to 20, but a is now also equal to 20 and b is now 16. This is why your second line returns 46:
a + b + e
= 20 + 16 + 10
= 46
The operator += is a shortcut.
Doing: a += 1; is equivalent to a = a + 1;
So, when you do: int wynik1 = a += b += e;
is reality you are doing:
int wynik1 = (a = a + (b = b + e));
+ just adds numeric values
+= adds the value on the right to the variable on the left part
Examples:
int a=3;
int b=4;
int c = a+b; // result c==7
c += 1; // result c==8
You can also use any other operator, like - * /
int d = 4;
d -= 3; // result d=1
int e=13;
int f *=3; // result f=39
As for the line:
int wynik1 = a += b += e;
b will be added with 10,
a with b, which is now 16, so the result is 20
The difference with a simple + is that the value of b is changed as well.
You could rewrite this to:
b = b + e; //results in b equals16
a = a + b; //results in a equals 20
First, note that
a += b;
is equivalent to
a = a + b;
The order of operations for assignment in Java is right to left. So,
a += b += e;
is
b = b + e; //16
a = a + b; //20
wynik1 = a; //20
Hence
wynik2 = a + b + e; //46

Java modulus operator

Use a modulus operator is something which all programmers must to know. I know it =).
In java we have :
int a = 100 , b = 50, c;
If we do :
c = a % b; // c = 0 because : 100 = 50*2 + 0 | D = d*q + r using simple maths
However I felt a little frustrated for not finding the Why of this operation :
c = b % a; // c = 50 ???? It seems not to have logic when a use D = d*q + r
Can someone could explain me why 50 % 100 is 50 ??? I can't understand very well.
Thanks
Becuase you can multiply by 0:
c = 100*0 + 50;
It's the + 50 that is returned as modulo.
Think of it this way:
100 goes into 50 how many times?
Zero times. So there must be 50 left over. Therefore the answer is 50.

Java: Prefix - Postfix issue

I have a small issue performing a subtraction on numbers using prefix and postfix operators.
This is my program:
public class postfixprefix
{
public static void main (String args[])
{
int a = 5;
int b;
b = (a++) - (++a);
System.out.println("B = " +b);
}
}
Doing this, theoretically I am supposed to get 0 as the answer, but however, I am getting a -2.
When I try to individually try to increment the values like in this program:
public class postfixprefix
{
public static void main (String args[])
{
int a = 5;
int b, c;
b = a++;
c = ++a;
System.out.println("B = " +b);
System.out.println("C = " +c);
}
}
I get the values as B = 5, C = 7.
So i get the idea that 'c' takes the value of 'a' from 'b' (Please correct me if i am wrong), but what I want to know is
How can I have it not take the value of 'a' from 'b', and
using prefix - postfix, can I have 0 as an answer when they're subtracted.
If you go through this step by step, you can see what happens:
b = (a++) - (++a); //a is now 5
b = 5 - (++a); //read a, then increment it. a is now 6
b = 5 - 7; //increment a, then read it. a is now 7
b = -2
If you do it the other way, you get:
b = (++a) - (a++); //a is now 5
b = 6 - (a++); //increment a, then read it. a is now 6
b = 6 - 6; //read a, then increment it. a is now 7
b = 0
b = a++;
means:
assign to b the value of a
increase a by 1
c = ++a
means:
increase a by 1
assign to c the value of a
b = (a++) - (++a)
means:
get the value of a (5) (a without the ++)
increase the value of a by 1 (thus making it 6) (the result of a++)
increase a by 1 (++a) (thus making it 7)
assign to b thae value 5-7=-2 (5 from step 1, 7 from step 3)
So i get the idea that 'c' takes the value of 'a' from 'b' (Please correct me if i am wrong), but what I want to know is 1) How can I have it not take the value of 'a' from 'b'
Its not like this, in c = ++a; value is taken from a only, in b = a++; statement, a was incremented but after assigning value to b, and then while c = ++a; a is again incremented and assigned to c (as this is pre-increment now)
2) using prefix - postfix, can I have 0 as an answer when they're subtracted.
you can have like: b = (++a) - (a++); as first a increments first and then the second a (which is now 6) is substracted from first a (still 6). And then the final value of a is 7
int a = 5;
int b, c;
b = a++;
c = ++a;
About this code b has a value 5 because posting fix increment/decrement happens after assingment is completed. So the value is 5.
c has a value 7 because prefix increment/decrement happens before assingment is completed. So the value is 7 beause previous statement made the value of a as 6.
About this code
int a = 5;
int b;
b = (a++) - (++a);
System.out.println("B = " +b);
when brackets are applied, your prefix/postfix operations will be completed first in (a++) - (++a); from left to right fashion.
So firstly if we go left to right
(a++) -(++a)
1. (a++) -- Take 5 from a.
2. (++a) -- 5 becomes 6 with ++a take 6.
3. (a++) - (++a) -- Subtract results of (a++) - (++a) operations which makes it -2.
Solutions for you first query -- How can I have it not take the value of 'a' from 'b', and
int a = 5;
int temp = a;
int b, c;
b = a++;
c = ++temp;
System.out.println("B = " +b);
System.out.println("C = " +c);
**Solutions for you first query has been well explained by Sir #Keppil **

Categories

Resources