Showing posts with label Tricky Java Programs. Show all posts
Showing posts with label Tricky Java Programs. Show all posts

Monday, June 21, 2010

Solution to the tricky program 2

 Solution to the program http://javacoderblog.blogspot.com/2010/05/tricky-program-1-to-java-beginners.html

import java.io.*;
public class NMM
{
static
{

final PrintStream out = System.out;

PrintStream newOut = new PrintStream(out)
{

public void println(String str1)
{
print("Great ");
print(str1);
super.println("Programmer");
}
};

System.setOut(newOut);
}


public static void main(String [ ]argums)
{
System.out.println("Java ");
}
}

Tuesday, May 18, 2010

A tricky program 2 to Java Beginners,

Question:- You should bring the output by not modifying the main method,The output is "Great Java Programmer".

class NMM //No main method
{
public static void main(String []args)
{
System.out.println(“Java”);
}
}Seems to be tricky for you right?.Let us see what is answer in the next post..If you know the answer just post as comment or mail to me.

UPDATE: Check out the solution here http://javacoderblog.blogspot.com/2010/06/solution-to-tricky-program-2.html

Java program that runs without Main method

Most of you heard about this popular question.this post is for those who did not know about this.
While Learning Java in Computer Centre,my Mam asked me this question. I replied, immediately “Mam, Applets run without main method,is this is answer?” ;) . It is also a right answer I think..But it is not the answer what she expected. She asked me to write a program again, without main method,, after some time I gave her the answer,[ I read related article already ]. I wrote the following program.
class NMM //No main method
{
static
{
System.out.println(“This is the Java Program That Runs Without Main Method”);
System.exit(0);
}
}
Reason is, before the main block getting executed, the static initializations gets executed. So You might ask , why this System.exit(0) line. This is to terminate the program, when it throws exception because of the class not having main method.