Single Choice Easy

QGive the output of the following method:

public static void main(String args[]){
    int a = 5;
    a++;
    System.out.println(a);

    a -= (a--) - (--a);
    System.out.println(a);

}

ID: #22238 switch case in Java 126 views
Question Info
#22238Q ID
EasyDifficulty
switch case in JavaTopic

Choose the Best Option

Click any option to instantly check if you're correct.

  • A 6 4
  • B 5 7
  • C 4 6
  • D 6 6
Correct Answer

Explanation

Let's analyze the given Java code to determine its output:

Code:


public static void main(String[] args) {
    int a = 5;
    a++;
    System.out.println(a);
    
    a -= (a--) - (--a);
    System.out.println(a);
}
        

Explanation:

  1. Initial Code Analysis:

    - int a = 5; initializes a with the value 5.
    - a++; increments a by 1. After this operation, a becomes 6.
    - System.out.println(a); prints the value of a, which is 6.

  2. Second Part of the Code:

    - a-- is the post-decrement operator. It returns the value of a before decrementing it. So, a-- evaluates to 6, and then a is decremented to 5.
    - --a is the pre-decrement operator. It decrements a first, so --a evaluates to 4, and a becomes 4.
    - Therefore, the expression a -= (a--) - (--a) translates to a -= 6 - 4:

    • 6 - 4 evaluates to 2.
    • Thus, a -= 2 is equivalent to a = a - 2. Since a is 4 at this point, this becomes 4 - 2, which results in 2.

    - System.out.println(a); prints the value of a, which is 4.

Conclusion:

The output of the program is:

  • 6 (after the a++ operation)
  • 4 (after the a -= (a--) - (--a) operation)

Share This Question

Challenge a friend or share with your study group.