Java Tutorial

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

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 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 BufferedWriter Java InputStreamReader Java File Java Read File Line By Line Java FileOutputStream Jar File in Java

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 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

Java Differences

Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Static vs Non-static in Java C vs Java int vs Integer in Java Stack vs Heap in Java Java Array vs ArrayList

How to

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 call a method in Java How to sort an array 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 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 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 achieve abstraction in Java How to call static method in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Parallel Arrays Sort in Java

Java 9 Features

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

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hibernate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial

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.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

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 Char and String differences in Java Difference between String, StringBuffer and StringBuilder 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 calculate time difference in Java 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

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