unit-2
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:
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.
Output:
Decision Making statements: if else statement
Write java program for following task:
• 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
• 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:
Syntax flowchart
do while loop:
• Write java program to display table of 2 output:
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:
• 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
• Write java program to display numbers between 100 to 200 if it is divisible by 5 and 10 both
Math.log1p() It returns the natural logarithm of the sum of the argument and 1.