0% found this document useful (0 votes)
8 views

unit-2

This document covers control structures in Java, including decision-making statements (if, switch), looping statements (for, while, do-while), and jump statements (break, continue). It explains the syntax and usage of these structures, providing examples and exercises for practice. Additionally, it discusses methods in Java, including predefined and user-defined methods, their declarations, and types.

Uploaded by

dead220905
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

unit-2

This document covers control structures in Java, including decision-making statements (if, switch), looping statements (for, while, do-while), and jump statements (break, continue). It explains the syntax and usage of these structures, providing examples and exercises for practice. Additionally, it discusses methods in Java, including predefined and user-defined methods, their declarations, and types.

Uploaded by

dead220905
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

UNIT-2

S Syllabus:
Y Control structures
• if single-selection statement, if….else double-
L selection statement, while repetition statement,
L do….while repetition statement, Switch multi-
selection statement, Break and continue
B statements,
• Logical operators, Methods :Introduction, Program
U modules in Java, Static methods, Static Fields and
Class Math, Declaring methods with multiple
S parameters, Scope of declaration, method
overloading and Java API, packages..a
Control Structure in Java:

After studying this chapter, you will

• Be able to solve problems involving repetition.


• Understand the differences among various loop structures.
• Know the principles used to design effective loops.
• Understand the goals and principles of structured programming.
• Able to deal with methods in java
• Solving problems with Packages in java
Control Structure in Java:
Java provides statements that can be used to control the flow of Java code. Such statements are
called control flow statements. It is one of the fundamental features of Java, which provides a
smooth flow of program.
Java provides three types of control flow statements.
• Decision Making statements ()
– if statements
– switch statement
• Loop statement
– do while loop
– while loop
– for loop
– for-each loop
• Jump statements
– break statement
– continue statement
Decision Making statements:
• As the name suggests, decision-making statements decide which statement to execute and
when.
• Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided.
• There are two types of decision-making statements in Java, i.e., If statement and switch
statement.
1) If Statement:
• In Java, the "if" statement is also called as selection statements
• The control of the program is diverted depending upon the specific condition.
• The condition of the If statement gives a Boolean value, either true or false. In Java, there are
four types of if-statements given below.
– Simple if statement
– if-else statement
– if-else-if ladder
– Nested if-statement
Decision Making statements: if statement
1) Simple if statement:
• It is the most basic statement among all control flow statements in Java.
• It evaluates a Boolean expression and enables the program to enter a block of code if the
expression evaluates to true.
• Syntax of if statement is given below.

• In above syntax, it execute statement 1 iff


condition is TRUE otherwise if block will be
skipped while execution
Decision Making statements: if statement
Example: Write java program to display given two numbers if their addition is greater or equal to
50

Program:
Decision Making statements: if statement
Write java program for following tsk:
1. Write program to display given number by adding 100 to it if it is even number
2. Take two numbers, and display their multiplication if both are odd numbers
3. Take string from user and display it if its length is greater than 5
4. For any student take marks for five subject and display “congrats….” if percentage of
students is more than 75%
Decision Making statements: if else statement
• If else statement:
• The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
• Syntax of if statement is given below.

• In above syntax, it execute if block iff condition


is TRUE otherwise it execute else block
Decision Making statements: if else statement
Example: Write java program to check whether number is even or odd
Program:

Output:
Decision Making statements: if else statement
Write java program for following task:

• Write a java program to find the largest of two numbers


• Write a java program to check if a character is a vowel or consonant
• Write a java program to check if a year is a leap year or not, by use of an if else statement in
java
• Write a java program to check if a number is divisible by 5 or not,
Decision Making statements: if ladder statement
If-else-if ladder:
• The if-else-if statement contains the if-statement followed by multiple else-if statements.
• it is the chain of if-else statements in which the program may enter in the block of code where
the condition is true.
• All else keywords will be followed by if block except last else block.
• Syntax:
Decision Making statements: if ladder statement
Flow chart for if-else-if ladder:
Decision Making statements: if ladder statement
Write java to check whether entered number is positive, negative or zero
Program:
Output:
Decision Making statements: if ladder statement
write java program using if else if ladder for following task:
• Write a java program to Find the largest of three numbers
• Take the percentage of student and display the grade(A(>90),B(71-90),C(50-70)or fail(<70))
Decision Making statements: Nested if statement
• The nested if statements mean an if statement inside another if statement.
• The inner block of the if statement executes only if the outer block condition is true.
• This statement is useful when you want to test a dependent condition.
• Synatx:
Decision Making statements: Nested if statement
Flow chart for Nested If:
Decision Making statements: Nested if statement
Write java program to perform following task using nested if :
• Take number of awards as input for 3 employees and display the employee with highest
awards as a winner
• Take three numbers and check whether all are same or all are different
Switch case:
• The Java, switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
• Multiple cases will be written in code but only that case will be executed which user wants to.
Flowchart
Syntax Flowchart->
Switch case contin…..
Points to note:
• The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums
and string.
• Each case statement can have a break statement which is optional. When control reaches to
the break statement, it jumps the control after the switch expression. If a break statement is
not found, it executes the next case.
• The case value can have a default label which is optional.
Switch case contin…
How does the switch-case statement work?
• Lets take an example:

• The swich() value ‘num’ will be compared with the values of each case.
• If num is equal to 1, the code of case 1 will be executed. Similarly, the num is equal to 2, the
code of case 2 will be executed. After specific case execution control flow will be out of switch
statement
• If there is no match, the code of the default case is executed.
Switch case contin…
• Write java program to deliver the item of user demand(size of item)
Looping statements:

Introduction:

• In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. In such cases looping statements are used.
• The loop in java is being used to iterate set of instructions multiple times.
• In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
– for loop
– while loop
– do-while loop
Java for loop:
• In Java, for loop is similar to C and C++.
• It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code as follow.

• We use the for loop only when we exactly know the number of times, we want to execute the
block of code.

• Flowchart
Java for loop:
Important points to note :
• All three expressions in a for header are optional.
• If the loop Continuation Condition is omitted, Java assumes that the loop-continuation
condition is always true, thus creating an infinite loop.
– Ex:for(){ }
• You might omit the initialization expression if the program initializes the control variable
before the loop.
– Ex: int i=1;
for( ; i<10 ; i++)
• You might omit the increment expression if the program calculates the increment with
statements in the loop’s body or if no increment is needed.
– Ex: for(i=0 ; i<10 ; ){
sop(i);
i++; }
Java for loop:
• Write Java program to display addition of first 10 natural numbers

• Display all numbers from 100 to 200 which are divisible by 5


Java for loop:
Write Java program to display
addition of numbers for given range
by user

• Write java program to sum of all numbers from


100 to 200 which are divisible by 5 and not divisible by 5
For each loop:
• Java provides an enhanced for loop to traverse the data structures like array or collection.
• In the for-each loop, we don't need to update the loop variable.
• The syntax to use the for-each loop in java is given below.

• Example: write java program to display all elements from an string array
For each loop:
• Write java program to display marks which are greater than 75
Nested for loop:

• If a loop exists inside the body of another loop, it's called a nested loop.
• Main/starting loop is called as outer loop and all inside loops are called as inner loops.

• Syntax:

• All such loop should have different loop variable (like i, j in above example)
• All iterations of inner loop will be executed for each iteration of outer loop
While loop:
Introduction
• The while loop is also used to iterate over the number of statements multiple times.
• However, if we don't know the number of iterations in advance, it is recommended to use a
while loop.
• Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
• It is also known as the entry-controlled loop since the condition is checked at the start of the
loop.
• If the condition is true, then the loop body will be executed; otherwise, the statements after
the loop will be executed.
• The syntax of the while loop is given below.
While loop:
While loop:
• Write java program to display table of 2 output:

• Display all numbers whose square is less than 100 output:


do while loop:
Java do-while loop
• The do-while loop checks the condition at the end of the loop after executing the loop
statements.
• When the number of iteration is not known and we have to execute the loop at least once, we
can use do-while loop.
• It is also known as the exit-controlled loop since the condition is not checked in advance.

Syntax flowchart
do while loop:
• Write java program to display table of 2 output:

• Display all numbers whose square is less than 100 output:


do while loop:
• Take marks of 15 students in an array and display first five student mark which are greater
than 75

output
Jump Statements
Introduction:
• Jump statements are used to transfer the control of the program control from one point to
elsewhere in the program.
• Jump statements are primarily used to interrupt loop or switch-case instantly.
• Looping statements like for, while, and do-while are used to execute a set of statements
repeatedly.
• While execution of loops if code reaches to desired point where loop must be ended, jump
statements help us to end the loop at that point.
• This can be prevented by adding appropriate terminating conditions to the loop or by
implementing jump statements. A jump statement helps transfer the control of a program
from one line of the code to another and skip the ones in between.
• Java supports three jump statements: break, continue, and return.
break statement:
Java break statement
• As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement.
• However, it breaks only the inner loop in the case of the nested loop.
• The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
• That is, we can force immediate termination of a loop, bypassing any remaining code in the
body of the loop. It is mostly used to exit early from the loop by skipping the remaining
statements of loop or switch control structures.

• Syntax: break;
break statement:
Example:

• Here output will be: 0 1 2 3 4 5 Bye


• Because when i=5, if condition will be true. Hence break statement will be executed and it
ends next 4 loops
continue statement:

THE continue STATEMENT

• Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
• Like the break statement, the continue statement also skips the remaining statements of the
body of the loop where it is defined but instead of terminating the loop, the control is
transferred to the beginning of the loop for next iteration.
• The loop continues until the test condition of the loop becomes false.

• Syntax: continue;
continue statement:
Program for continue statement:
Excersize:
Ans: b)
Excersize:
Ans: c)
Excersize:
Ans:
Excersize:
Ans: b
Excersize:
• 25.) What is the main purpose of the “break” statement in a switch-case statement?
• A) To compare the value of the expression.
• B) To terminate the entire program.
• C) To skip the current case and proceed to the next case.
• D) To exit the loop or switch-case statement.

Ans: d

• Which of the following is true about the “default” case in a switch statement?
• A) It is mandatory in every switch statement.
• B) It can be placed anywhere in the switch statement.
• C) It is executed when no other case matches the expression value.
• D) It is used to compare the value of the expression.
Ans: c
Method in Java: Declaration & Types:
Method Declaration:
• Method in java is like function in C programming
• Method is a set of statement which perform particular task
• The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments as follows:
Method in Java: Declaration & Types:
• Simple java program for
method declaration:
Method in Java: Declaration & Types:
Types of Method
• There are two types of methods in Java:
– Predefined Method
– User-defined Method
Method in Java: Declaration & Types:
Predefined Method:
• In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods.
• It is also known as the standard library method or built-in method.
• We can directly use these methods just by calling them in the program at any point.
• Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
• Each and every predefined method is defined inside a class. Such as print() method is defined
in the java.io.PrintStream class.
• Example->
Method in Java: Declaration & Types:
User defined Method:
• The method written by the user or programmer is known as a user-defined method. These methods
are modified according to the requirement.
• Following points need to focus while declaring these methods:
– 1. Method declaration definition
Public void fun(int a, int b)
{
--------------
}
– 2. Method invoking/calling
fun(10,20);
Method in Java: Declaration & Types:
Types of user defined method:
1. Instance method:
• Since the instance method represents behaviour of the objects. Therefore, instance
method is linked with an object.
• An instance method is also known as non-static method. So, instance method must be
called with object of respective class
• Ex- ObjName.methodName();
2. Static method
• If you apply static keyword with any method, it is known as static method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access only static data member of same class or another class.
• Ex- 1. methodName();
or 2. classNmae.methodName(); Example are on next slide
Method in Java: Declaration & Types:
Instance method Static method
Method with multiple parameter:
• In java method can have any number of parameter with combination of any data type
– void method1(int, int)
– void mehtod2(int,float)
– void method3(int,float,char,String)
Points to consider:
• Calling method should have same name as that of defined method
• Calling method should have same number of parameters as like defied method
• Calling method parameters sequence should be same as that of defined method
• Consider following method call for above defined methods
– Method1(10,20) //error
– method2(10, 34.44) //correct
– method3 (100, 89.88, ‘A’, “orchid”) //correct
Method with multiple parameter:
• Program to write two functions for addition of 2 numbers and addition of 3 numbers using
different function
Method with multiple parameter as Varargs:
Variable Arguments (Varargs) in Java
• If there is any change in the number of arguments, we have to declare a new method. This
approach increases the length of the code and reduces readability.
• To resolve these problems, Variable Arguments (Varargs) were introduced in JDK 5. From JDK 5
onwards, we can declare a method with a variable number of arguments. Such types of
methods are called Varargs methods. The varargs feature offers a simpler, better option.
Syntax of Varargs
• Internally, the Varargs method is implemented by using the single dimensions arrays concept.
Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-
length argument is specified by three periods or dots(…).
Method with multiple parameter:
• Write a program to implement one method to deal with different number of parameter using
Varargs
Method overloading:
• If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
• Difference will be count in terms of different number of parameters, different types of
parameters, or both.
• If we have to perform only one operation, having same name of the methods increases the
readability of the program.
• Overloaded methods may have the same or different return types, but they must differ in
parameters.

• Examples:

• Here method func() is overloaded. These methods have the same name but accept different
arguments.
Method overloading:
There are two ways to overload the method in java
• 1. By changing number of arguments
• 2. By changing the data type
1. By changing number of arguments
– Here all methods will have same name
– No two methods will have same numbers of parameters.
– Example: void add(10,20);
void add(10,20,30);
void add(30,40); //error

2. By changing the data type


– Here all methods will have same name
– Two or more methods can have same number of parameters
– But all parameters should be different in terms of their data types
– Example: void add(10, 20);
void add(10.20, 30.40);
void add(60, 1.2);
Method overloading Example:
Program on logical operators:
• Write java program to take 3 numbers from user and display have duplicate number
message if any two numbers are same

• Write java program to display numbers between 100 to 200 if it is divisible by 5 and 10 both

• Write java program to display numbers between 1 to 50 if it is divisible by 2 or 4

• Write java program to add all digit of given number


Input: 123
Output: 6
Math class:
• ava.lang.Math Class methods help to perform numeric operations like square, square root,
cube, cube root, exponential and trigonometric operations.
• If the size is int or long and the results overflow the range of value, the methods addExact(),
subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException.
• Java Math class provides following types of operation:
• Basic math
• Logarithmic methods
• Trignometric methods
• Hyperboloc ,ethods
• Angular math methods:
Math class in Java:
Basic math methodsClass methods help to perform numeric operations like square, square root,
• ava.lang.Math
cube,Method
cube root, exponential and trigonometric operations.
Description
• If the size is int or long and the results overflow the range of value, the methods addExact(),
Math.abs() It will return the Absolute value of the given value.
subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException.
• Java Math class provides following types of operation:
• Basic math
Math.max() It returns the Largest of two values.
• Logarithmic methods
Math.min() It is used to return the Smallest of two values.
• Trignometric methods
• Hyperboloc ,ethods
Math.round() It is used to round of the decimal numbers to the nearest value.
• Angular math methods:

Math.addExact() It is used to return the sum of its arguments, throwing an exception


if the result overflows an int or long.

Math.subtractExact() It returns the difference of the arguments, throwing an exception if


the result overflows an int.

Math.multiplyExact() It is used to return the product of the arguments, throwing an


exception if the result overflows an int or long.
Math class in Java:
Basic math methods
Method Description
Math.abs() It will return the Absolute value of the given value.

Math.max() It returns the Largest of two values.

Math.min() It is used to return the Smallest of two values.

Math.round() It is used to round of the decimal numbers to the nearest value.

Math.addExact() It is used to return the sum of its arguments, throwing an exception


if the result overflows an int or long.

Math.subtractExact() It returns the difference of the arguments, throwing an exception if


the result overflows an int.

Math.multiplyExact() It is used to return the product of the arguments, throwing an


exception if the result overflows an int or long.
Math class in Java:
Trignometric methods:
Method Description

sin Returns the trigonometric value of the sine of an angle.

cos Returns the trigonometric value of the cosine of an angle.

tan Returns the trigonometric value of the tangent of an angle.

asin Returns the trigonometric value of the arc sine of an angle.

atan Returns the trigonometric value of the arc tangent of an angle.

abs Return the absolute value


Math class in Java:
Logarithmic methods:
Method Description
Math.log() It returns the natural logarithm of a double value.

Math.log10() It is used to return the base 10 logarithm of a double value.

Math.log1p() It returns the natural logarithm of the sum of the argument and 1.

Math.exp() It returns E raised to the power of a double value, where E is Euler's


number and it is approximately equal to 2.71828.
Math.expm1() It is used to calculate the power of E and subtract one from it.

Math.log() It returns the natural logarithm of a double value.

Math.log10() It is used to return the base 10 logarithm of a double value.


JAVA Packages:
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java can be categorized in two form, built-in package and user-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
• 1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
• 2) Java package provides access protection.
• 3) Java package removes naming collision.
JAVA Packages:
Starting with packages in java:
• The package keyword is used to create a package in java along with package name
– Example: package pack1;
• Save the file
– Example: Test.java

• Use following commands for program compilation to create package


• javac -d . javafilename
– Example: javac –d . Test.java
• To run the file use following command
• java packageName.filename: Example: java pack1.Test
JAVA Packages:
Steps to create and use package in java
• Step1: Create two java files. Suppose Student.java and Access.java as given below.
Access.java Student.java
JAVA Packages conti…
• Step2: compile both files using following commands
– javac –d . Student.java
– javac -d . Access.java
• Here after compilation two folders with pack1 and pack2 name will be created
• Step 3: run access file using following command
– java pavk2.Access
Here output will be displayed as shown below:
Rollnumber=1
Name=John
Thank you

You might also like