search
HomeJavajavaTutorialElse-If Statement in Java

Else-If Statement in Java

Aug 30, 2024 pm 03:23 PM
java

Conditional statements used to check if a block of code is to be executed or not is called else-if statements. If a specified condition is true, it is executed or executes the condition given in the else block of the code. This block code is used to test if a condition is true or not so that the following codes can be executed. Else statement block is optional. Also, there is if-else-if statements and nested if statements. Only one else can be used with an if condition. This is one of the basic statements in any programming language.

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The syntax generally used for the Else If the statement is like a ladder where if one statement is not executed, the other statement is executed. If the multiple checks do not execute all the Else If statements, the Else statement is finally executed, giving a specific output. The syntax of the Else If statement is given below:

Code:

if(condition1)
{
//Specific code to be run if the Condition 1 is true according to the program.
}
else if(condition2)
{
// Specific code to be run if the Condition 2 is true according to the program
}
else if(condition3)
{
// Specific code to be run if the Condition 3 is true according to the program
}
...
else
{
// Specific code to be run if the Condition n is true according to the program false
}

In the above syntax, we notice that if none of the conditions is executed, then the final Else statement is executed, which is the nth condition. The syntax is extremely similar to the If statement. The difference is that there are multiple Ifs in the Else If statement.

Flowchart of Else-If Statement in Java

The flowchart of the Else If statement is very similar to the If statement. We can check the working of the Else If statement with a flowchart. As shown in the diagram, if the Condition 1 is false, then the Condition 2 is executed. If that is also false, then the Condition 3 is executed, and so on.
On the other hand, if the condition 1 is true, then Statement 1 is executed. Also, if Condition 1 is false, then it moves to Condition 2, and if the Condition 2 is true, then Statement 2 is executed.

Else-If Statement in Java

Examples of Else-If Statement in Java

Here are the following examples of Else-If Statement in Java mention below

Example #1

In the first coding example, we are going to enter a number and check whether it is positive, negative or zero. We used the Else if ladder in this case and check the behavior of the number. It is a very basic program, finding the nature of the number.

Code:

import java.io.*;
public class PositiveNegativeExample
{
public static void main(String[] args)throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number");
int n= Integer.parseInt(br.readLine());
if(n>0)
{
System.out.println("The number is POSITIVE");
}
else if(n
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500260431087.png?x-oss-process=image/resize,p_40" class="lazy" alt="Else-If Statement in Java" ></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500260571553.png?x-oss-process=image/resize,p_40" class="lazy" alt="Else-If Statement in Java" ></p>
<p>In the coding example 1. we first input 36 as the number, and then we enter 0 as a number. We get the perfect output, respectively. When we enter 36 as the number, we get the output that the number is positive. Again, we enter a number as zero, and then we get the output that the number is zero.</p>


<h4 id="Example">Example #2</h4>
<p>In this coding example, we check the Else If statement’s functioning, and we see whether a person is eligible to donate blood or not. We do not use Buffered Reader for the input of the two variables.  We directly input them into the program, and we get the result as desired.</p>
<p>Java Program to illustrate the working of Else If Statement</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">public class Age
{
public static void main(String[] args)
{
//Here the variable a is age and w is weight
int a=25;//Age
int w=48;// Weight
//Generating condition on age and weight
if(a>=18){
if(w>50)
{
System.out.println("You are eligible to donate blood");
} else
{
System.out.println("You are not eligible to donate blood");
}
} else
{
System.out.println("Age must be greater than 18");
}
}
}

Output:

Else-If Statement in Java

In the sample code, we input the age as 25 and weight as 48, and we execute the program accordingly. The age is greater than 18, so it satisfies the condition to donate blood. However, the weight is less than 50, which is required in the program, so the program rejects the person to donate blood.

Example #3

In this program, we check the grade of a student according to the marks entered by the user. The grades are Fail, D, C, B, A, and A+.

Java Program to check the grade of a student in a particular exam as entered by the user.

Code:

import java.io.*;
public class Exam
{
public static void main(String[] args)throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter marks of the student in the exam");
int m=Integer.parseInt(br.readLine());
if(m=50 && m=60 && m=70 && m=80 && m=90 && m
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500260982183.png?x-oss-process=image/resize,p_40" class="lazy" alt="Else-If Statement in Java" ></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500261098331.png?x-oss-process=image/resize,p_40" class="lazy" alt="Else-If Statement in Java" ></p>
<p>From the program, we enter 65 and 80 as the numbers. The program successively returns that the student has got a C grade and A grade in the exam, respectively.</p><h3 id="Conclusion">Conclusion</h3>
<p>In this article, we check the functionality of the Else If statement in Java, and we see that it is nothing but a multiple If statement which is used in all the programs. We also see three coding examples that enlighten the function of the Else if statement very elaborately. All the programs use Else If statements extensively and print the output in a fashion desired by the user. Further, Else if statement is used wherever there are multiple conditions to be checked. They are used in all programming languages.</p>

The above is the detailed content of Else-If Statement in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools