Home
/ Puzzle for Java Programmers
Puzzle for Java Programmers
This post is intended to sharp the programming skills of a Java programmer. Those who don’t know programming in Java can skip this post.
Here I am presenting a small piece of code written in Java.
class N
{
public static void main(String [] args)
{
System.out.println(“Java”);
}
}
The above program simply prints Java. Now the question is with out modifying the main method you have to print the output as Sun Java Programmer. Remember you are not allowed to change the content of main method. Outside main you can do anything as you like.
Hope you got my point. Let me know your answer via comments.
Now it’s the time to post the solution for the above puzzle. The only reason for delaying to post the solution is, I want you people to try on your own. I received a lot of comments and mails regarding this. Naveen Kumar and Rajeev have successfully solved this puzzle. Remaining people also tried but there are some mistakes. Here is the logic:
class N
{
static
{
System.out.println(“Sun”);
main(null);
System.out.println(“Programmer”);
System.exit(0);
}
public static void main(String [] args)
{
System.out.println(“Java”);
}
}
Explanation:
We already knew that program execution starts from static block. So Sun will be printed. Now we are calling the main method. Since main method takes String Array as arguments I am passing null String to avoid compile time error. After printing Java, the next statement i.e. Programmer will be printed. But remember after execution of static block control goes to main method and execute all the statements in main method. Hence I terminated the program by calling the exit method in the static block itself so that Programmer will not be printed twice. Hope you got the logic.
SAINADH REDDY
A to Z Info.org website dedicated to Young Indians. This website mainly focus on Education, Jobs, Tricks, Tips, Latest Technology Updates, Software's, Biographies of Eminent Personalities, Entertainment, Film News, Tutorials and many more. Please comment below how to improve our services
0 comments:
Post a Comment