Posted by: ahmedashfaque | March 11, 2015

Why Java is so popular? Part 10


So far in part 1, part 2, part 3, part 4, part 5, part 6, part 7, part 8 and part 9 we have covered many topics on Java. In this post we will see nested if statement.

If you have a requirement to check 2 conditions for a statement to verify then you can use a nested if statement. Let us see an example:

public class doubleCheck{

public static void main(String args[]){
int x = 40;
int y = 30;

if( x == 40 ){
if( y == 30 ){
System.out.print(“X = 40 and Y = 30”);
}
}
}
}

The system will print “X = 40 and Y = 30”.

Explanation

The system will first check value of x. If value is true then it will proceed to check value of y. If value of y is also true then the system will go to statement to print the values of X and Y. if any of the conditions is false then the system will terminate the program without reaching the print statement. In that case, the print statement can not be reached and so there will be no printing of values.

Nested if statements are complex in nature and so should be avoided.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: