1

Context: I'm mainly a Javascript/Python developer and I'm doing Java just for schoolwork.

This is the code block that perplexes me.

public static void display(int a, int b) {
  a = a+b-(b=a);
  System.out.println(a);
  System.out.println(b);
}

I encountered this code block in a practice exam I was doing. I expected this to be syntactically incorrect so I tried it with a compiler. No syntax errors appeared.

I don't understand how this is valid syntax. I get that the assignment operator would assign a to b and the result of a = a+b-(b=a) would be the original value of a. How does the compiler register b-(b=a) as a valid piece of code?

alcan
  • 31
  • 1
  • 8
Aadivya
  • 11
  • 4
  • Why would it not be? An assignment expression is still an expression with a well-defined result - see https://docs.oracle.com/javase/specs/jls/se10/html/jls-15.html#jls-15.26 – Jon Skeet Feb 14 '23 at 17:50
  • 1
    `b=a` assigns to `b` and evaluates to the new value of `b`. – khelwood Feb 14 '23 at 17:51
  • _the result of `a = a+b-(b=a)` would be the original value of a_ - no, the result is `a + b - a` which is equal to the value `b` had before. The whole construct is similar to Python: `a, b = b, a` – Thomas Kläger Feb 14 '23 at 18:00
  • Right, it's just something allowed by the syntax. It's useful for example when you both want to remember a result of a method call, and calculate with that result too. `for( int c; (c = stream.read()) != -1; )` etc... – markspace Feb 14 '23 at 18:01
  • Short answer: Because James Gosling decided it so. Slightly longer answer: Given Java's heritage as "C family" language, i.e. with syntax similar to C, that decision was understandable. The concept of assignments being expressions with well-defined values was familiar to Java's original target group when it was introduced, i.e. C and C++ programmers, and James Gosling saw no reason to take that away. Guido van Rossum on the other hand had different priorities when designing Python, and familiarity for C/C++ programmers wasn't in his top tier. So there you have it, I guess. – chris Feb 14 '23 at 19:04

0 Answers0