0% found this document useful (0 votes)
18 views10 pages

Haha 2

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views10 pages

Haha 2

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Decision Making in Java (if, if-else, switch, break, continue, jump)
Java if statement with Examples
Java if-else
Java if-else-if ladder with Examples
Loops in Java
For Loop in Java
Java while loop with Examples
Java do-while loop with Examples
For-each loop in Java
Continue Statement in Java
Break statement in Java
Usage of Break keyword in Java
return keyword in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
Java if statement with Examples
Last Updated : 22 Mar, 2023
Decision Making in Java helps to write decision-driven statements and execute a
particular set of code based on certain conditions.
The Java if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or not
i.e if a certain condition is true then a block of statement is executed otherwise
not.

Syntax:

if(condition)
{
// Statements to execute if
// condition is true
}
Working of if statement:

Control falls into the if block.


The flow jumps to Condition.
Condition is tested.
If Condition yields true, goto Step 4.
If Condition yields false, goto Step 5.
The if-block or the body inside the if is executed.
Flow steps out of the if block.
Flowchart if statement:

Operation: The condition after evaluation of if-statement will be either true or


false. The if statement in Java accepts boolean values and if the value is true
then it will execute the block of statements under it.

Note: If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then
by default if statement will consider the immediate one statement to be inside its
block.

For example:

if(condition)
statement1;
statement2;

// Here if the condition is true, if block will consider the statement


// under it, i.e statement1, and statement2 will not be considered in the if block,
it will still be executed
// as it is not affected by any if condition.
Example 1:

// Java program to illustrate If statement

class IfDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("10 is less than 15");

System.out.println("Outside if-block");
// both statements will be printed
}
}
Output
10 is less than 15
Outside if-block
Time Complexity: O(1)

Auxiliary Space: O(1)

Dry-Running Example 1:

1. Program starts.
2. i is initialized to 10.
3. if-condition is checked. 10<15, yields true.
3.a) "10 is less than 15" gets printed.
4. "Outside if-block" is printed.
Example 2:

// Java program to illustrate If statement

class IfDemo {
public static void main(String args[])
{
String str = "GeeksforGeeks";
int i = 4;

// if block
if (i == 4) {
i++;
System.out.println(str);
}

// Executed by default
System.out.println("i = " + i);
}
}
Output
GeeksforGeeks
i = 5
Time Complexity: O(1)
Auxiliary Space: O(1)

Example no 3: (Implementing if else for Boolean values)


Input -

boolean a = true;
boolean b = false;
Program –

public class IfElseExample {


public static void main(String[] args) {
boolean a = true;
boolean b = false;

if (a) {
System.out.println("a is true");
} else {
System.out.println("a is false");
}

if (b) {
System.out.println("b is true");
} else {
System.out.println("b is false");
}
}
}
Output
a is true
b is false
Explanation-
The code above demonstrates how to use an if-else statement in Java with Boolean
values.
The code starts with the declaration of two Boolean variables a and b, with a set
to true and b set to false.
The first if-else statement checks the value of a. If the value of a is true, the
code inside the first set of curly braces {} is executed and the message “a is
true” is printed to the console. If the value of a is false, the code inside the
second set of curly braces {} is executed and the message “a is false” is printed
to the console.
The second if-else statement checks the value of b in the same way. If the value of
b is true, the message “b is true” is printed to the console. If the value of b is
false, the message “b is false” is printed to the console.
This code demonstrates how to use an if-else statement to make decisions based on
Boolean values. By using an if-else statement, you can control the flow of your
program and execute code only under certain conditions. The use of Boolean values
in an if-else statement provides a simple and flexible way to make these decisions.
Advantages of If else statement –
The if-else statement has several advantages in programming, including:
Conditional execution: The if-else statement allows code to be executed
conditionally based on the result of a Boolean expression. This provides a way to
make decisions and control the flow of a program based on different inputs and
conditions.
Readability: The if-else statement makes code more readable by clearly indicating
when a particular block of code should be executed. This makes it easier for others
to understand and maintain the code.
Reusability: By using if-else statements, developers can write code that can be
reused in different parts of the program. This reduces the amount of code that
needs to be written and maintained, making the development process more efficient.
Debugging: The if-else statement can help simplify the debugging process by making
it easier to trace problems in the code. By clearly indicating when a particular
block of code should be executed, it becomes easier to determine why a particular
piece of code is not working as expected.
Flexibility: The if-else statement provides a flexible way to control the flow of a
program. It allows developers to handle different scenarios and respond dynamically
to changes in the program’s inputs.
Overall, the if-else statement is a fundamental tool in programming that provides a
way to control the flow of a program based on conditions. It helps to improve the
readability, reusability, debuggability, and flexibility of the code.

Related Articles:

Decision Making in Java


Java if-else statement with Examples
Java if-else-if ladder with Examples
Switch Statement in Java
Break statement in Java
return keyword in Java

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

Chinmoy Lenka

68
Previous Article
Decision Making in Java (if, if-else, switch, break, continue, jump)
Next Article
Java if-else
Read More
Down Arrow
Similar Reads
return statement in C++ with Examples
Pre-requisite: Functions in C++ The return statement returns the flow of the
execution to the function from where it is called. This statement does not
mandatorily need any conditional statements. As soon as the statement is executed,
the flow of the program stops immediately and returns the control from where it was
called. The return statement ma
4 min read
Break and Continue statement in Java
The break and continue statements are the jump statements that are used to skip
some statements inside the loop or terminate the loop immediately without checking
the test expression. These statements can be used inside any loops such as for,
while, do-while loop. Break: The break statement in java is used to terminate from
the loop immediately. Wh
5 min read
Continue Statement in Java
Suppose a person wants code to execute for the values as per the code is designed
to be executed but forcefully the same user wants to skip out the execution for
which code should have been executed as designed above but will not as per the
demand of the user. In simpler words, it is a decision-making problem as per the
demand of the user. Real-Lif
6 min read
How to Use Callable Statement in Java to Call Stored Procedure?
The CallableStatement of JDBC API is used to call a stored procedure. A Callable
statement can have output parameters, input parameters, or both. The prepareCall()
method of connection interface will be used to create CallableStatement object.
Following are the steps to use Callable Statement in Java to call Stored Procedure:
1) Load MySQL driver a
2 min read
Import Statement in Java
Import statement in Java is helpful to take a class or all classes visible for a
program specified under a package, with the help of a single statement. It is
pretty beneficial as the programmer do not require to write the entire class
definition. Hence, it improves the readability of the program. This article focuses
on the import statements used
8 min read
Unreachable statement using final and non-final variable in Java
Unreachable statements in Java refers to those sets of statements that won't get
executed during the execution of the program are called Unreachable Statements.
These statements might be unreachable because of the following reasons which are as
follows: Have a return statement before themHave an infinite loop before
themExecution forcibly terminate
4 min read
Library Management System Using Switch Statement in Java
Here we are supposed to design and implement a simple library management system
using a switch statement in Java, where have operated the following operations Add
a new book, Check Out a book, display specific book status, search specific book,
and display book details using different classes. Follow the given link to build
the Library Management S
9 min read
Enhancements for Switch Statement in Java 13
Java 12 improved the traditional switch statement and made it more useful. Java 13
further introduced new features. Before going into the details of new features,
let's have a look at the drawbacks faced by the traditional Switch statement.
Problems in Traditional Switch1. Default fall through due to missing break:The
default fall-through behavior
5 min read
Break statement in Java
Break Statement is a loop control statement that is used to terminate the loop. As
soon as the break statement is encountered from within a loop, the loop iterations
stop there, and control returns from the loop immediately to the first statement
after the loop. Syntax: break;Basically, break statements are used in situations
when we are not sure
3 min read
goto Statement in C
The C goto statement is a jump statement which is sometimes also referred to as an
unconditional jump statement. The goto statement can be used to jump from anywhere
to anywhere within a function. Syntax: Syntax1 | Syntax2
---------------------------- goto label; | label: . | . . | . . | . label: | goto
label; In the above syntax, the first line te
3 min read
Article Tags :
Java
Misc
School Programming
java-basics
Practice Tags :
Java
Misc
three90RightbarBannerImg

course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Avail 90% Refund
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund

geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like