if statement in Java

if statement in Java

exploreJava logo


if statement is one of the most important programming constructs, it is available in all most all of the programming language. While programing, there are lots of situations where decisions have to be made based on some condition; condition can be a simple or complex. Simple condition involves only one or two conditions checking but complex conditions will have more conditions with different comparisons. In programs, execution has to be branched based on the situation or condition. Examples for using if condition in programs:
  • if user provided value is word “search” then searching in the database has to be performed otherwise simply display all the records.
  • if user provided value is even number then display values associated with even numbers only otherwise do nothing
  • if a value is "Sunday" then show menu of Sunday only, if a value is "Monday" then show menu of Monday only.
  • if a value is "Prime number" then use that number to divide another number otherwise do nothing
  • if first value is prime number, second is name of database table, third is male then display records of all employees whose id is prime and who are male from the give database table.

Syntax of if statement

if(condition)
	if_true_statement; //if condition is true this statement will be executed
else 
	if_false statement; //if condition is false this statement will be executed
if(condition)
	if_true_statement; //if condition is true this statement will be executed
else if(condition)
	if_true statement; //if condition is true this statement will be executed
....

else
	if_false statement; //if condition is false this statement will be executed

if more than one statement is to be executed after the evaluation of the condition then those statements are enclosed within the curly brackets. It is not necessary to write else part in every if statement, it depends on the situation.

Example

if(age >=18)
	System.out.println("You can ride a bike");
else	
	System.out.println("You have to wait for few more years to ride a bike.");
if(text.equals("search") && isPrime(number)){
	System.out.println("Search records with id as prime number");
}
if(day.equals("Sunday")){
	System.out.println("\n1.Chatamari\n2.Momo\n3.Bara\n4.Masu Chura\n5.Samosa\n6.Pizza.\n7.Burger");
}else if(day.equals("Monday")){
	System.out.println("\n1.Chatamari\n2.Momo\n3.Bara\n4.Allu Tama\n5.Samosa\n6.Chowmin.\n7.Hot Dogs");
}else if(day.equals("Tuesday")){
	System.out.println("\n1.Fry Rice\n2.Momo\n3.Fried Prawn\n4.Fish curry\n5.Sandwich\n6.Pizza.\n7.Burger");
}else{
	System.out.println("Have to take order");
}

Java Programs: if-statements Examples

In the given program two integers are defined x and y; x is assigned 444 and y is not assigned any value, by default it will be zero. if statement is used to check if the value of x is less than 1000, if less than 1000, message is displayed.

Then Object of class Scanner is created, method nextInt() is used to take integer from user. Two integers are taken from user, one at a time, and assigned to x and y respectively. Then if value of x is greater than y is checked; Output is given.

import java.util.Scanner;
class if_demo{
	public static void main(String[] ops){
		int x = 444, y;
		if(x < 1000)
			System.out.println("Value of x is less than 1000");
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter a number: ");
		x = sc.nextInt();
		System.out.print("Enter a number: ");
		y = sc.nextInt();
		if(x > y){
			System.out.println(x+" is greater than "+y);
		}else{
			System.out.println(x+" is less than "+y);
		}
	}
}

Output:

33 44 33 is less than 44

Following program asks user to provide a line of words. Object of class Scanner is created; method nextLine() of Scanner object is used to take a line from the user. Then if statement is used to check if the length of the provided line lies between 3 and 10 or not.

import java.util.Scanner;
class if_demo{
	public static void main(String[] app){
		String str;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a word: ");
		str = sc.nextLine();
		if(str.length()>=3 && str.length() <=10){
			System.out.println("Length of "+str +" lies between 3 and 10");
		}else{
			System.out.println(str +" is either shorter than 3 characters or greater than 10.");
		}
	}
}


Output:
Enter a word: 
Fish Tail
Length of Fish Tail lies between 3 and 10
Kanchanjunga
Kanchanjunga is either shorter than 3 characters or greater than 10.

In the given program three integers are taken from the user, Object of Scanner class is created, this class has several methods defined for taking different types of values from the keyboard; nextInt() method is used to take integer from user. Three number are taken as inputs; those three numbers are added and stored in variable sum. Then if statement is used to check if the sum lies between 270 and 300 or not. Second if statement is used to check if the sum lies between 210 and 270 or not. If both of the if statements evaluate to false then statement in the else part is executed.

import java.util.Scanner;
class if_demo{
	public static void main(String[] app){
	int a, b, c, sum;
	Scanner sc = new Scanner(System.in);
	System.out.print("Enter a number: ");
	a = sc.nextInt();
	System.out.print("Enter a number: ");
	b = sc.nextInt();
	System.out.print("Enter a number: ");
	c = sc.nextInt();
	sum = a + b + c;
	if(sum >=270 && sum <= 300)
		System.out.println("You got very good total of "+sum);
	else if(sum >=210 && sum < 270)
		System.out.println("You got fair total of "+sum);
	else
		System.out.println("You got low total of "+sum);
	}
}

Output:
First run:
Enter a number: 88
Enter a number: 100
Enter a number: 99
You got very good total of 287
Second run:
Enter a number: 90
Enter a number: 60
Enter a number: 70
You got fair total of 220
Third run:
Enter a number: 80
Enter a number: 40
Enter a number: 40
You got low total of 160

Two words are taken from the user; those words are compared using compareTo() method of the string object. This method compareTo() takes a string as parameter and is called by a string; strings are equal if the value returned is 0, first string is greater than second string if value returned by compareTo method is greater than 0; first string is less than second string if the value returned by compareTo method is less than 0. Strings are compared based on the alphabetical order. Output of the program is given.

import java.util.Scanner;
class if_demo{
	public static void main(String[] app){
		String word1,word2;
		Scanner sc = new Scanner(System.in);	
		System.out.print("Enter a word: ");
		word1 = sc.next();
		System.out.print("Enter a word: ");
		word2 = sc.next();
		if(word1.compareTo(word2) == 0){
			System.out.println(word1+ " and "+word2 +" are equal.");
		}
		if(word1.compareTo(word2) > 0){
			System.out.println(word1+ " is lexicographically greater than "+word2);
		}
		if(word1.compareTo(word2) < 0){
			System.out.println(word1+ " is lexicographically less than "+word2);
		}
		
	}
}
Output:
First run:
Enter a word: lion
Enter a word: tiger
lion is lexicographically less than tiger
Second Run:
Enter a word: eagle
Enter a word: eagle
eagle and eagle are equal.
Third Run:
Enter a word: Parrot
Enter a word: Crow
Parrot is lexicographically greater than Crow

In the given program below user is asked to enter a text. Object of class Scanner is created; Scanner class has methods to take different type of data values from keyboard. Scanner class is defined in the java.util package. It is a build in class. if statement is used to check if the text input by user contains letter 'o' or not; next() method of the Scanner object is used to take text from the user. Then second input asks user to input another text (a line); nextLine() method of Scanner object is used to take input. Then if statement is used to see if the second input text contains first input text or not. Output of the program is given just below the program code.

import java.util.Scanner;
class if_demo{
	public static void main(String[] app){
		String word1,word2;
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter a text: ");
		word1 = sc.nextLine();
		System.out.println("Checking if given text contains character o or not:");
		if(word1.indexOf('k')>-1){
			System.out.println("Given text "+word1+" contains o");
		}else System.out.println("Given text "+word1+" does not contain o");
		
		System.out.print("Enter a word: ");
		word2 = sc.next();
		System.out.println("Checking if first entered word contains second entered word or not:");
		if(word1.indexOf(word1)>-1){
			System.out.println("Given word "+word1+" contains "+word2);
		}else System.out.println("Given word "+word1+" does not contain "+word2);
	}
}
Output:
Enter a text: Mission Impossible
Checking if given text contains character o or not:
Given text Mission Impossible does not contain o
Enter a word: possible
Checking if first entered word contains second entered word or not:
Given word Mission Impossible contains possible


Arrays in Java

switch case in Java

Post a Comment

Previous Post Next Post