. Java . Java Control Structures

Java Control Structures

switch (the Java case statement)

//note: shown using char.  
//Primitive types char, byte, short, or int 
//  can be used in the switch.

switch (charToCheck) { case 'A' : System.out.print('A'); break; //Print 'A' if charToCheck = 'A' case 'B' : System.out.print('B'); break; //Print 'B' if charToCheck = 'B' default : System.out.print('D'); //Print 'D' if charToCheck does // not equal 'A' or 'B' }

//note: if neither break were there, // and if charToCheck = 'A', // the code would print ABD

if else

if (x > 5)
{
    System.out.println("x is greater than 5");
}
else
{
    System.out.println("x is not greater than 5");
}

ternary if (boolean?true - return this:false - return this)

public int returnLesser(int x, int y)
{
    return (x < y ? x : y);
}

while (check before loop)

int x = 0;
while (x < 10)  //checks before executing loop
{
    System.out.println(" x < 10 : " + x);
    x++;
}
System.out.println("!(x < 10) : " + x);

do while (check after loop)

int x = 0;
do
{
    System.out.println(" x < 10 : " + x);
    x++;
}
while (x < 10);  
//checks after executing loop 
//  loop is executed at least once
System.out.println("!(x < 10) : " + x);

for loop

int maxX = 10;
for (int x = 0; x < maxX; x++)
//the format is 
//   (initializer; 
//    boolean checked before each loop; 
//    opertaion after each loop)
{
    System.out.println(" x < 10 : " + x);
}

another for loop

int maxX = 10;
int maxY = 15;
for (
      int x = 0, y = 0; 
      (x < maxX) && (y < maxY); 
      x++, y = x * 2
    )
//the format is 
//  (initiaizer, zero or more initialzers of same type; 
//   boolean checked before each loop; 
//   operation after each loop, 
//        zero or more operations after loop)
{
    System.out.println(" x < 10 : " + x);
    System.out.println(" y < 15 : " + y);    
}

break and continue

for (int x = 0; x < 5; x++)  //continue goes to here
{
    System.out.println(" x < 10 : " + x);
    if (x > 5) {continue;}  //goes back to top of loop
    if (x > 10) {break;}    //breaks out of loop
}
//break goes to here

for (int x = 0; x < 5; x++) //outer loop { System.out.println("Outer: " + x); for (int y = 0; y < 5; y++) //inner loop - continue goes back to here { System.out.println("Inner: " + y); if (x > 2) {continue;} //goes back to top of inner loop if (x > 3) {break;} //breaks out of inner loop } //breaks goes back to here, remains in outer loop }
Sign In
to add the first comment for Java Control Structures.