3

I was going through java code snippets and this one snippet I am not able to figure out why the output is 2?

 package com.instanceofjava;     
    public class A{  
     static int a = 1111;
     static
     {
            a = a-- - --a;
     }        
     {
            a = a++ + ++a;
     }     
     public static void main(String[] args)  {     
           System.out.println(a);     
        }     
    }

Can somebody explain why the output is 2 for this code snippet.

2 Answers 2

6

Since you don't create an instance of your class, only the static initializer block is executed (the expression a = a++ + ++a; in the instance initializer block is not executed).

First a is initialized to 1111 (as a result of static int a = 1111;).

Then the static initializer block is executed and the following assignment takes place :

a = a-- - --a;

a-- decrements a and returns the previous value 1111. --a decrements the previously decremented value (1110) and returns the new value 1109.

Hence the expression is evaluated to :

a = 1111 - 1109 = 2
Sign up to request clarification or add additional context in comments.

6 Comments

'a-- decrements a and returns the previous value 1111'. If a-- decrements a why it then returns 1111 again?
so a-- makes the value as 1110 and --a makes it 1109 but since a-- is there so decremented value will be used next time and a-- will be 1111 only?
@ArthurEirich the postfix decrement operator a-- decrements the value of a but returns the previous value of a. That's the definition of this operator.
@Akki619 Yes, a-- will return the original value of a - 1111 - even though it decrements it to 1110.
@SSH Whether the static keyword is missing from the second block or was intentionally left out is another question. Without the static keyword, it is an instance initializer block, which would only get executed when you create an instance of the class. Since no instance of A is ever created, it is not executed.
|
3

The key point here to note is only static block executes and initialization block never executed here.

Hence the code

  static
     {

     } 

Executed and giving result 2.

Just to check with you can remove the whole initilization block and run

public class A{
    static int a = 1111;
    static
    {
        a = a-- - --a;
        System.out.println(a);
    }

    public static void main(String[] args)  {
        System.out.println(a);
    }

And run the code. Gives you the same out put.

And coming to the part decrement

a-- means: Decrement a AFTER evaluating the expression.

--a means: Decrement variable BEFORE evaluating the expression.

Hence the line a = a-- - --a; equals to

a = 1111 - 1109

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.