Java Programming - Java.lang Class - Discussion
Discussion Forum : Java.lang Class - Finding the output (Q.No. 11)
11.
What will be the output of the program?
public class ExamQuestion7
{
static int j;
static void methodA(int i)
{
boolean b;
do
{
b = i<10 | methodB(4); /* Line 9 */
b = i<10 || methodB(8); /* Line 10 */
}while (!b);
}
static boolean methodB(int i)
{
j += i;
return true;
}
public static void main(String[] args)
{
methodA(0);
System.out.println( "j = " + j );
}
}
Answer: Option
Explanation:
The lines to watch here are lines 9 & 10. Line 9 features the non-shortcut version of the OR operator so both of its operands will be evaluated and therefore methodB(4) is executed.
However line 10 has the shortcut version of the OR operator and if the 1st of its operands evaluates to true (which in this case is true), then the 2nd operand isn't evaluated, so methodB(8) never gets called.
The loop is only executed once, b is initialized to false and is assigned true on line 9. Thus j = 4.
Discussion:
8 comments Page 1 of 1.
Stinger said:
1 decade ago
Never heard of the term "non-shortcut version of the OR operator". Should be labeled "bitwise OR operator"?
Raj said:
1 decade ago
Where j is initialized?
Costas said:
1 decade ago
I agree this Raj. I think that this should produce a compilation error as j is never initialized and += operator is used.
Laughingpig said:
1 decade ago
@Raj, Java guarantee class-level variables are initialized. int's are initialized to 0.
Sharad said:
1 decade ago
Why methodB(8) never gets called?
Hemanth said:
1 decade ago
Hi @Raj where local where b initialized.
In method methodA().
In method methodA().
Dhamu bee said:
7 years ago
What is the value of j += i;?
Chandu said:
4 years ago
Where j is initialized? Anyone, please explain me.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers