Q95
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
AnswerAnswer: Option D
Solution
Answer: Option D
Solution:
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.