Results 1 to 2 of 2
Thread: Order of Execution
- 07-31-2011, 08:44 AM #1
Member
- Join Date
- Jul 2011
- Posts
- 2
- Rep Power
- 0
Order of Execution
I am fairly new to the core concepts of Java and don't have much expertise as to how the execution steps are followed. The following is a code from Kathy & Sierra's book and I am unable to understand how the execution is carried out.
=========
JAVA CODE
=========
class Bird {
{
System.out.print("b1 ");
}
public Bird() {
System.out.print("b2 ");
}
}
class Raptor extends Bird {
static {
System.out.print("r1 ");
}
public Raptor() {
System.out.print("r2 ");
}
{
System.out.print("r3 ");
}
static {
System.out.print("r4 ");
}
}
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}
Output:
r1 r4 pre b1 b2 r3 r2 hawk
=====================
Help me clarify some doubts
=====================
1. I was under the impression that execution of any code starts from main(). Is that true?
- if it is, then how come the code actually jumps to the class and accesses the static initializer blocks when there is no code accessing the class itself.
2. According to me, the order of execution is like this:
main() --> SOP("pre") --> "pre" is printed on screen --> new Hawk() --> //Raptor is accessed ---> //Bird is accessed --> // r1 and r2 printed ---> r1 r4 r3 r2 printed ---> SOP("Hawk") ---> hawk printed.
Please help me correct the order of execution.
- 07-31-2011, 09:14 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Not really. The precise order of events (which begins with the runtime actually loading a binary representation of the Hawk class; something that must preceed anything to do with the main() method) is summarised in the JLS Chapter 12 - Execution. It's quite a read! and the JVM documentation includes even more.I was under the impression that execution of any code starts from main(). Is that true?
Pay attention to "12.1.3 Initialize Test: Execute Initializers" which happens just before main() is invoked. Ask if you are unsure about what it is saying, in particular about what "initialisation" means in this context and in what order it will occur with respect to a class and all its superclasses.
Similar Threads
-
thread execution one after another
By turanan in forum New To JavaReplies: 16Last Post: 05-08-2012, 12:11 PM -
Re-iterate Thread execution after its execution finishes.
By TurtleRock in forum New To JavaReplies: 10Last Post: 11-29-2010, 02:02 PM -
Order of EXECUTION followed by JVM!
By _ShivamKapoOr_ in forum New To JavaReplies: 5Last Post: 09-24-2010, 09:18 PM -
JAR execution
By patoh in forum New To JavaReplies: 2Last Post: 11-26-2008, 09:09 AM -
Execution cut
By Eric in forum Advanced JavaReplies: 1Last Post: 06-27-2007, 03:52 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks