aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes could you pls explain this   code and the output. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "could you pls explain this   code and the output." Watch "could you pls explain this   code and the output." New topic
Author

could you pls explain this code and the output.

Supriya Nimakuri
Ranch Hand

Joined: May 23, 2006
Posts: 83
What will happen when you attempt to compile and run the following code?

How will a b.run(); a valid condition. instead of b.start();

public class Bground extends Thread{
public static void main(String argv[]){
Bground b = new Bground();
b.run();
}
public void start(){
for (int i = 0; i <10; i++){
System.out.println("Value of i = " + i);
}
}
}

1) A compile time error indicating that no run method is defined for the Thread class
2) A run time error indicating that no run method is defined for the Thread class
3) Clean compile and at run time the values 0 to 9 are printed out
4) Clean compile but no output at runtime
Peter MacMillan
Ranch Hand

Joined: Jun 23, 2006
Posts: 34
As written, that code will compile and run cleanly without any output (4).

To understand why, examine the java API for the Thread.start and Thread.run methods.

As a hint, here is a modified version that will produce output:




hint: the default run method is essentially empty (well, it will try to use a delegate Runnable, but that's not applicable in this case). The code from your question overrides the start() method and calls the Thread.run() method.

Hope that helps.
[ June 27, 2006: Message edited by: Peter MacMillan ]
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023

How will a b.run(); a valid condition. instead of b.start();


Can the run() Method Be Called Directly to Start a Thread?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: could you pls explain this code and the output.