Java If-else Statement
The Java if statement is used to test the condition. It returns true or false. There are various types of if statement in java.
- if statement
- if-else statement
- nested if statement
- if-else-if ladder
Java IF Statement
The if statement tests the condition. It executes the if statement if condition is true.
Syntax:
![if statement in java](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_uqi9WMVWP5CzMhh1DhtR_MpUPMR3CZnbbZ_54RmGqMKjrUGdFdq4b86qTdmREG1VSON9nrWfERcWlJiik2ojBYGd6zUCI3bS8qOu9C71su=s0-d)
Example:
- public class IfExample {
- public static void main(String[] args) {
- int age=20;
- if(age>18){
- System.out.print("Age is greater than 18");
- }
- }
- }
Output:
Java IF-else Statement
The if-else statement also tests the condition. It executes the if block if condition is true otherwise else block.
Syntax:
![if-else statement in java](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_v2oXe6o8dtLf3SRmr4DrRWq2iWOAQss-wOgPtq_udElNgBNpRze_0oAosPsvewkngwEFwM6WaWk3evbPIRw3LFmYzUEHs4_XceciiaCJMl=s0-d)
Example:
- public class IfElseExample {
- public static void main(String[] args) {
- int number=13;
- if(number%2==0){
- System.out.println("even number");
- }else{
- System.out.println("odd number");
- }
- }
- }
Output:
Java IF-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
- if(condition1){
-
- }else if(condition2){
-
- }
- else if(condition3){
-
- }
- ...
- else{
-
- }
![if-else-if ladder statement in java](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_uryQwkyzWpbOaLNxg7IkkefwDwhZLERryo7O9fqwSf2K2p9icXa1RjekwjQbJcQZAu8NKgi3sGC2Qevcq8f30hHbEmewxFTHWibf7MWenLXstO5xncJCSErkU=s0-d)
Example:
- public class IfElseIfExample {
- public static void main(String[] args) {
- int marks=65;
-
- if(marks<50){
- System.out.println("fail");
- }
- else if(marks>=50 && marks<60){
- System.out.println("D grade");
- }
- else if(marks>=60 && marks<70){
- System.out.println("C grade");
- }
- else if(marks>=70 && marks<80){
- System.out.println("B grade");
- }
- else if(marks>=80 && marks<90){
- System.out.println("A grade");
- }else if(marks>=90 && marks<100){
- System.out.println("A+ grade");
- }else{
- System.out.println("Invalid!");
- }
- }
- }
Output:
Output:
No comments:
Post a Comment