Go back
Nested Statements
Subscribe to Tech with Tim
YouTube
Nesting Statements
The concept of nesting is quite trivial. Yet, many beginners do not recognize that it is possible. Nesting is simply placing statements within other statements. An example of nesting can be seen below.
public class Main { public static void main (String[] args){ int x = 5; int y = 6; if (x == 5){ System.out.println("X is 5"); // These statements are only checked if x == 5 if (y == 6){ System.out.println("Y is 6"); } else{ System.out.println("Y is not 6"); } } } }
Example Program
To bring all of the topics we've learned so far I have created an example program for you to have a look at.
import java.util.Scanner; public class Main { public static void main (String[] args){ System.out.print("Input your age: "); // Notice the lack of "ln", this makes our input come in on the same line as our printed text Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int age = Integer.parseInt(s); if (age >= 18){ System.out.println("Are you a senior citizen (yes/no)? "); String senior = sc.nextLine(); if (senior.equals("yes") || senior.equals("y")){ System.out.println("You are 65+ years old"); }else { System.out.println("You are less than 65 years old"); } }else if(age >= 13){ System.out.println("You are a teenager"); }else{ System.out.println("You are younger than 13"); } } }
IntroductionVariables & Data TypesOperatorsInput and ScannersConditions and BooleansIF/ELSE/ELSE IFNested StatementsArraysFor LoopsFor Loops(Continued)While LoopsSets and ListsMaps & HashMapsMaps ExampleIntroduction to ObjectsCreating ClassesInheritanceStatic KeywordInner ClassesInterfacesEnumsOverloading Methods