Control Flow
Your code is usually executed from top to bottom. Control flow statements changes the flow of a program depending on a condition. There are 3 control flow statements.
Decision-making statements
if statement
Ex.
int wheels = 4; //declare and assign wheels to 4.
if (wheels == 4) {
System.out.println(“It is a car”); //executes this if wheel is 4.
}else if (wheels == 2){
System.out.println(“It is a bicycle”); //executes this if wheel is 2.
}else if (wheels == 1){
System.out.println(“It is a unicycle”);// executes this if wheel is 1.
}else{
System.out.println(“It is another vehicle”); //executes this if no other conditions are met.
}
Note: else if and else are optional.
In this example, we used the == equality operator rather than the assignment operator = to test for conditions.
Switch Statements – Switch statement works with:
Primitive data types
Enumerated types
Few classes like Integers, etc.
Ex.
int wheels = 4;
switch (wheels){
case 1: System.out.println(“unicycle”); break;
case 2: System.out.println(“bicycle”); break;
case 3: System.out.println(“tri-cycle”);break;
case 4: System.out.println(“car”);break;
default: System.out.println(“another vehicle”);
}
Example of Enumerated Types, Switch Statement
import java.lang.*;
public class enumVehicle{
enum Wheels{
ONE,TWO,FOUR //assign fixed set of constants.
}
Wheels wheels; //declare wheels variable having Wheels enum.
public enumVehicle(Wheels wheels){ //create constructor
this.wheels = wheels; //initializes variable
}
public void whatVehicle(){
switch(wheels){
case ONE: System.out.println("unicycle");break; //prints unicycle since we pass Wheels.ONE to constructor and assign it to wheels.
case TWO: System.out.println("bicycle");break;
case FOUR: System.out.println("car");break;
default: System.out.println("another vehicle");
}
}
public static void main(String[] args){
enumVehicle vehicle1 = new enumVehicle(Wheels.ONE); //execute constructor enumVehicle and assign Wheels.ONE to wheels.
vehicle1.whatVehicle(); //call whatVehicle method and print “unicycle.”
enumVehicle vehicle2 = new enumVehicle(Wheels.FOUR); //execute constructor enumVehicle and assign Wheels.FOUR to wheels.
vehicle2.whatVehicle(); //call whatVehicle method and print “car.”
}
}
to be continued...
No comments:
Post a Comment