简体   繁体   中英

Why to use "printf" instead of "println" while printing hello in if statement

I want to print "hello" without using semicolon.While using for loop for printing hello i came to know println and printf both can be used for printing hello. But in case of if only printf is used for printing hello.When i used println in if statement its showing "void type not allowed here".What does this error means and why println cannot be used in if statement??

public class withoutsemicolon
{ 
public static void main(String [] args)
{   
for(int i=0;i<=4;System.out.println("hello"+i+"\n"),i++)
{}
if(System.out.println("hello"+"\n")!=null)
{}
}
}

The reason is printf returns PrintWriter which you can compare to null . println returns void ie nothing which you can't compare to null. A couple of additional options to print without using semicolon in your program are while and try . All the mentioned options:

if(System.out.printf("hello\n") == null){}
while(System.out.printf("hello\n") == null){}
try(Closeable c = System.out.printf("hello\n")){}

One additional option and my favorite is to tell the interviewer that you refuse to answer stupid questions but that's a luxury not everybody have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM