In this article, you will learn to use two selection statements: if and if else to the statements which alter the flow of your program’s execution.
if else statement
Syntax
if (condition)
{
statement 1 ;
}
else
{
statement 2;
}
Here condition is a Boolean condition(returns either true or false).
- If the condition is evaluated to true, statement(s) inside the body of if (statements inside parenthesis) are executed.
- If the condition is evaluated to false, statement(s) inside the body of if are skipped from execution
Java if-else statement examples
1. Take values of length and breadth of a rectangle and check if it is
square or not.
Answer :
import java.io.*;
class sha
{
public static void main(String[] args)
{
int x=4;
int y=4;
if(x==y)
System.out.println("Square");
else
System.out.println("rectangle");
}
}
2. Take two int values and print greatest among them.
Answer:
import java.io.*;
class sha
{
public static void main(String[] args)
{
int x=323;
int y=234;
if (x>y)
System.out.println("x is greater");
else
System.out.println("y is greater");
}
}
3. Write a program to check whether a entered character is lowercase ( a to z ) or uppercase ( A to Z ).
Answer :
import java.io.*;
class sha
{
public static void main(String[] args)
{
char x = 'A'; // You must remember to enclose any character
within single quotes, while initializing a
charater data type.
ie,
eg. char x= 'B';//
if(x=='a')
System.out.println("Lower case");
else
System.out.println("Upper case");
}
}
4. write a program to identify the given number is a perfect square root.
Answer:
import java.io.*;
class sha
{
public static void main(String[] args)
{
int x=81;
int y;
y=(int)Math.sqrt(x);
if(x==y*y)
System.out.println(" Number is perfect square root");
else
System.out.println(" Number is not a perfect square root");
}
}
5.Write a program to display whether a person is eligible for vote or not.
Answer:
import java.io.*;
class sha
{
public static void main(String[] args)
{
int age=18;
if(age>=18)
System.out.println("person is Eligible to vote");
else
System.out.println(" person is not Eligible to vote");
}
}






No comments:
Post a Comment