public class ControlStructures { /** * @param args */ public static void main(String[] args) { /* * How can we build boolean expressions ? * a. Use boolean literals * b. Use relational operators and * c. Use method calls * */ boolean programStarted=true; if(programStarted) System.out.println("Program has started"); int a=5; int b=10; int dummy=0; if(a>b){ System.out.println("a="+a+" is larger than b="+b); } System.out.println("You need to use braces if you have multiple conditional statements"); if(a>b) dummy=dummy+1; System.out.println("a="+a+" is larger than b="+b); if(a>b){ dummy=dummy+1; System.out.println("a="+a+" is larger than b="+b); } // braces serve to group statements. The build the body of the conditional statement. String sentence="John goes to the school."; if(sentence.startsWith("John")){ System.out.println("We are talking about John."); } else{ System.out.println("We are talking about someone else."); } /* * if ... else if... else * * */ int c=40; if(c<20){ System.out.println("c is less than 20"); } else if(c<50){ System.out.println("c is (larger or equal) than 20 and is less than 50"); } else if(c<60){ System.out.println("c is (larger or equal) than 50 and is less than 60"); } else{ System.out.println("c is larger than 60"); } if(c<20){ System.out.println("c is less than 20"); } if(c<50){ System.out.println("c is less than 50"); } if(c<60){ System.out.println("c is less than 60"); } /* * * Nested if statements * Each entered if-branch provides us with additional information * Nested if statements provides step-by-step refinement of the condition. Thus they make code more readable. */ int d=40; if(d<50){ if(d>=30){ System.out.println("d is less than 50 and (equal or greater) than 30"); } else{ System.out.println("d is less than 50 and is less than 30. This means it is less than 30"); } } if(d<50 && d>=30){ System.out.println("d is less than 50 and (equal or greater) than 30"); } else{ System.out.println("d is less than 50 and is less than 30. This means it is less than 30"); } /* * * To compare Strings use equals * */ String x="Car"; // if(x==args[0]){ // System.out.println("The value of the string variable is \"Car\""); // } // else{ // System.out.println("The value of the string variable is not \"Car\""); // } // // if(x.equals(args[0])){ // System.out.println("The value of the string variable is \"Car\""); // } // else{ // System.out.println("The value of the string variable is not \"Car\""); // } } }