• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can anyone tell me the correct answer for the following question with explanation

 
R .sourav nayak
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class JMM125 {
static int i;
public static void main(String args[]) {
for (i=1; i<3; i++) {System.out.print(i);} // 1
for (int i=1; i<3; i++) {System.out.print(i);} // 2
int i; // 3
for (i=0; i<2; i++) {System.out.print(i);} // 4
System.out.print(JMM125.i);
}}

What is the result of attempting to compile and run the program?

a. Prints: 1212010
b. Prints: 1212013
c. Compile-time error at line 1
d. Compile-time error at line 2
e. Compile-time error at line 4
f. Run-time error
g. None of the above

why the correct answer is b. 1212013?

thanks in advance
reena
 
Radoslaw Sztando
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


first "for" loop is iterating using JMM125.i variable. It prints: "12" (and JMM125.i is set to 3).
Second loop uses loop-local variable and also prints "12". After loop finishes variable is disposed.
Third loop uses variable declared in line //3. It prints "01".
And last line prints value of JMM125.i which is set to 3 at first loop.

As a result 1212013 is printed.

Hope it helps
 
nivas ratthaaq
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember always local variable got preference over global varibales.When you say 'i' means it tries to access the local variable 'i' (if it is there!).
 
wise owen
Ranch Hand
Posts: 2023
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic