If Statement
Only run code when a condition is true.
1public static void main(String[] args) {
2 boolean isTrue = true;
3 if (isTrue) {
4 System.out.println("isTrue is true");
5 }
6}
$ javac Main.java
$ java Main
isTrue is true
Every line, explained
public static void main(String[] args) {- Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
boolean isTrue = true;- boolean declares a variable that can store only one of two values: true or false. Watch the spelling: in Java the type is boolean; writing bool (like some other languages use) will not compile.
if (isTrue) {- if checks the condition inside its parentheses. If the condition is true, Java runs the code between the { and }. If it is false, Java skips that code completely. Here the condition is simply the variable isTrue, which is true, so the code inside runs.
System.out.println("isTrue is true");- System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line".
}- This } closes the if block.
}- This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.