Unusual Java Syntax

When I ran into this problem, I passed the Computer Science UIL test form:

What is output as follows?

int a = 5; int b = 7; int c = 10; c = b+++-c--+--a; System.out.println(a + " " + b + " " + c); 

I postponed the answer "No output due to a syntax error", but I realized that it was wrong. The real answer was 4 8 1! (I checked it myself)

Can someone explain to me how line 4 works?
Thanks

+6
source share
5 answers

I have 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 using b

c--: c = c - 1 after using c

- a: a = a - 1 before using a

+14
source

Look at it like this:

 (b++) + (-(c--)) + (--a) 

That should make more sense!

See Operator Priority to see why it works this way.

+6
source

Look at the initialization of c as follows: c = (b++) + (-(c--)) + (--a);

They have been compressed and intentionally confused for your training purposes. The code essentially says this, c = (b + 1) + (-(c - 1)) + (a - 1);

+3
source

Slightly untwist instructions. He was deliberately confused.

 c = b++ + -c-- + --a; 

What does it mean:

  • variable c assigned the result ...
    • b (increment will take effect after this line) plus
    • unary operation - of c (decrement takes effect after this line), plus
    • a (decrement has an immediate effect).

Replace the variables with the values ​​and you will get:

 c = 7 + (-10) + 4 c = 1 

... and the result of your print statement should be:

 4 8 0 
+2
source

Let it slow down and look hard at the equation. Think about it carefully.

 int a = 5; int b = 7; int c = 10; c = b+++-c--+--a; 

b ++ means increment b after assignment, so b remains equal to its original value in the equation, but after that it will increase.

Then a +.

Then the negation of c-- . c receives a decrement, but remains unchanged for the equation.

Then add this to -a, which means that a decreases immediately.

Thus, the values ​​of the variables in 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 the test. All that he really asks if you understand i++ vs ++i .

+2
source

Source: https://habr.com/ru/post/950979/


All Articles