Home » Data Structures using Java »
Sample Code of if-then and if-then-else Statements in Java
The if-then Statement
void applyBrakes(){
if (isMoving){ // the "if" clause: bicycle must moving
currentSpeed--; // the "then" clause: decrease current speed
}
}
void applyBrakes(){
if (isMoving) currentSpeed--; // same as above, but without braces
}
The if-then-else Statement
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
The output from the program is:
Grade = C
Related posts:
If you enjoyed this article, subscribe to receive more great content just like it.
Disclaimer
Labels
- Computer Tips and Tricks (8)
- Content Management System (1)
- Data Structures using Java (15)
- Database Management Systems (2)
- File Formats (7)
- Gadgets Reviews (2)
- Games Reviews (2)
- hardware (16)
- Internet Terms (7)
- Management Information System (5)
- networking (8)
- Programming (15)
- sofware (17)
- Tech News (4)
- Web Design (4)
0 comments for this post
Leave a reply