Featured Posts
Recent Articles

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

Share and Enjoy:

0 comments for this post

Leave a reply

We will keep You Updated...
Sign up to receive breaking news
as well as receive other site updates!
Subscribe via RSS Feed subscribe to feeds
Recent Stories
Blog Archives
Recent Comments
Tag Cloud