Java Programming - Operators and Assignments - Discussion
Discussion Forum : Operators and Assignments - Finding the output (Q.No. 8)
8.
What will be the output of the program?
class Test
{
public static void main(String [] args)
{
int x= 0;
int y= 0;
for (int z = 0; z < 5; z++)
{
if (( ++x > 2 ) || (++y > 2))
{
x++;
}
}
System.out.println(x + " " + y);
}
}
Answer: Option
Explanation:
The first two iterations of the for loop both x and y are incremented. On the third iteration x is incremented, and for the first time becomes greater than 2. The short circuit or operator || keeps y from ever being incremented again and x is incremented twice on each of the last three iterations.
Discussion:
20 comments Page 2 of 2.
Anand patil m said:
9 years ago
Enter a number to find fact.
3
n store 3
if(3<0)
no so 3 is not a negative number
then else execute
for()
The first iteration take 1 value is less then equal 3
yes
fact=1*1
fact store 1
next iteration
2is less then equal to 3
yes
then
fact=1*2;
fact store 2
3rd iteration
3 is less then equal to3
yes then
fact=2*3
then fact store 6.
fourth iteration fail then print 6 value.
3
n store 3
if(3<0)
no so 3 is not a negative number
then else execute
for()
The first iteration take 1 value is less then equal 3
yes
fact=1*1
fact store 1
next iteration
2is less then equal to 3
yes
then
fact=1*2;
fact store 2
3rd iteration
3 is less then equal to3
yes then
fact=2*3
then fact store 6.
fourth iteration fail then print 6 value.
Arun said:
8 years ago
Guys, When we use || logic operator, second condition will be executed only when the first condition is false.
Saurabh said:
8 years ago
In simple word, in Logical OR, if the first condition is true then second will be ignored.
So here the condition of 'y' is checked only for 2 times.
So here the condition of 'y' is checked only for 2 times.
Malathi said:
8 years ago
Thanks @Maheshthakuri.
Priyanka said:
8 years ago
Thank You @Arun.
Neha said:
7 years ago
Thanks @Maheshthakuri.
Mayur Patil said:
6 years ago
Thanks @Maheshthakuri.
Sanjay kumar said:
5 years ago
Thanks @Maheshthakuri.
Arham said:
3 years ago
Thank you for explaining @Arun.
Sami said:
7 months ago
@All.
Here, || (OR) operator short-circuits, the second part (++y > 2) is not evaluated?
Yet y still incremented.
Then the result should be 8 5.
Here, || (OR) operator short-circuits, the second part (++y > 2) is not evaluated?
Yet y still incremented.
Then the result should be 8 5.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers