Object Oriented Programming Lab # 02
Object Oriented Programming Lab # 02
Lab # 2
Aim:
Understanding the decision making statements in Java.
Theory:
Decision making structures requires the programmer to specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed
if the condition is determined to be true, and optionally, other statements to be executed if
the condition is determined to be false. Java provides following types of decision making
statements.
Statement Description
nested if You can use one if or else if statement inside another if or else
statements if statement(s).
Syntax:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
Object Oriented Programming Lab # 02
}
}
switch statement A switch statement allows a variable to be tested for equality against a list
of values.
Syntax:
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
nested switch You can use one switch statement inside another switch statement(s).
statements Syntax:
switch(ch1)
{
case 'A':
printf("This A is part of outer switch" );
switch(ch2)
{
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */
}
Program:
package com.mycompany.lab2;
int a = 100;
if (a < 20)
else
Output:
Object Oriented Programming Lab # 02
package com.mycompany.lab2;
Output:
Program:
package com.mycompany.lab2;
switch (grade)
{
case 'A':
System.out.println("Excellent!");
break;
case 'B':
case 'C':
System.out.println("Well done");
break;
case 'D':
System.out.println("You passed");
break;
case 'F':
System.out.println("Better try again");
Object Oriented Programming Lab # 02
break;
default:
System.out.println("Invalid grade");
break;
}
System.out.println("Your grade is " +grade);
}
}
Output:
Program:
package com.mycompany.lab2;
switch (a)
{
case 100:
System.out.println("This is part of outer switch ");
switch (b)
{
case 200:
System.out.println("This is part of inner switch ");
break;
}
Object Oriented Programming Lab # 02
break;
}
System.out.println("Exact value of a is : " +a );
System.out.println("Exact value of b is : " +b);
}
}
Output:
Lab Task:
a. Write a program that determines that number entered by user is even or odd.
b. Write a program which takes user’s input for age and on basis of that input gives
the following output:
If Age is greater than 45 then prints the message “You are old stay at home and wait for
call”
If Age is less than 30 then prints “Hey! Man enjoy your life with your kids”
Use Switch statement in this Task.