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 ");
}
}
}
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 ");
}
}
}
😂 Its a kind Of Trick 😄👍✌️
ReplyDeleteyes my dear amar
DeleteBut if is not executed above, only condition is checked, body remains unexecuted.
ReplyDeletedear 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