• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Doubt with static block+variable

 
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
source http://www.valoxo.ch/jr/mocks/mock01a.html Q54

What is the output of the following code when compiled and run? Select two correct answers.
public class Question54 {
static int i;
int j;
static {
System.out.print("("+i+")");
i=3;
System.out.print("("+i+")");
}
{
System.out.print("("+i+","+j+")");
j=2;
System.out.print("("+i+","+j+")");
}
Question54(){
System.out.print("("+i+","+j+")");
}
public static void main(String[] args) {
System.out.print("("+i+")");
Question54 q54 = new Question54();
System.out.print("("+q54.i+","+q54.j+")");
}
}

A. Prints: (3)(3)(3)(3,2)(3,2)(3,2)(3,2)

B. Prints: (0)(3)(3)(3,0)(3,2)(3,2)(3,2)

C. Prints: (0)(3,0)(3,2)(3)(3)(3,2)(3,2)

D. Prints: (3)(3,3)(3,2)(3)(3)(3,2)(3,2)

E. The code compiles and runs fine.

Ans:B,E
Doubt: not able to understand flow and hence the output? static I as well as the static block will execute at the class loading time, after that the constructor and then other statements in class, but according to ans it is not so


pls help,
Gitesh
 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is the flow:
(0)(3) at static block (class loading)
(3) at first statement in static main() method
(3,0)(3,2) at new instance block
(3,2) at constructor
(3,2) at last statement in main()
 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks Greg
 
A timing clock, fuse wire, high explosives and a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic