Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Control Structures (Part 1)

 Java Control Structures


 Decision Control Structures Types of Java Control Structures:
 If 1. Decision Control Structures
2. Repetition Control Structures
 If-Else
 If-Else-If
 Switch

Syntax:
Types of Java Decision Control Structures: if ([expression]){
1. If [statement or block of code];
2. If-else }
3. If-else-if or
4. Switch if ([expression]) [statement];

1
Example:
The program prints a message if the final grade of a student exceeds 75%:
Syntax:
public class PassFail1{ if ([expression]){
public static void main (String[] args) [statement1/codeblock1];
{
}
int grade = 85;
else {
if (grade >= 75){ [statement2/codeblock2];
System.out.println("Congratulations!"); }
System.out.println("You Passed!");
or
}
if ([expression]) [statement1];
}
} else [statement2];

Example:
The program prints a message if the final grade of a student exceeds 75%, else
it would print another message if the student fails to exceed 75%:

public class PassFail2{


Syntax:
public static void main (String[] args) if ([expression1]) {
{
[statement1/codeblock1];
int grade = 65; }
if (grade >= 75){
else if ([expression 2]) {
System.out.println("Congratulations!");
System.out.println("You Passed!"); [statement2/codeblock2];
} }
else{
System.out.println("Sorry!"); else {
System.out.println("You failed!"); [statement3/codeblock3];
}
}
}
}

2
Example:
The program prints two separate messages if the final grade of a student
exceeds 85% and 75%, else it would print another message if the student
fails to exceed 75%:
public class PassFail3{ Syntax:
public static void main (String[] args)
switch ([switch expression])
{
{
int grade = 95; case 1:
if (grade >= 85){
[statement1];
System.out.println("Congratulations!");
System.out.println("You Excelled!"); case 2:
} [statement2];
else if (grade >= 75 ){ case n:
System.out.println("Good!");
System.out.println("You Passed!"); [statement];
} default:
else{ ..
System.out.println("Sorry!");
System.out.println("You failed!");
}
}
} What are the differences between switch statements and if statements?
}

Example:
The program prints a message for each corresponding grade rating based
on given grade ranges:
public class PassFail4{
public static void main (String[] args){
char rating;
switch (rating) {
case 'S':
System.out.println("Excellent!");
break;
case 'A':
System.out.println("Good!");
break;
case 'B':
System.out.println("Study Harder!");
break;
default:
System.out.println("You failed!");
break;
}
}
}

3
Computer Programming (JAVA) – Week 5 Page 1 of 2
References

Deitel, H., & Deitel, P. (2004). Java: How to program (early objects). Prentice Hall.

Lambert, K., Osborne, M. (2011). Fundamentals of Java. Cengage Learning Asia Pte Ltd.

Computer Programming (JAVA) – Week 5 Page 2 of 2

You might also like