Monday, July 9, 2007

Print any text without using semicolon in the program

Here is the question.

Print any text without using semicolon in your program.

In C/C++, it is wasy to answer, you will say:

int main(){
if (printf("Printed the text without using semicolon")){}
}


But in Java, you cannot do directly like that because System.out.println() returns nothing and the println()'s return type is void.

So, how will you do it in Java?
We can do the same in Java using Reflection classes(java.lang.reflect)

class semicolon{
public static void main(String args[]){
try{
if (System.out.getClass().getDeclaredMethod("println", Class.forName("java.lang.String")).invoke(System.out, "This text is printed by a program without a semicolon") == null){}
}catch(Exception e){
}
}
}


Just try it out yourselves.

2 comments:

GayanNR said...

class semicolon
{
public static void main(String args[])
{
if(System.out.printf("hellow world")==System.out.printf(""))
{
//nothing in here

}
}
}

Antony Vincent Pandian.S. said...

Hi Gayannr,
Your answer is correct when the java version is greater than 1.5

The printf method is not present in versions before 1.5