Java Tutorials - Herong's Tutorial Examples - v8.22, by Herong Yang
"if-then-else" Statements
This section describes 'if-then-else' statements, which is a decision-making statement that executes only one of two its containing block based on the given 'boolean' expression.
What Is "if-then-else" Statement? - An "if-then-else" statement is a decision-making statement that executes only the first contained sub-statement when the given "boolean" expression is "true". Otherwise it executes only the second contained sub-statement.
Here is the syntax for an "if-then-else" statement. Note that "then" is not used a keyword used in the statement at all.
if (condition_expression) first_contained_statement else second_contained_statement
The contained sub-statement can be a simple single statement, or a complex statement block. Here is a sample program that shows you how to use "if-then-else" statements:
/* IfThenElseStatementTest.java * Copyright (c) HerongYang.com. All Rights Reserved. */ import java.time.LocalTime; class IfThenElseStatementTest { public static void main(String[] arg) { java.io.PrintStream out = System.out; LocalTime now = LocalTime.now(); int hour = now.getHour(); // from 0 to 23 out.println("\"if-then-else\" statement with 2 statement blocks:"); if (hour<12) { out.println(" Good morning!"); out.println(" Current time is "+now); } else { out.println(" How are you?"); out.println(" Current time is "+now); } } }
If you compile and run the above program, you will see:
herong> java IfElseStatementTest.java "if-then-else" statement with 2 statement blocks: Good morning! Current time is 09:36:47.356223
Table of Contents
Execution Process, Entry Point, Input and Output
Primitive Data Types and Literals
What Is Control Flow Statement
Nested "if-then-else" Statements
Fall-Through Behavior of "switch" Statements
Bits, Bytes, Bitwise and Shift Operations
Managing Bit Strings in Byte Arrays
Reference Data Types and Variables
StringBuffer - The String Buffer Class
System Properties and Runtime Object Methods
Generic Classes and Parameterized Types
Generic Methods and Type Inference
Lambda Expressions and Method References
Java Modules - Java Package Aggregation
Execution Threads and Multi-Threading Java Programs
ThreadGroup Class and "system" ThreadGroup Tree
Synchronization Technique and Synchronized Code Blocks
Deadlock Condition Example Programs
Garbage Collection and the gc() Method
Assert Statements and -ea" Option