What is the result of the following code execution?
public class Main {
    public static void main(String[] args) {
        int var = 1;
        System.out.println("The variable var (post-increment): " + var++);
        System.out.println("The variable var (pre-increment): " + ++var); //1
        int var1 = 1;
        int var2 = 1;
        if (var1++ == ++var2)  //2
            System.out.println("The variables are equal");
        else 
            System.out.println("The variables are not equal");
    }
}
Explanation
Increment and decrement operators are available in 2 forms: postfix and prefix. The difference between them is that the postfix operator is executed after the expression is evaluated, but prefix - before it is evaluated. Thus, the line with a postfix expression var ++ will result in the original value of the variable var (1), and the one with a prefix expression - the new value of given variable (3).
Because of that, when comparing the values of expressions ​​var1++ and ++var2 - they will not be equal.

Fixed.

2015 Jun 26, 8:05:56 PM

What is this russian text?

2015 Jun 26, 7:24:56 PM

Java
Java Quiz
Start Quiz

or Read more about Java Quiz

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback