Pages

Monday, December 26, 2022

Else if Condition Statement Program | Java Tutorial for Beginners


If there is two condition we use if else but if condition is more than one? well we can use else if. So we will learn how else if condition is used in java with example. If you want to watch video tutorial about how to use else if in Java , below videos are available in English and in Hindi languages. 

Here is scenario 

Write Java program of where if food is warm print out food is perfect , if food is cold print "could you warm please" and for any other option print "I will wait"

Java Else if video tutorial in English


Java Else IF Statement Video Tutorial in Hindi



Now lets create class, 




As we can observe in code we have created class name ElseIF and inside this class we created method name myElseIfMethod . We do not want to return but just would like to print as a result we are using void. In side curly brace we want to write our logic . 

Now lets create variable and data type is string and name of variable is food and we set to warm for now . we will change it later to see how it will be in output. 

Now we will use if condition so we use if and inside bracket we will specify our condition . In last tutorial we used double equal sign to compare and in this tutorial we are using dot equal to as shown in the code.  we are comparing if food is warm then , system will run that block of code which is food is perfect.  

But if food is cold then? we will write different logic for that . Now we will type else if and again in bracket we are specifying condition that if food is cold then we will print out please warm food 

And other than that , we will print out I will wait .  This is how if we have more than two condition we can use else if condition. You can change variable to cold , warm and other and check out put . 

Code 

public class ElseIF {

public void myElseIFMethod(){

String food= "warm";

if(food.equals("warm")){

System.out.println("Food is perfect");

}

else if(food.equals("cold")){

System.out.println("could you warm it please..");

}

else{

System.out.println("I will wait .....");

}

}

Now lets create object in main method . To create object on main method first type name of class then create provide name of variable and then equal sign , new and once again name of class and bracket. If you type variable and dot it will provide you accessible methods , select method which we created, run and check in the output. 

If you want to learn more step by step java tutorial for beginners here is link . 

https://www.youtube.com/channel/UC6nXbd7cjO2QE_pnP81MjTw