oop_unit2
oop_unit2
If statement
Two way if statement
Nested if statement
Switch statement
Conditional Expression
While loop
Do-while loop
For loop
Nested loop
Break and continue statement
Common mathematical expression
Decision Making
Compiler executes program statements sequentially.
Decision making statements are used to control the flow of program execution.
It allows us to control whether a set of program statement should be executed or not.
It evaluates condition or logical expression first and based on its result (true or false),
the control is transferred to the particular statement.
If result is true then it takes one path else it takes another path.
… …
…
Decision Making Statements
Commonly used decision making statements are
One way Decision: if (Also known as simple if)
Two way Decision: if…else
Multi way Decision: if…else if…else if…else
Decision within Decision: nested if
Two way Decision: ?: (Conditional Operator)
n-way Decision: switch…case
One way Decision
if
if statement is the most simple decision-making statement also known as simple if.
An if statement consists of a boolean expression followed by one or more
statements.
If the expression is true, then 'statement-inside' will be executed, otherwise
'statement-inside' is skipped and only 'statement-outside' will be executed.
It is used to decide whether a block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
False
if(condition)
condition {
// Statements to execute if condition is
True
true
statement-inside }
WAP to print if a number is positive
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5.Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if(x > 0){
8. System.out.println("number is a positive");
9. }
10.}
Exercise
Write a program which reads two numbers and based on different between it prints
either of following message DIFFERENCE IS POSITIVE or DIFFERENCE IS
NAGATIVE.
WAP to print if a number is odd or even
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5.Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if( x % 2 == 1 ){
8. System.out.println("number is a odd");
9. }
10. if( x % 2 == 0 ){
11. System.out.println("number is a even");
12. }
13.}
Two way Decision
If…else
For a simple if, if a condition is true, the compiler executes a block of statements, if
condition is false then it doesn’t do anything.
What if we want to do something when the condition is false? if…else is used for the
same.
If the 'expression' is true then the 'statement-block-1' will get executed else
'statement-block-2' will be executed. if(condition)
{
// statement-block-1
True False // to execute if condition is
condition true
}
else
statement-block- statement-block-
{
1 2
// statement-block-2
// to execute if condition is
… false
}
WAP to print if a number is positive or negative
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if (x > 0){
8. System.out.println("Number is positive");
9. }//if
10. else{
11. System.out.println("Number is negative");
12. }//else
13. }//main
14.}//class
WAP to print if a number is odd or even
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4. int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if( x % 2 == 1 ){
8. System.out.println("number is a odd");
9. }
10. else{
11. System.out.println("number is a even");
12. }
13.}
Exercise
1. Any year is entered through the keyboard, write a program to determine whether
the year is leap or not.
2. Write a program to check whether a triangle is valid or not, when the three angles
of the triangle are entered through the keyboard. A triangle is valid if the sum of all
the three angles is equal to 180 degrees.
Multi way Decision
if…else if…else
if…else if…else statement is also known as if-else-if if(condition 1)
ladder which is used for multi way decision making. {
statement-block1;
It is used when there are more than two different conditions. }
It tests conditions in a sequence, from top to bottom. else if(condition 2)
{
If first condition is true then the associated block with if statement-block2;
statement is executed and rest of the conditions are }
skipped. else if(condition 3)
{
If condition is false then then the next if condition will be statement-block3;
tested, if it is true then the associated block is executed and }
rest of the conditions are skipped. Thus it checks till last else if(condition 4)
condition. {
Condition is tested only and only when all previous statement-block4;
}
conditions are false.
else
The last else is the default block which will be executed if default-statement;
none of the conditions are true.
The last else is not mandatory. If there are no default
if-else-if ladder
condition False
1
if(condition 1)
{
statement-block1; True condition False
}
else if(condition 2) 2
{
statement-block2; … True condition
False
}
else if(condition 3) 3
{
statement-block3; … True
}
else if(condition 4)
{
statement-block4; … …
}
else
default-
statement;
WAP to print if a number is zero or positive or negative
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4. int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if(x > 0){
8. System.out.println(" number is a positive");
9. }
10. else if(x < 0) {
11. System.out.println(" number is a negative");
12. }
13. else{
14. System.out.println(" number is a zero");
15. }
16.}
WAP to print day name from day number
1.public class Demo {
2. public static void main(String[] args) {
3. int d;
4. Scanner sc = new Scanner(System.in);
5. d = sc.nextInt();
6. if (d == 1 ) System.out.println(“Monday”);
7. else if (d == 2) System.out.println(“Tuesday“);
8. else if (d == 3) System.out.println(“Wednesday“);
9. else if (d == 4) System.out.println(“Thursday“);
10. else if (d == 5) System.out.println(“Friday“);
11. else if (d == 6) System.out.println(“Saturday“);
12. else System.out.println(“Sunday“);
13. }
14.}
if-else statement
1. int marks = 65;
2. if (marks < 60) {
3. System.out.println("fail");
4. } else if (marks >= 60 && marks < 80) {
5. System.out.println("B grade");
6. } else if (marks >= 80 && marks < 90) {
7. System.out.println("A grade");
8. } else if (marks >= 90 && marks < 100) {
9. System.out.println("A+ grade");
10.} else {
11. System.out.println("Invalid!");
12.}
Nested If
A nested if is an if statement that is the target of another if(condition 1)
if statement. {
if(condition 2)
Nested if statements mean an if statement inside {
another if statement. nested-block;
}
The statement connected to the nested if statement is else
only executed when -: {
nested-block;
condition of outer if statement is true, and }
condition of the nested if statement is also true. }//if
else if(condition 3)
Note: There could be an optional else statement {
associated with the outer if statement, which is only statement-block3;
}
executed when the condition of the outer if statement is else(condition 4)
evaluated to be false and in this case, the condition of {
statement-block4;
nested if condition won't be checked at all. }
Nested If statement
We can also use if/else if statement inside another if/else if statement, this is known
as nested if statement.
int username = Integer.parseInt(args[0]);
int password = Integer.parseInt(args[1]);
double balance = 123456.25;
if(username==1234){
if(password==987654){
System.out.println("Your Balance is ="+balance);
}
else{
System.out.println("Password is invalid");
}
}
else{
System.out.println("Username is invalid");
}
Exercise
In a company an employee is paid as under:
If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA
= 90% of basic salary.
If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA =
98% of basic salary.
Employee's salary is input through the keyboard, write a program to find his
gross salary.
n-way Decision
Switch…case
switch…case is a multi-way decision making switch (expression)
statement. {
case constant 1:
It is similar to if-else-if ladder statement. // Statement-1
break;
It executes one statement from multiple
conditions. case constant 2:
// Statement-2
break;
case constant 3:
// Statement-3
break;
default:
// Statement-default
// if none of the above case
matches then this block would be
executed.
}
Switch…case: WAP to print day based on number entered
6. switch (d) {
1. public class Demo { 7. case 1:
2. public static void 8. System.out.println(“Monday“); break;
main(String[] args){ 9. case 2:
3. int d; 10. System.out.println(“Tuesday“); break;
4. Scanner sc= new 11. case 3:
Scanner(System.in); 12. System.out.println(“Wednesday“); break;
5. d = sc.nextInt(); 13. case 4:
14. System.out.println(“Thursday“); break;
15. case 5:
16. System.out.println(“Friday“); break;
17. case 6:
18. System.out.println(“Saturday“); break;
19. case 7:
20. System.out.println(“Sunday“); break;
21. default:
22. System.out.println(“Invalid Day“);
23. } //switch
24. }
25.}
Switch…case
switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
public class SwitchExampleDemo {
public static void main(String[] args)
{
int number = 20;
switch (number) {
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
default:
System.out.println("Not 10 or 20");
}
}
}
Exercise
Write a menu driven program that allows user to enters five numbers and then
choose between finding the smallest, largest, sum or average. Use switch case to
determine what action to take. Provide error message if an invalid choice is entered.
Points to remember for switch…case
The condition in the switch should result in a constant value otherwise it would be
invalid.
In some languages, switch statements can be used for integer values only.
Duplicate case values are not allowed.
The value for a case must be of the same data type as the variable in the switch.
The value for a case must be a constant.
variables are not allowed as an argument in switch statement.
The break statement is used inside the switch to terminate a statement sequence.
The break statement is optional, if eliminated, execution will continue on into the
next case.
The default statement is optional and can appear anywhere inside the switch block.
Exercise
Write a Java program to get a number from the user and print whether it is positive or
negative.
Write a program to find maximum no from given 3 no.
The marks obtained by a student in 5 different subjects are input through the
keyboard.
The student gets a division as per the following rules:
Percentage above or equals to 60-first division
Percentage between 50 to 59-second division
Percentage between 40 and 49-Third division
Percentage less than 40-fail
Write a program to calculate the division obtained by the student.
Write a Java program that takes a number from the user and displays the name of
the weekday accordingly (For example if user enter 1 program should return
Monday) .
Repeatedly execute a block of statements
Loop
Sometimes we need to repeat certain actions several times or till the some criteria is
satisfied.
Loop constructs are used to iterate a block of statements several times.
Loop constructs repeatedly execute a block of statements for a fixed number of times
or till some condition is satisfied
Flowchart of if Flowchart of while
(true-block executed only once) (true-block executed till condition is true)
False False
condition condition
True True
true-block true-block
Looping Statements
Following are looping statements in any programming language,
Entry Controlled while, for
Exit Controlled do…while
Unconditional Jump goto (It is advised to never use goto in a program)
Entry Controlled Loop
while
while is a entry controlled loop.
It executes a block of statements till the condition is true.
False Label
conditio Statement
n Loop Body
True True conditio
True conditio n
Loop Body
n goto
False
False label
loop within a loop
WAP to print given pattern (nested loop)
* 1.class PatternDemo{
** 2.public static void main(String[] args) {
*** 3. int n=5;
**** 4. for(int i=1;i<=n;i++){
***** 5. for(int j=1;j<=i;j++){
6. System.out.print("*");
7. }//for j
8. System.out.println();
9. }//outer for i
10. }
11.}
WAP to print given pattern (nested loop)
1 1.class PatternDemo{
1 2 2.public static void main(String[] args) {
1 2 3 3. int n=5;
1 2 3 4 4. for(int i=1;i<=n;i++){
1 2 3 4 5 5. for(int j=1;j<=i;j++){
6. System.out.print(j+"\t");
7. }//for j
8. System.out.println();
9. }//outer for i
10. }
11.}
Programs to perform (Looping Statements)
Write a program to print first n odd numbers.
Write a program to check that the given number is prime or not.
Write a program to draw given patterns,
Math class
The Java Math class provides more advanced mathematical calculations other
than arithmetic operator.
The java.lang.Math class contains methods which performs basic numeric
operations such as the elementary exponential, logarithm, square root, and
trigonometric functions.
All the methods of class Math are static.
Fields :
Math class comes with two important static fields
E : returns double value of Euler's number (i.e 2.718281828459045).
PI : returns double value of PI (i.e. 3.141592653589793).
Methods of class Math
Methods of class Math (Cont.)
Methods of class Math (Cont.)
Math Example