You are on page 1of 2

OBJECT-ORRIENTED PROGRAMMING IT 55

The if-then and if-then-else Statements



The if-then Statement
The if-then statement is the most basic of all the control flow statements. It tells your program to
execute a certain section of code only if a particular test evaluates to true.

The if-else statement has the following form.
if (boolean-expression) {
then-clause
} else {
else-clause
}

Ex. Love Bug
import java.io.*;
public class SimpleIF
{
public static void main(String[]args)
{
try
{
byte Num[]=new byte[255];
System.out.print("Enter Number: ");
System.in.read(Num);
System.out.println("\n");
Integer Love=Integer.parseInt(new String(Num).trim());
if(Love==14344)
System.out.println("\t \t I LOVE YOU VERY MUCH");
else
System.out.println("I HATE YOU");
System.out.println("\n");
}catch(IOException e) {
}
}
}
Ex. PositiveNegative
import java.io.*;
public class PositiveNegativeprogram
{
public static void main(String []args)
{
try{
byte num[]=new byte[255];
System.out.print("Enter Number: ");
System.in.read(num);
System.out.print("\n\n");
Integer x = Integer.parseInt(new String(num).trim());
if(x>=0)
{
System.out.println("\t \t Positive Number");
}
else
{
System.out.println("\t" +"\t" + Negative Number");
}
System.out.print("\n\n");
}catch(IOException e){
}
}
}
OBJECT-ORRIENTED PROGRAMMING IT 55

Ex. Simple Highest Lowest

import java.io.*;

public class GreaterLessthan
{
public static void main(String []args)
{
int num1,num2;
num1=5;
num2=6;

if(num1>num2)
{
System.out.println("Num1 is greater than Num2");
}
else
{

System.out.println("Num2 is greater than Num1");
}

}
}

Ex. TWO inputted Values Greater than and Less Than

import java.io.*;

public class GreaterLessthan
{
public static void main(String []args)
{
try
{
byte n1[]=new byte[255];
byte n2[]=new byte[255];

System.out.print("Enter Num1: ");
System.in.read(n1);
System.out.print("Enter Num2: " );
System.in.read(n2);

Integer num1 = Integer.parseInt(new String(n1).trim());
Integer num2 = Integer.parseInt(new String(n2).trim());

if(num1>num2)
{
System.out.println("Num1 is greater than Num2");
}
else
{

System.out.println("Num2 is greater than Num1");
}
}catch (IOException e){
}
}
}

You might also like