Please open the menu to show more

Friday, July 21, 2017

Here i am posting a very interesting java program. It is frequently asked in interviews (mainly in TCS).
In this code if as well as else both will be executed (as we know if and else both cant be executed at a time)

Lets understand the code =>

## the printf method in java will print the message and will return the object of PrintStream (it is a pre-defined-class).
since, printf returns an object so we can check a condition inside if statement by comparing the returned object with null. as we know an object cant be null the condition become false and else part will be executed, but before else part the message is already been printed by printf.


note: null means no object


public class ExecutionOfIfAndElseAtSameTime 
{
public static void main(String[] args) 
{

if(System.out.printf("Hello, my name is if")==null)
{

}
else
{
System.out.printf("\nand, my name is else ");
}

}
}

4 comments:

  1. 😂 Its a kind Of Trick 😄👍✌️

    ReplyDelete
  2. But if is not executed above, only condition is checked, body remains unexecuted.

    ReplyDelete
    Replies
    1. dear suraj, the actual question is the execution of if and else at the same time, the body consideration was not there in interview. hope you get the answer. sorry for the late response.

      Delete