-
Notifications
You must be signed in to change notification settings - Fork 1
Decision Making
This week we will learn the basics of decision making in Java. This guide will help you create a program that will act in different ways based on certain conditions using If/Else statements.
The If/Else statement is used by Java to determine whether it should run a line (or lines) of code or not. Once the Java program finds the "If" statement it will check the condition in parenthesis and see if the condition is fulfilled before running the following lines of code.
For example:
> public class IfElse{
> public static void main(String[] args) {
> int x = 5;
> if (x == 5)
> System.out.println("X is 5");
> }
> }
X is 5As seen by the above code, because the condition: if (x == 5) was fulfilled the Java program decided to execute the line: System.out.println("X is 5")
The "Else" statement exist as a means of telling the program to execute some code if the conditions are NOT fulfilled.
For example:
> public class IfElse{
> public static void main(String[] args) {
> int x = 6;
> if (x == 5)
> System.out.println("X is 5");
> else
> System.out.println("X is not 5");
> }
> }
X is not 5Since the condition for If statement was not fulfilled the Java program decided to execute: System.out.println("X is not 5");