Examveda

What will be the output of the following Java program?
class Output 
{
    static void main(String args[]) 
    {    
         int x , y = 1;
         x = 10;
         if(x != 10 && x / 0 == 0)
             System.out.println(y);
         else
             System.out.println(++y);
    } 
}

A. 1

B. 2

C. Runtime Error

D. Compilation Error

Answer: Option D

Solution (By Examveda Team)

This Java program defines a class named "Output" with a main method. Inside the main method, it declares two integer variables, x and y, and initializes y to 1. Then, it assigns the value 10 to x.

In the if statement, the condition x != 10 && x / 0 == 0 is evaluated. Since x is indeed equal to 10, the first part of the condition, x != 10, evaluates to false.

However, Java short-circuits the logical AND operator (&&), meaning if the left operand is false, the right operand is not evaluated. Thus, x / 0 == 0 is not executed because of the short-circuiting behavior.

Therefore, the else block is executed, which increments the value of y by 1 using the pre-increment operator (++y).

So, the output of the program will be 2.

Therefore, the correct answer is Option B: 2.

This Question Belongs to Java Program >> Miscellaneous In Java

Join The Discussion

Comments (1)

  1. Yasir Khan
    Yasir Khan:
    1 year ago

    The answer will be B. 2

Related Questions on Miscellaneous in Java