elseif statement in java

In the previous post, we have seen if else statement. In this post, we will learn about elseif statements.

If we have multiple verification check points, we can use elseif statements. A if statements can be followed by zero or more elseif statements.

If there is a requirement to put else as well, then it must come after elseif statement.

Syntax of if ..else if:

if ( condition_to_test ) {
  // some statements 
}
else if( condition_to_test ) {
   // some statements
}else{
   // some statements
}

Example of else if:

public class ExampleElseIf {
	public static void main(String[] args) {
		
		String book = "php";
		if(book.equals("math")){
			System.out.println("It is a mathmetic book.");
		}else if(book.equals("php")){
			System.out.println("It is a php book.");
		}else if(book.equals("python")){
			System.out.println("It is a python book.");
		}else{
			System.out.println("Book is not present");
		}
	}
}
Output: It is a php book.

 

?: conditional operator:

It is a conditional operator which works same like a if..else statement. If condition is ture ,it returns value  that comes after ‘?’ , else it returns value after ‘:’.

Let’s understand with an example , where we are checking if book is a java book or PHP book.

public class Example {
	public static void main(String[] args) {
		
		String book = "php";
		String b = (book.equals("java")) ? "java book" : "PHP book";
		System.out.println(b);
	}
}
Output: PHP book
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.

 

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 10, 2015

    […] the previous post, we have seen if..else if conditional statements. In this post, we will learn switch case […]