If Statements
An if statement allows us to do something only if some condition is true.
If statement syntax
Here is the syntax for an if statement:
if (condition)
{
//statements
}Here, condition is either a boolean variable or an expression that evaluates to true or false.
The statements inside the if- tatement are things that we ONLY want to happen if our
condition is true. Finally, the brackets {} around the body are optional if there is only one
statement inside.
If statement example
For example, suppose we want to get the user’s name and age as input. In any case, we want to then print out a greeting. We also want to print “You are an adult” if the user is 18 or older.
Here is the full program:
import java.util.*;
public class HelloAdult
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = s.nextLine();
System.out.print("Enter your age: ");
int age = s.nextInt();
System.out.printf("Hello, %s%n", name);
if (age >= 18)
{
System.out.println("You are an adult");
}
}
}When the program runs, it will ask the user for their name and age and read those values into the
name and age variables. It will then print Hello and the person’s name. Finally, if the person is
18 or older, the program will print “You are an adult”. If the user is under 18, the program will
not print the “You are an adult” line.