Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, certification courses.

Created with over a decade of experience and thousands of feedback.

Java Introduction

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output

Java Expressions, Statements and Blocks

Java Flow Control

Java if...else statement.

Java Ternary Operator

  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop

Java break Statement

  • Java continue Statement

Java switch Statement

  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

In programming, we use the if..else statement to run a block of code among more than one alternatives.

For example, assigning grades (A, B, C) based on the percentage obtained by a student.

  • if the percentage is above 90 , assign grade A
  • if the percentage is above 75 , assign grade B
  • if the percentage is above 65 , assign grade C

1. Java if (if-then) Statement

The syntax of an if-then statement is:

Here, condition is a boolean expression such as age >= 18 .

  • if condition evaluates to true , the lines of code inside if are executed
  • if condition evaluates to false , the lines of code inside if are skipped

Working of if Statement

if the number is greater than 0, code inside if block is executed, otherwise code inside if block is skipped

Example 1: Java if Statement

In the program, number < 0 is false . Hence, the code inside the body of the if statement is skipped .

Note: If you want to learn more about about test conditions, visit Java Relational Operators and Java Logical Operators .

We can also use Java Strings as the test condition.

Example 2: Java if with String

In the above example, we are comparing two strings in the if block.

2. Java if...else (if-then-else) Statement

The if statement executes a certain section of code if the test expression is evaluated to true . However, if the test expression is evaluated to false , it does nothing.

In this case, we can use an optional else block. Statements inside the body of else block are executed if the test expression is evaluated to false . This is known as the if-...else statement in Java.

The syntax of the if...else statement is:

Here, the program will do one task (codes inside if block) if the condition is true and another task (codes inside else block) if the condition is false .

How the if...else statement works?

If the condition is true, the code inside the if block is executed, otherwise, code inside the else block is executed

Example 3: Java if...else Statement

In the above example, we have a variable named number . Here, the test expression number > 0 checks if number is greater than 0.

Since the value of the number is 10 , the test expression evaluates to true . Hence code inside the body of if is executed.

Now, change the value of the number to a negative integer. Let's say -5 .

If we run the program with the new value of number , the output will be:

Here, the value of number is -5 . So the test expression evaluates to false . Hence code inside the body of else is executed.

3. Java if...else...if Statement

In Java, we have an if...else...if ladder, that can be used to execute one block of code among multiple other blocks.

Here, if statements are executed from the top towards the bottom. When the test condition is true , codes inside the body of that if block is executed. And, program control jumps outside the if...else...if ladder.

If all test expressions are false , codes inside the body of else are executed.

How the if...else...if ladder works?

If the first test condition if true, code inside first if block is executed, if the second condition is true, block inside second if is executed, and if all conditions are false, the else block is executed

Example 4: Java if...else...if Statement

In the above example, we are checking whether number is positive, negative, or zero . Here, we have two condition expressions:

  • number > 0 - checks if number is greater than 0
  • number < 0 - checks if number is less than 0

Here, the value of number is 0 . So both the conditions evaluate to false . Hence the statement inside the body of else is executed.

Note : Java provides a special operator called ternary operator , which is a kind of shorthand notation of if...else...if statement. To learn about the ternary operator, visit Java Ternary Operator .

4. Java Nested if..else Statement

In Java, it is also possible to use if..else statements inside an if...else statement. It's called the nested if...else statement.

Here's a program to find the largest of 3 numbers using the nested if...else statement.

Example 5: Nested if...else Statement

In the above programs, we have assigned the value of variables ourselves to make this easier.

However, in real-world applications, these values may come from user input data, log files, form submission, etc.

Table of Contents

  • Introduction
  • Java if (if-then) Statement
  • Example: Java if Statement
  • Java if...else (if-then-else) Statement
  • Example: Java if else Statement
  • Java if..else..if Statement
  • Example: Java if..else..if Statement
  • Java Nested if..else Statement

Before we wrap up, let’s put your knowledge of Java if...else (With Examples) to the test! Can you solve the following challenge?

Write a function to check if a student has passed or failed based on the score.

  • If the score is greater than or equal to 50 , return "Pass" . Otherwise, return "Fail" .
  • For example, if score = 55 , the expected output is "Pass" .

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Java Tutorial

Java Language

  • Getting started with Java Language
  • Top 10 Java Errors with Solutions
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • 2D Graphics in Java
  • Alternative Collections
  • Annotations
  • Apache Commons Lang
  • AppDynamics and TIBCO BusinessWorks Instrumentation for Easy Integration
  • Atomic Types
  • Auto-unboxing may lead to NullPointerException
  • Different Cases When Integer and int can be used interchangeably
  • Memory and Computational Overhead of Autoboxing
  • Using Boolean in if statement
  • Using int and Integer interchangeably
  • Basic Control Structures
  • Bit Manipulation
  • BufferedWriter
  • Bytecode Modification
  • C++ Comparison
  • Calendar and its Subclasses
  • Character encoding
  • Choosing Collections
  • Class - Java Reflection
  • Classes and Objects
  • Classloaders
  • Collection Factory Methods
  • Collections
  • Command line Argument Processing
  • Common Java Pitfalls
  • Comparable and Comparator
  • CompletableFuture
  • Concurrent Collections
  • Concurrent Programming (Threads)
  • Console I/O
  • Constructors
  • Converting to and from Strings
  • Creating Images Programmatically
  • Currency and Money
  • Dates and Time (java.time.*)
  • Default Methods
  • Dequeue Interface
  • Disassembling and Decompiling
  • Documenting Java Code
  • Dynamic Method Dispatch
  • Encapsulation
  • Enum starting with number
  • EnumSet class
  • Exceptions and exception handling
  • Executor, ExecutorService and Thread pools
  • Expressions
  • FileUpload to AWS
  • Fluent Interface
  • FTP (File Transfer Protocol)
  • Functional Interfaces
  • Generating Java Code
  • Getters and Setters
  • HttpURLConnection
  • Immutable Class
  • Immutable Objects
  • Inheritance
  • InputStreams and OutputStreams
  • Installing Java (Standard Edition)
  • Iterator and Iterable
  • Java Agents
  • Java Compiler - 'javac'
  • Java deployment
  • Java Editions, Versions, Releases and Distributions
  • Java Floating Point Operations
  • Java Memory Management
  • Java Memory Model
  • Java Native Access
  • Java Native Interface
  • Java Performance Tuning
  • Java Pitfalls - Exception usage
  • Java Pitfalls - Language syntax
  • Java Pitfalls - Nulls and NullPointerException
  • Java Pitfalls - Performance Issues
  • Java Pitfalls - Threads and Concurrency
  • Java plugin system implementations
  • Java Print Service
  • Java SE 7 Features
  • Java SE 8 Features
  • Java Sockets
  • Java Virtual Machine (JVM)
  • JSON in Java
  • Just in Time (JIT) compiler
  • JVM Tool Interface
  • Lambda Expressions
  • LinkedHashMap
  • List vs SET
  • Local Inner Class
  • Localization and Internationalization
  • log4j / log4j2
  • Logging (java.util.logging)
  • Multi-Release JAR Files
  • Nashorn JavaScript engine
  • Nested and Inner Classes
  • New File I/O
  • NIO - Networking
  • Non-Access Modifiers
  • NumberFormat
  • Object Class Methods and Constructor
  • Object Cloning
  • Object References
  • Oracle Official Code Standard
  • Parallel programming with Fork/Join framework
  • Polymorphism
  • Preferences
  • Primitive Data Types
  • Properties Class
  • Queues and Deques
  • Random Number Generation
  • Readers and Writers
  • Reference Data Types
  • Reference Types
  • Reflection API
  • Regular Expressions
  • Remote Method Invocation (RMI)
  • Resources (on classpath)
  • RSA Encryption
  • Runtime Commands
  • Secure objects
  • Security & Cryptography
  • SecurityManager
  • Serialization
  • ServiceLoader
  • Splitting a string into fixed length parts
  • Stack-Walking API
  • String Tokenizer
  • StringBuffer
  • StringBuilder
  • sun.misc.Unsafe
  • super keyword
  • The Classpath
  • The Java Command - 'java' and 'javaw'
  • The java.util.Objects Class
  • ThreadLocal
  • TreeMap and TreeSet
  • Type Conversion
  • Unit Testing
  • Using Other Scripting Languages in Java
  • Using the static keyword
  • Using ThreadPoolExecutor in MultiThreaded applications.
  • Varargs (Variable Argument)
  • Visibility (controlling access to members of a class)
  • WeakHashMap
  • XML Parsing using the JAXP APIs
  • XML XPath Evaluation
  • XOM - XML Object Model

Java Language Autoboxing Using Boolean in if statement

Fastest entity framework extensions.

Due to auto unboxing, one can use a Boolean in an if statement:

That works for while , do while and the condition in the for statements as well.

Note that, if the Boolean is null , a NullPointerException will be thrown in the conversion.

Got any Java Language Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

IMAGES

  1. Java if...else (With Examples)

    java boolean assignment in if condition

  2. [Solved] if (boolean condition) in Java

    java boolean assignment in if condition

  3. How to Java: Boolean Opterators & if / else

    java boolean assignment in if condition

  4. Beginners Java, Lesson 6, Simple if statements and boolean variables

    java boolean assignment in if condition

  5. Booleans in Java explained

    java boolean assignment in if condition

  6. If Statement in Java with Example

    java boolean assignment in if condition

VIDEO

  1. The boolean Data Type in Java

  2. Boolean Java Tutorial #15

  3. Java For Beginners: Boolean Operators & IF Statement (4/10)

  4. 14 if else in Java

  5. 21

  6. Java if statements 🚧【6 minutes】