JAVA QUESTION

Let me tease u a little bit!! Below is a quite familiar java prog. :


public class MyDraft {

public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("Welcome to Java!");
MyDraft obj = new MyDraft();
System.out.println("Bye Bye!");
}
}



Now the ques. is : Can u do some familiar coding inside MyDraft class but outside the main() method i.e. u must not modify the main() method at all, so that the above prog. gives the output as: All are JavaGuru!


Hint: you have to think of a way such that the main() method doesn't get executed & only "All are JavaGuru!" gets printed in the output.


ANS. It is mentioned in the comments

1 comments:

gautam said...

1:42 am(1½ hours ago) ok....Here's the simple solution :



public class MyDraft {

static {
System.out.println(" All are JavaGuru!");
System.exit(0);
}

public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("Welcome to Java!");
MyDraft obj = new MyDraft();
System.out.println("Bye Bye!");
}
}




output : All are JavaGuru!

Explanation : We know that static blocks are executed before any statement in the main method. Also the control doesn't return to the main method. This is ensured by System.exit(0) method used within static block!!

Post a Comment