Java development for beginners 5. If statement and if-else statement

The flow control instructions, like if else and switch, change the flow of the program execution in runtime according to certain conditions.

The structure of the IF Statement in Java is this:

	if (condition)
		sentence;

If the condition is true, the instruction is executed, if not, the instruction is jumped and the execution of the program continues on the next instruction. It can be one or several instructions.


	if (condition){
		sentence1;
		sentence2;
	}

We can use the code of the class "Tutorial5", from the video tutorial, to change the data of the condition and see how it works.

package com.edu4java.tutorial5;

public class Tutorial5 {
	public static void main(String[] args) {
		System.out.println("instruction 1");
		if (3 > 2) {
			System.out.println("instruction 2");
		}
		System.out.println("instruction 3");
		System.out.println("instruction 4");
	}

}

The sentence if...else gives us the possibility to write an alternative for when the condition is false.

	if (condition)
		sentence1;
	else
		sentence2

If the condition is true, sentence1 is executed. The key word "else", means that if the condition is false, then sentence2 is executed.

The structure of the if... else statement is:

	if (condition){
		sentence1;
		sentence2;
	}else{
		sentence3
		sentence4;
		sentence5;
	}
    

In the class "Tutorial5" we can see the code of the example of the video tutorial:

package com.edu4java.tutorial5;

public class Tutorial5 {
	public static void main(String[] args) {
		System.out.println("instruction 1");
		if (1 > 2) {
			System.out.println("instruction 2");
		} else {
			System.out.println("instruction 3");
		}

		System.out.println("instruction 4");
	}

}

These are easy examples. Below we have a more complicated example, which is also explained in the tutorial:

package com.edu4java.tutorial5;

import java.util.Scanner;

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


		Scanner scanner = new Scanner(System.in);
		System.out.print("scanner age:");
		int age = scanner.nextInt();
		if (age >= 18) {
			System.out.println("can drink");
		} else {
			System.out.println("can´t drink");
		}
		System.out.print("print age: ");
		System.out.println(age);
	}

}
<< Previous Next >>