Decision making in Java

The best part about coding is making things happen. But it’s not fun printing predefined stuff, we need things to happen on specific conditions. For this we make use of something called if statement. This is a simple if statement:

int x = 5;
int y = 2;

if (x > y) {
	System.out.println("X is greater than Y");
}

Currently the condition (x > y) is true, so the if block will be executed. And then everything else after the if block will be executed in normal flow.

What if you need to execute something if (x < y)? In that case, you can use an else statement as follows:

int x = 5;
int y = 2;

if (x > y) {
	System.out.println("X is greater than Y");
}
else {
	System.out.println("X is less than Y");
}

In any case you wish to have multiple conditions, you can do that as well using an else if statement in the middle as follows:

int x = 5;

if (x == 5) {
	System.out.println("X is 5");
}
else if (x == 6) {
	System.out.println("X is 6");
}
else {
	System.out.println("X is not 5 or 6");
}

You can also have nested if statements as follows:

String x = "human";
String y = "male";

if (x == "human") {
	if (y == "male") {
		System.out.println("It's a human male model");
	}
}

Then there’s the switch statement:

int x = 0;

switch(x) {
	case 1: System.out.println("number is 1");
			System.out.println("this is first case");
			break;
	case 5: System.out.println("number is 5");
			break;
	default:
			System.out.println("number is not 1 or 5");
}

You can try to run the above code with different values of x. Try putting in 0, 1 and 5 to see the output. If x equals 1, statements inside the first case are executed. If x equals 0, the default case is executed as no case is matched.

In the next post, I’ll share info on loops in Java!