A
A
Arthur Braver2016-02-12 09:45:15
Java
Arthur Braver, 2016-02-12 09:45:15

Explain Java code?

There is the following code:

int a = 1, b = 2;
b=a + 0*(a=b);
System.out.println(b+" " +a);

As a result, the values ​​of a and b are swapped. I can not understand at what point this happens and why a and b do not become equal to each other?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Roo, 2016-02-12
@Zurus

Here's what happens after compilation:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

public class test {
    public test() {
    }

    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        byte var10000 = a;
        a = b;
        int b1 = var10000 + 0 * b;
        System.out.println(b1 + " " + a);
    }
}

As you can see, there is no magic here.
In general, I do not recommend using such "magic". It is much better to write clear and obvious code.

A
aol-nnov, 2016-02-12
@aol-nnov

presumably this is an example of undefined behavior.
terrible magic, which, when applied in production, will spoil the healthy sleep of the developer.
the java compiler, as shown in one of the answers, added a temporary variable, which provided this behavior.
For example, if you draw this example in C (gcc), there will be no such magic. Again, I guess another compiler might do otherwise.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question