Control Statements
Selection Statements
JAVA SUPPORTS TWO SELECTION STATEMENTS.
THEY ARE
if
Switch
THESE STATEMENTS ALLOW THE USER TO CONTROL THE FLOW OF
PROGRAM'S EXECUTION BASED UPON CONDITIONS KNOWN ONLY
DURING RUN TIME.
If, else, Nested ifs, if-else-if ladder
Contd…
CONDITIONAL STATEMENTS:
CONTROL BRANCHES TO THE STATEMENTS BASED ON THE CONDITION.
CASE 1:
IF(CONDITION)
STATEMENT;
CASE 2:
IF(CONDITION)
STATEMENT;
ELSE
STATEMENT;
Contd…
CASE 3:
IF(CONDITION)
STATEMENT;
ELSE IF CONDITION
STATEMENT;
ELSE
STATEMENT;
Contd…
CASE 4:
IF(CONDITION)
STATEMENT;
ELSE IF CONDITION
STATEMENT;
ELSE IF CONDITION
STATEMENT;
ELSE IF CONDITION
STATEMENT;
ELSE
STATEMENT;
Contd…
Contd…
Contd…
Contd…
Switch Statement
IT IS A MULTIWAY BRANCHING STATEMENT.
IT IS ALSO AN CONDITIONAL STATEMENT.
SELECTING ONE STATEMENT OR ONE ALTERNATIVE OUT OF SET OF
STATEMENTS OR SET OF ALTERNATIVES
IT PROVIDES AN EASY WAY TO DISPATCH EXECUTION TO DIFFERENT
PARTS OF THE CODE BASED ON THE VALUE OF AN EXPRESSION.
SOMETIMES WE CAN HAVE MULTIPLE CASES WITHOUT BREAK
STATEMENTS BETWEEN THEM.
Contd…
There can be one or N number of case values for a switch expression.
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.
Syntax
switch(expression)
{
case label:
statement;
break;
case label:
statement;
break;
case label:
statement;
break;
default:
statement;
}
Flow Chart
Nested Switch Statements
Nested-Switch statements refers to Switch statements inside of another
Switch Statements.
Easy to maintain.
More efficient than if-else.
Easy to debug.
It performs execution at a faster pace.
Switch statement is usually more efficient than a set of nested ifs.
Switch looks only for a match between the value of the expression and one
of its case constants.
No two case constants in the same switch can have identical values. A
switch statement and an enclosing outer switch can have case constants in
common.
Iteration Statements
Java iteration statements are for, while and do-while. These
statements creates what we call loops.
A loop repeatedly executes the same set of instructions until a
termination condition is met.
While Loop
While loop repeats a statement or block while its controlling expression is
true.
while (condition)
{
// body of loop
}
Condition can be any Boolean expression.
The body of the loop will be executed as long as the conditional
expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop.
Curly braces are unnecessary if only a single statement is being repeated.
Contd….
Do-While Loop
The do-while loop always executes its body at least once, because its
conditional expression is at the bottom of the loop.
do
{
// body of loop
} while (condition)
Each iteration of the do-while loop first executes the body of the loop
and then evaluates the conditional expression. If this expression is
true, the loop will repeat. Otherwise the loop terminates.
Contd…
Simple for loop
We can initialize the variable, check condition and increment/decrement value. It consists of four
parts:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value either true
or false. It is an optional condition.
Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
Statement: The statement of the loop is executed each time until the second condition is false.
Contd…
Contd…
If only one statement is being repeated, there is no need for the curly
braces.
Scope of the loop variable is limited to the for loop.
Infinite loop: One of the most common mistakes while implementing
any sort of looping is that it may not ever exit, that is the loop runs
for infinite time. This happens when the condition fails for some
reason
for each – enhanced for loop
For-each is designed to cycle through a collection of objects. (Ex :
Array).
Syntax : for(type itr-var : collection) statement block
type specifies the type.
itr-var specifies the name of an iteration variable that will receive the
elements from a collection , one at a time, from beginning to end.
Collection – Array, Map, List…etc
With each iteration of the loop , the next element in the collection is
retrieved and stored in itr-var.
The loop repeats until all elements in the collection have been
obtained.
Type must be same as the elements stored in the collection.
Contd…
Advantages
It makes the code more readable.
It eliminates the possibility of programming errors.
Disadvantages
The drawback of the enhanced for loop is that it cannot traverse the
elements in reverse order.
We do not have the option to skip any element because it does not
work on an index basis.
We cannot traverse the odd or even elements only.
Contd…
int ar[] = { 10, 50, 60, 80, 90 };
for (int element : ar)
System.out.print(element + " ");
for (int i=0; i<ar.length; i++)
{
int element = arr[i];
System.out.print(element + " ");
}
Jump Statements
Java supports three jump statements :
Break statement.
Continue statement.
Return Statement
Using Break Statement to exit a loop
Break statement is used to terminate the execution of the nearest
looping statement or switch statement.
The break statement is widely used with the switch statement, for
loop, while loop, do-while loop.
Break statement in the inner loop only causes termination of that
loop. The outer loop is unaffected.
Contd…
Use Break as a form of goto
Java does not have a goto statement because it produces an
unstructured way to alter the flow of program execution.
Java illustrates an extended form of the break statement.
This form of break works with the label. The label is the name of a
label that identifies a statement or a block of code.
Continue Statement
The continue statement pushes the next repetition of the loop to take
place, hopping any code between itself and the conditional
expression that controls the loop.
Contd…
Return Statement
The “return” keyword can help you transfer control from one method
to the method that called it.
Since the control jumps from one part of the program to another, the
return is also a jump statement.
It causes program control to transfer back to the caller of the method.
Return statement immediately terminates the method in which it is
executed.
“return” is a reserved keyword means we can’t use it as an identifier.
It is used to exit from a method, with or without a value.
Class Fundamentals
In Java, classes and objects are basic concepts of Object Oriented
Programming (OOPs) that are used to represent real-world concepts
and entities.
A class in Java is a set of objects which shares common
characteristics/ behavior and common properties/ attributes.
It is a user-defined blueprint or prototype from which objects are
created. For example, Student is a class while a particular student
named Ravi is an object.
Properties of Java Classes
Class is not a real-world entity. It is just a template or blueprint or
prototype from which objects are created.
Class does not occupy memory.
Class is a group of variables of different data types and a group of
methods.
A Class in Java can contain:
Data member
Method
Constructor
Nested Class
Interface
Class Declaration
access_modifier class <class_name>
{
data member/Instance Variable;
method;
constructor;
nested class;
interface;
}
Contd…
Data or Variables defined within a class are called instance variables.
Code is obtained within methods.
Collectively the methods and variables defined within a class are
called members of the class.
Variables defined within a class called instance variables because
each instance of the class contains its own copy of these variables.
Object Declaration
An entity that has state and behavior is known as an object e.g.,
chair, bike, marker, pen, table, car, etc.
It can be physical or logical
An object has three characteristics:
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user. However, it is
used internally by the JVM to identify each object uniquely.
Contd…
Box mybox = new Box();
Mybox as a reference to an object of type Box.
New operator dynamically allocates memory for an object.
Constructor
A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes:
CONSTRUCTOR SHOULD HAVE THE SAME NAME AS THAT OF THE
CLASS NAME.
CONSTRUCTOR DOES NOT HAVE RETURN TYPE BECAUSE IT RETURNS
THE INSTANCE OF THE CLASS ITSELF.
CONSTRUCTOR CAN BE OVERLOADED.
CONSTRUCTOR MAY NOT BE STATIC
Contd…
TYPES OF CONSTRUCTOR:
• DEFAULT CONSTRUCTOR
• PARAMETERIZED CONSTRUCTOR
DEFAULT CONSTRUCTOR :
CONSTRUCTOR WITH NO ARGUMENTS OR PARAMETERS CALLED DEFAULT
CONSTRUCTOR.
PARAMETERIZED CONSTRUCTOR:
• SINGLE PARAMETER CONSTRUCTOR
• MULTI PARAMETER CONSTRUCTOR
How Java Constructors are Different
From Java Methods?
Constructors must have the same name as the class within which it is
defined it is not necessary for the method in Java.
Constructors do not return any type while method(s) have the return
type or void if does not return any value.
Constructors are called only once at the time of Object creation while
method(s) can be called any number of times.
Contd…
Method Overloading
In Java, Method Overloading allows different methods to have the
same name, but different signatures where the signature can differ by
the number of input parameters or type of input parameters, or a
mixture of both.
Method overloading in Java is also known as Compile-time
Polymorphism, Static Polymorphism, or Early binding.
Different Ways of Method Overloading in Java
Changing the Number of Parameters.
Changing Data Types of the Arguments.
Changing the Order of the Parameters of Methods
Contd…
Advantages of Method Overloading
Method overloading improves the Readability and reusability of the
program.
Method overloading reduces the complexity of the program.
Using method overloading, programmers can perform a task
efficiently and effectively.
Using method overloading, it is possible to access methods
performing related functions with slightly different arguments and
types.
Objects of a class can also be initialized in different ways using the
constructors.
Constructor Overloading in Java
Java supports Constructor Overloading in addition to overloading
methods.
In Java, overloaded constructor is called based on the parameters
specified when a new is executed.
Sometimes there is a need of initializing an object in different ways.
This can be done using constructor overloading.