Java Tutorial Index

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse Program to find and replace characters on string in java Program to find the duplicate characters in a string Program to check whether a given character is present in a string or not Java Program to Print Permutations of String Java program to find frequency of characters in a string Java Program to remove duplicate characters in a string

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Methods in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java file Reader Java Buffer Reader Java file Writer Java BufferedWriter Java InputStreamReader Scanner in Java Java StringReader Java StringReader Class Java StringWriter Class Java PrintWriter Java File Java Read File Line By Line Java FileInputStream Java FileOutputStream Java Create File Java Delete File Java Open File Java Read File to String Java copy file Jar File in Java Java FileNotFoundException

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java Deque in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial JDBC Architecture Types of JDBC Drivers JDBC vs ODBC Java Database Connectivity with MySQL Java Database Connectivity with Oracle Statements in java Prepared statement in Java Resultset in java Java ResultSetMetaData DatabaseMetaData in Java Callable Statement in Java Transaction Management in Java Design of JDBC

Java Differences

Java vs DotNET Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Java float vs double Java vs Scala Java vs Go Java vs Golang Java Extends vs Implements Java vs Node.js Static vs Non-static in Java C vs Java int vs Integer in Java Java protected vs private Java vs Dot Net Stack vs Heap in Java Java Array vs ArrayList Java SE vs EE Class vs Object in Java Java vs Bedrock Difference between = = and equals ( ) in java Difference between C, C++, java HashMap Vs HashTable Checked vs Unchecked Exceptions in Java Difference between print() and println() in Java Differences between Lock and Monitor in Java Concurrency Differences between Set and List in Java How to calculate time difference in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Difference between String and Char Array in Java Differences between Byte Code and Machine Code Difference between String Tokenizer and split Method in Java Difference between JIT and JVM in Java Difference Between Data Hiding and Abstraction in Java Difference between String Tokenizer and Split Method in Java Difference Between BufferedReader and FileReader Difference Between Thread.start() and Thread.run()

How to

How to convert String to String array in Java How to find length of integer in Java How to get Day Name from Date in Java How to open the Java control panel How to resolve Illegal state exceptions in Java How to reverse a linked list in java How to encrypt password in Java How to calculate time complexity of any program in Java How to check version of java in Linux How to enable java in chrome How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to add double quotes in a string in Java How to convert list to String in Java How to call a method in Java How to Set Environment Variables for Java How to sort an array in Java How to Create Immutable Classes in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to Create Singleton Class in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to find the length of an Array in Java How to Read Java JSON file How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to import packages in Java How to run applet Program in Java How to take Array Input in Java How to achieve abstraction in Java How to call static method in Java How to compare characters in Java How to compare dates in Java How to create a linked list in Java How to download Eclipse for Java How to get ASCII value of char in Java How to get the current date and time in Java How to handle NullPointerException in Java How to initialize string array in Java How to Install Java on MAC How to run java program in ubuntu How to find characters with the maximum number of times in a string java How to Set Java_home in Linux How to Split the String in Java with Delimiter How to take Multiple String Input in Java using Scanner class How to uninstall the Java in Ubuntu How to Update Java How to add Elements in Array in Java How to avoid deadlock in java How to Split String by Comma in Java How to remove special characters from String in Java How to remove last character from String in Java How to Read XML Files in Java How to download and install Eclipse in Windows How to Create an API in Java How to Round Double Float up to Two Decimal Places in Java How to create a mirror image of a 2D array in Java How to set timer in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Type Annotations in Java Java Stringjoiner Class Parallel Arrays Sort in Java Bifunction in java 8 Java 8 filters list Java 8 Consumer Interface in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java 12

What’s new in Java 12

Java 13

Java 13 New Features

Java 14

New Features of Java 14

Java 15

What’s New in Java 15

Java 16

Java 16

Java 17

What is new in Java 17

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hiberate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial Jenkins java net socket connection time out

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.fma() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

List all files in a Directory in Java Nonagonal number in Java Null Pointer Exception in Java Package naming convention in Java Packages Program in java Pangram Program in Java PriorityBlockingQueue Class in Java Race Condition in Java Repdigit Numbers in Java Reserved Keywords in Java Rotate matrix by 90 degrees in Java Segment Tree in Java Sierpinski Number in Java Sort Dates in Java Thread Safety and How to Achieve it in Java Normal and Trace of a Matrix in Java Transient variable in Java Tribonacci series in Java Web Crawler in Java Zigzag Traversal of Binary Tree in Java Java Full Stack Java IO filenotfoundexception Java Output Formatting Java Plot Java Pop Java program to print matrix in Z form Java Set to List Java Switch string Java Thread Lifecycle: States and Stages Java Viva Questions and Answers Lazy Propagation in Segment Tree in Java Level order Traversal of a Binary Tree in Java Method chaining in Java Narcissistic Number in Java Java Case Keyword Java Try-Catch Block Java Class KeywordJava concurrency interview questions Java Continue Keyword Java CountDownLatch Java Default Keyword Java Double Keyword Java Editors Java Else Keyword Java Enum Keyword Java Extends keywordJava Finally Keyword Java Font Example of Static import in Java How Many Ways to Create Objects in Java Implementing Queue Using Array in Java Instanceof operator in Java Interchange Diagonal elements in Java Java Arrays Fill Java Char Keyword Convert list to array Java Convert milliseconds to date in Java Copy data/content from one file to another in java CRC Program in Java Creating a Jar file in Java Crown Pattern in Java Difference Between Access Specifiers and Modifiers in Java Difference Between Java and PHP Difference Between replace() and replaceall() in Java Duodecimal in Java Finding middle node of a linked list in Java Group by in Java 8 Hollow Diamond Pattern in Java How annotations work in Java Java Boyer Moore Catalan number in Java Cosmic Superclass in Java Difference between this and super in Java Fall through in Java Figurate Number in Java Java Anon Proxy Java RMI Lazy loading in Java Magnanimous Number in java Shallow copy in Java String to JSON in Java Tetranacci Number in Java Vigesimal in Java Why main method is static in Java Add Time in Java Bellman Ford Algorithm in Java Best Java Libraries Blockchain in Java Blocking Queue in Java Example Bully Algorithm code in Java Contextual keywords in Java Convert JSON File to String in Java Determine the Upper Bound of a Two-Dimensional Array in Java Java.net.ConnectionException Java.net.SocketException Web Service Response Time Calculation in Java Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java Convert Char array to string in java Check whether Java is installed or not How to stop execution after a certain time in Java Jagged Array in Java Java ArraylistRemove() Time Complexity Java Swing Time Picker Zigzag Array in Java Array and String based questions in Java Array and String with Examples in Java Best Practices to use String Class in Java What is string in Java why it's immutable Java String Java String Inbuilt functions Java String Matches vs Contains Sum of digits in string in java Check the presence of Substring in a String in java Java import packages Interfaces and Classes in Strings in Java Maximum length of string in java Hidden classes in Java Class memory in Java public static void main string args meaning in java Reverse a String in Java String Concatenation in Java Buffer reader to read string in Java Split String into String Array in Java Reverse a String using Collections in Java Upcasting and Downcasting in Java String Declaration in Java Method Overloading In Java Java Solid Principles Java Architecture Binary Search Java Star Program in Java Java Type Casting Java Pass-by-Reference Java Framework List Java Destructors Java Control Statements Java Byte Code Java Beans Java Identifiers Character Array in Java Java Applications Java Substring Java Session Non-primitive data types in Java Matrix Multiplication in Java JIT in Java Java Tokens Java Externalization Default Virtual Behaviour in C++ vs Java Why we use static in Java Session Tracking in Java Knapsack problem in Java Java Logo Java exception list Java Iterator Java instance variable Frugal number in Java Fork Join in Java Date time API in java Compile time vs Runtime in java Compare time in java AES 256 Encryption in Java Advanced Java skills What is advance Java? User Defined Exception in Java Upcasting in Java Tree Implementation in Java Special Operators in Java Reentrant Lock in Java Perfect Number in Java Java logger Java LinkedList vs ArrayList File Operation in Java Constructor Overloading in Java Conditional operator in Java Concurrent Linked Deque in Java with Examples Command Class in Java Java Break Keyword Best Java IDE Association in Java Access specifiers in Java AbstractSet Class in Java Adapter class in Java Composition in Java Mutable and Immutable in Java Static() Function in Java Traverse through HashMap in Java Vectors in Java Creation of Multi Thread in java Java Enumeration Compile-time Error in Java Java Get Time in UTC Java.sql.Time Format Structure of Java Program Thread Concept in Java Creation of Multi-Thread in Java Enterprise Java Beans POJO in Java Volatile keyword in Java Java Constant Collection Interfaces in Java with Examples Deadlock Prevention and avoidance in Java Java Boolean Keyword Java Byte Keyword Java List Implementations Java Xml Parser Method Overriding in Java RMI program in Java Virtual Function in Java What is interpreter in Java? Advanced Java Viva Questions Application of Array in Java Economical number in Java Iterate JSON array in Java Java callable example Java Command not found Java Date add Days Java File Extension Java Location Java Trim User Defined Custom Exceptions in Java Java array list remove time complexity Java.lang.Exception.NoRunnableMethods Java Map Example Java Obfuscator Java Pi Java Queue Java time local date Java Xmx Uses of Java Applet Life Cycle in Java Best Java Security Framework BigDecimal toString() in Java Jdoodle Java Literals in Java MVC in Java Powerful Number in Java Read the XLSX file in Java Relatively Prime in Java Root exception in java What is anagram in Java? Accessors and Mutator in Java Bottom view of a binary tree in Java Convert List to String in Java Equidigital in Java How to check data type in Java IdentityHashMap in Java Java Clone Array Java LDAP Authentication Java List Node Java Password Generator Magic Square in Java Pancake Sorting in Java Practical Number in Java Sublime Number in Java Sudoku in Java Compare Two Times in Java Diffie Hellman Algorithm in Java How to Reduce Time Complexity in Java Java calculate age Map of Map in Java Minimum XOR value pair in Java Palindrome Partitioning problem in Java Pernicious Number in Java Prime Points in Java Rectangular Numbers in Java Sleep Time in Java The final Keyword in Java Types of Statements in Java Unicode System in Java Zig Zag star and Number Pattern in Java Balanced Prime Number in Java ConcurrentSkipListSet in Java Construct the Largest Number from the Given Array in Java CopyOnWriteArrayList in Java Cyclic Barrier in Java Dangling Else problem in Java Display Unique Rows in a Binary Matrix in Java Empty Statement in Java Factorial of a Large Number in Java Facts about null in Java Rehashing in Java Singleton Design Pattern in Java Zebra Puzzle Problem in Java XOR of Array Elements Except Itself in Java Types of Sockets in Java Thread Synchronization in Java Set Up the Environment in Java Method and Block Synchronization in Java Fibodiv Number in Java House Numbers in Java GCD of Different SubSequences in Java Hogben Numbers in Java Decagonal Numbers in Java Converting Roman to Integer Numerals in java Check if the given array is mirror inverse in Java Caesar Cipher Program in Java Block Swap Algorithm for array rotation in Java Java Binary Tree Binary Strings Without Consecutive Ones in Java Beautiful Array in Java Balanced Parentheses in Java Arithmetic exception in Java Add numbers represented by Linked Lists in Java Two Decimal Places Java Intersection Point of two linked list in Java Find next greater number with same set of digits in Java Getter and Setter Method in Java Example Java Binary to Hexadecimal Java Calculate Average of List Iccanobif Numbers in Java Java delete directory Java For Keyword Java Float Keyword Java Instanceof Keyword Java If Keyword Java Int Keyword Java Import Keyword Java Package Keyword Java Static Keyword Java Public Keyword Java Implements Keyword Java Private keyword Java Protected Keyword Java Short Keyword Java Long Keyword Java Interface Keyword Java Try Keyword Java New Keyword Java Return Keyword Tug of War in Java Types of Events in Java

if-else Program in Java

if-else Program in Java

The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one can make a decision in the world of computer programming by controlling the flow of the program. There are following types of if-else statements in Java.

  1. if statements
  2. if-else statements
  3. if-else if-else statements
  4. Nested if-else statements

Let’s discuss in detail.

1. if statements

The syntax of the if statement is:

if(expression)
 {
                // Body of if statement
 }
 //Statements after if block 
if-else Program in Java

Here, the expression is of type Boolean. The body of the if statement is only executed when the expression is evaluated true. The following flow-diagram demonstrates the same.

We can have any number if statements in our code. Let’s take an example to understand it.

Suppose, we have to assign grades to students on the basis of the following rule:

  • If a student gets a percentage equal to or above 80, grade A is awarded.
  • If a student gets a percentage above or equal to 60 but less than 80, grade B is awarded.
  • If the percentage is between 40 to 60, grade C is awarded.
  • If the percentage is below 40, then the student is considered to fail, and a grade F is awarded.

We see that we are making some decisions to assign grades on the basis of the percentage obtained. Let’s implement the above rules in a Java program and make decisions using if statements.

Filename: IfElseExample.java

public class IfElseExample
 {             
 public static void main(String argvs[])
 {
                // Assigning percentage to the totalPercentage variable
                int totalPercentage = 75;
                // Awarding grades on the basis of percentage obtained.
                // The first if statement
                if(totalPercentage >= 80 )
                {
                    System.out.println("Grade A is awarded.");
                }
                // The second if statement
                if(totalPercentage < 80 && totalPercentage >= 60)
                {
                    System.out.println("Grade B is awarded.");
                }
                // The third if statement
                if(totalPercentage < 60 && totalPercentage >= 40 )
                {
                    System.out.println("Grade C is awarded.");
                }
                // The fourth if statement
                if(totalPercentage < 40)
                {
                    System.out.println("Grade F is awarded.");
                }
 }
 } 

Output:

Grade B is awarded.

Explanation: First of all, the first if statement is evaluated (totalPercentage >= 80). The value of the variable totalPercentage is 75. Therefore, we get 75 >= 80, which is false. Hence, the body of the first if statement is not executed. The control then shifts to the second if statement. The expression is totalPercentage < 80 && totalPercentage >= 60. Thus, we get 75 < 80 && 75 >= 60, which is true and the body of the second if statement is executed. For the third and fourth if statements, the condition is evaluated false, and their body is not executed.

2. if-else statements

We know the body of if statement executes when its expression is evaluated true. But when the expression of the if statement is evaluated false then the body of the else statement (if an else statement is present) is executed. Let’s see the flow chart of ie-else statement.

if-else Program in Java

The else statements can never exist independently as its execution depends on the result of the preceding if expression. It will always come along-with an if statement. However, if statements can exist independently (see the above example). The syntax of an if-else statement is:

if(expression)
 {
                // Body of if statement
 }
 else
 {
                // Body of else statement
 }
 //Statements after if-else block 

Let’s see an example of if-else statement.

Filename: IfElseExample1.java

public class IfElseExample1
 {             
 public static void main(String argvs[])
 {
                int no = -75; // Assigning a number to no variable
                if(no >= 0)
                {
                                System.out.println(no + " is a non-negative number.");
                }
                else // if the expression no >= 0 results false then this block will execute
                {
                                System.out.println(no + " is a negative number.");                   
                }
 }
 } 

Output:

-75 is a negative number.

Explanation: The input number we have taken is -75, which is less than 0. Therefore, the expression of the if statement evaluates false. After that, the else part is executed. Note that the else part must come immediately after the if block. Otherwise, the compiler will understand that the else part is independent and therefore punishing the programmer by giving the compilation error. Consider the following program.

Filename: IfElseExample2.java

public class IfElseExample2
 {             
 public static void main(String argvs[])
 {
                int no = -75; // Assigning a number to no variable
                if(no >= 0)
                {
                                System.out.println(no + " is a non-negative number.");
                }
                // Statement between the if and else block
                System.out.println("Something between if and else");
                else // if the expression no >= 0 results false then this block will execute.
                {
                                System.out.println(no + " is a negative number.");                   
                }
 }
 } 

Output:

/IfElseExample2.java:15: error: 'else' without 'if'
                else
                ^
 1 error 

3. if-else if-else statements

We can even create a ladder of if-else if-else statements. The ladder style of programming is better than the multiple if statements. The syntax of an if-else if-else statement is:

if(expression)
 {
                // Body of if statement
 }
 else if
 {
                // Body of else if statement            
 }
 else if
 {
                // Body of else if statement            
 }
 else
 {
                // Body of else statement
 }
 //Statements after the if-else ladder 

The flow diagram of if-else … if-else ladder is given below.

if-else Program in Java

Let’s re-write the code of the first example where we had multiple if statements.

Filename: IfElseExample3.java

public class IfElseExample3
 {             
 public static void main(String argvs[])
 {
                // Assigning percentage to the totalPercentage variable
                int totalPercentage = 75;
                // Awarding grades on the basis of percentage obtained.
                // The first if statement
                if(totalPercentage >= 80 )
                {
                    System.out.println("Grade A is awarded.");
                }
                // The first else if statement
                else if(totalPercentage < 80 && totalPercentage >= 60)
                {
                    System.out.println("Grade B is awarded.");
                }
                // The second else if statement
                else if(totalPercentage < 60 && totalPercentage >= 40 )
                {
                    System.out.println("Grade C is awarded.");
                }
                // The else statement
                else
                {
                    System.out.println("Grade F is awarded.");
                }
 }
 } 

Output:

Grade B is awarded.

Explanation: In the above program, we have four blocks. Each block deals with each of the given grade (A, B, C, F). As the input percentage is 75, the expression of the first if statement is false, and the control shifts to the first else-if statement. Here, the expression evaluates to true, and grade B is awarded. The rest of the code does not get executed. It is because the following statements start with else, and the else part is only executed when the preceding if expression is evaluated false, which is true in our case. The last else block only gets executed when the expressions of the if statement and all else if statements are evaluated false.

In the first example, we observe that no matter what happens, all the expressions of the if statements are evaluated, but, in this case, when we get a true value for any of the expressions, the rest of the code of the if-else ladder is skipped. Hence, reducing the execution time.

4. Nested if-else statements

In Java, it is possible to write if-else statements inside an if-else statement. It is called the nesting of if-else statements. The nesting can be done to any degree. Let’s write a Java program to find the smallest or largest among three numbers by using the nesting of if-else statements.

Filename: IfElseExample4.java

public class IfElseExample4
 {             
 public static void main(String argvs[])
 {
                int a = 75, b = 76, c = 77; // given numbers
                if(a > b)
                {
                                // Nesting if-else inside the if block
                                if(a > c)
                                {
                                               System.out.println(a + " is the largest number.");
                                }
                                else // this part will be executed when c >= a
                                {
                                               System.out.println(c + " is the largest number.");      
                                }
                }
                else // Reaching here means a <= b
                {
                                // Nesting if-else inside the else block
                                if(b > c)
                                {
                                               System.out.println(b + " is the largest number.");
                                }
                                else // this part will be executed when c >= b
                                {
                                               System.out.println(c + " is the largest number.");      
                                }
                }
 }
 } 

Output:

77 is the largest number.

Explanation: First of all, we decide whether the if part of the code will be executed or the else part by choosing the largest among the two of the given three numbers. Then, we compare the result, largest among the two, from the third number and display the result accordingly.

By making little tweaks in the above code, we can achieve the smallest among the given three numbers.

Filename: IfElseExample5.java

public class IfElseExample5
 {             
 public static void main(String argvs[])
 {
                int a = 75, b = 76, c = 77; // given numbers
                if(a < b)
                {
                                // Nesting if-else inside the if block
                                if(a < c)
                                {
                                               System.out.println(a + " is the smallest number.");
                                }
                                else // this part will be executed when c <= a
                                {
                                               System.out.println(c + " is the smallest number.");   
                                }
                }
                else // Reaching here means a >= b
                {
                                // Nesting if-else inside the else block
                                if(b < c)
                                {
                                               System.out.println(b + " is the smallest number.");
                                }
                                else // this part will be executed when c <= b
                                {
                                               System.out.println(c + " is the smallest number.");   
                                }
                }
 }
 } 

Output:

75 is the smallest number.

Explanation: Similar to the previous example, we are finding whether the if part of the code will be executed or the else part, to get the smallest among any two numbers out of given three. The nested part of the code makes the final decision on finding the smallest number.

Ternary Operator

Another way to perform the task done by an if-else statement is to use the ternary operator (? :).  The syntax of the ternary operator is:

(expression) ? (statements) : (statements);

If the expression is evaluated true, the statements of the? part will be executed (similar to the if block). When the expression results in false, statements of the : part will be executed (similar to the else block). Thus, we can easily convert the code written in an if-else block using the ternary operator. Let’s convert a few of the above-written code.

Filename: IfElseExample6.java

public class IfElseExample6
 {             
 public static void main(String argvs[])
 {             
 int no = -75; // Assigning a number to no variable
 String output; // it will be used for storing the result.
 output = (no >= 0) ? (no + " is a non-negative number.") : (no + " is a negative number.");
 System.out.println(output);
 }
 } 

Output:

-75 is a negative number.

Explanation: Since the input number is negative, the : part got executed. The work of the above code is exactly the same if we compare it with the code written in the IfElseExample2.java file.

Similar to the nesting of the if-else block, we can also do the nesting of the ternary operator to any degree. Let’s re-write the program to find the largest among the three given numbers using the ternary operator.

Filename: IfElseExample7.java

public class IfElseExample7
 {             
 public static void main(String argvs[])
 {
                int a = 75, b = 76, c = 77; // given numbers
                int ans; // Final result will be stored in this variable
                //Nesting of the ternary operator
                ans = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
                // Displaying the result
                System.out.println(ans + " is the largest number.");
 }
 } 

Output:

77 is the largest number.

Difference Between if-else and the Ternary Operator

As far as execution time is concerned, if-else and the ternary operator takes almost the same amount of time. However, the ternary operator makes the program less verbose. See for yourself and compare the lines of code we have written to find the largest number using if-else and the ternary operator. But, the major drawback of the ternary operator is that it makes the code difficult to understand. Therefore, for the small if-else operations, ternary operators should be used. But for the lengthy stuff, we should stick with the if-else even though it is making the program wordy.

Another drawback of the ternary operator is that independent ? part (similar to if block) never exists. The ? will always come with the : (similar to the else). Thus, those programs that are only using if statements do not get converted easily using the ternary operator.



ADVERTISEMENT
ADVERTISEMENT