JAVA: Conditionals and Loops

if statement
int x = 7;
if (x < 42) {
    System.out.println("Hello");
}
if…else statement
int age = 30; 
if (age < 16) { 
   System.out.println("Too Young"); 
} else {  
   System.out.println("Welcome!"); 
} 
//Outputs "Welcome!"
else if statement
int age = 25; 
if(age <= 0) { 
   System.out.println("Error"); 
} else if(age <= 16) { 
   System.out.println("Too Young"); 
} else if(age < 100) { 
   System.out.println("Welcome!"); 
} else { 
   System.out.println("Really?"); 
} 
//Outputs "Welcome!"
AND operator
if (age > 18 && money > 500) { 
   System.out.println("Welcome!"); 
}
OR operator
int age = 25; 
int money = 100;  
if (age > 18 || money > 500) { 
   System.out.println("Welcome!"); 
} 
//Outputs "Welcome!"
NOT operator
int age = 25; 
if(!(age > 18)) { 
   System.out.println("Too Young"); 
} else { 
   System.out.println("Welcome"); 
} 
//Outputs "Welcome"
switch statement
int day = 3; 
switch(day) { 
  case 1: 
    System.out.println("Monday"); 
    break; 
  case 2: 
    System.out.println("Tuesday"); 
    break; 
  case 3: 
    System.out.println("Wednesday"); 
    break; 
} 
// Outputs "Wednesday"
default statement
int day = 3; 
switch(day) { 
  case 6: 
    System.out.println("Saturday"); 
    break; 
  case 7: 
    System.out.println("Sunday"); 
    break; 
  default: 
    System.out.println("Weekday"); 
} 
// Outputs "Weekday"
while loops
int x = 3; 
while(x > 0) { 
   System.out.println(x); 
   x--; 
} 
/*  
Outputs 
  3 
  2 
  1 
*/
int x = 6; 
while( x < 8 ) 
{ 
  System.out.println(x); 
  x++; 
} 
System.out.println("Loop ended"); 
/* 
6 
7 
Loop ended 
*/
for loops
for (initialization; condition; increment/decrement) { 
   statement(s) 
}
for(int x=0; x<=4; x=x+2) { 
System.out.println(x); 
} 
/* 
0 
2 
4 
*/
do…while loops
int x = 1; 
do { 
  System.out.println(x); 
  x++; 
} while(x < 4); 
/* 
1 
2 
3 
*/
break statement
int x = 1; 
while(x > 0) { 
 System.out.println(x); 
  if(x == 3) { 
    break; 
  } 
  x++; 
} 
/* Outputs 
1 
2 
3 
*/
continue statement
for(int x=10; x<=40; x=x+10) { 
  if(x == 30) { 
    continue; 
  } 
  System.out.println(x); 
} 
/* Outputs 
  10 
  20 
  40 
*/

About the author: Elegrous

Leave a Reply

Your email address will not be published.


This site uses Akismet to reduce spam. Learn how your comment data is processed.