Showing posts with label Java tips. Show all posts
Showing posts with label Java tips. Show all posts

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.