Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 18

UNIT-I

FUNDAMENTALS OF OBJECT – ORIENTED PROGRAMMING


OBJECT ORIENTED PROGRAMMING PARADIGM:
[Object-Oriented Programming (OOP): [UMP-10M, M17-10M]
It is used to eliminate the drawbacks of procedural language. In this mechanism data and
functionality combined together as a single unit. By using object to used the data and functionality in
Object Oriented Programming technology.
Object oriented language support data abstractions. They can be classified as
1. Object based language = Encapsulation + Object identity and
2. Object oriented language = Object based + Inheritance + Polymorphism
BASIC CONCEPTS OF OBJECT-ORIENTED PROGRAMMING:
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
1. Objects:
Objects can be defined as instance of a class. It is the basic run-time entities in an object-
oriented system. They may represent a person, a place, a bank account, a table of data or any item
that the program has to handle. They may also represent user-defined data such as vectors and lists.
Objects take up space in the memory and have an associated address.
2. Classes:
Class can be defined as a collection of data members and member functions applied on that data.
It is used to create the require classes for a specific purpose like person, bank etc. It is also used to
defined Abstract Data Types( ADT )
3. Data Encapsulation:
Packing data and functions into a single unit is known as encapsulation. it is the most important
feature of a class. The data is not accessible to the outside world. It can be accessed by functions in a
class. These functions provide the interface between the object’s data and the program. This insulation
of the data from direct access by the program is called data hiding.
4. Data Abstraction:
Representing essential features without including the background details are called
abstraction. It is used to create new data types as per user requirement. Classes use the concept of
data abstraction, they are known as Abstract Data Types (ADT)
5. Inheritance:
Derive a new class from an existing base class is called inheritance. It is used to extend or
reuse the existing code without having to rewrite the code from beginning. The new class is having the
combined features of existing class and the new class.
6. Polymorphism:
Polymorphism can be defined as one name many forms. In this each operation may exhibit
different behaviors in different instances. The applications of Polymorphism is
a. Operator Overloading ( Java does not support this )
b. Method Overloading
7. Dynamic Binding:
Binding means link the function call to the function code to be executed at the time of calling.
Dynamic binding (also known as late binding or run time binding ) means that the code associated
with a given function call is not known until the time of the call at run-time. It is associated with
polymorphism and inheritance.
8. Message Passing:
An object-oriented program consists of a set of objects that communicate with each other. The
process of programming in an object-oriented language, therefore, involves the following basic steps:
 Creating classes that define objects and their behavior
 Creating objects from class definitions, and
 Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same way as
people
pass messages to one another. ]
BENEFITS OR FEATURES OF OBJECT-ORIENTED PROGRAMMING:
1. It is possible to build programs from the standard working modules that communicate with
one another
2. Secured programs can be build by using data hiding
3. It is possible to coexist multiple instances of an object
4. It is possible to map objects in the problem domain to those in the program.
5. It is easy to partition the work in a, project based on objects.
6. It is possible to develop software’s having
a. Reusability (reusable components)
b. Reliability
c. Robustness
d. Extensibility
e. Maintainability
7. Data can be centralized to develop detailed modules
8. It can be upgraded easily from small to large systems.
9. Message passing techniques for communication between objects makes the interface
descriptions with external systems much simpler.
10. Software complexity can be easily managed.
APPLICATIONS OF OOPS:
1. Software engineering technology
2. Artificial intelligence and expert systems
3. Real-time systems
4. Simulation and modeling
5. Object-oriented databases
6. Hypertext, hypermedia and expert text
7. Neural networks and Parallel programming Decision
8. support and office automation systems
9. CIM/CAM/CAD systems

[FEATURES OR CHARACTERISTICS OF JAVA LANGUAGE: [M17-5M]


1. Platform Independent:
Java is platform independent language. The programs written on one system can easily run on
another system. Java gets the feature in two ways 1. Java compiler generates byte code
instructions that can be implemented on any machine. 2. The size of the primitive data types are
machine independent. Hence the java program are called the programs Write-Once-Run-
Anywhere.
2. Object Oriented language:
Java is pure Object Oriented. All the data and code written inside the class definition
3. Compiled and Interpreted:
a. Code is compiled to bytecodes that are interpreted by Java virtual machines (JVM).
b. The two steps of compilation and interpretation allow for extensive code checking and
improved security.
4. Robust:
a. It provides compile time and runtime checking for data types. It has a garbage collection
feature.
b. Exception handling is used to eliminate errors in built-in coding.
5. Security:
Code pathologies reduced by
 byte code verifier - checks classes after loading
 class loader - confines objects to unique namespaces. Prevents loading a hacked
"java.lang.SecurityManager" class, for example.
 security manager - determines what resources a class can access such as reading
and writing to the local disk.
6. Simple, Portable, Small and Familiar:
Several dangerous features of C & C++ eliminated:
a. No memory pointers
b. No preprocessors
c. Array index limit checking
Java Software can be easily moved One system to another and easily installed.
7. Dynamic and Extensible:
a. The linking of data and methods to where they are located is done at run-time.
b. New classes can be loaded while a program is running. Linking is done on the fly.
c. Even if libraries are recompiled, there is no need to recompile code that uses classes in those
libraries.
8. High Performance:
Interpretation of byte codes slowed performance in early versions, but advanced virtual
machines with adaptive and just-in-time compilation and other techniques now typically provide
performance up to 50% to 100%.
9. Multi Threading:
a. Lightweight processes, called threads, can easily perform multiprocessing.
b. Great for multimedia displays.
10. Built-in Networking
Java was designed with networking in mind and comes with many classes to develop sophisticated
Internet communications]
[JAVA VIRTUAL MACHINE (JVM): [UMP-5M][M17-10M]
The Java Virtual Machine (JVM) is a program that takes a Java bytecode file (“.class" file) as
input and interprets and executes the instructions in that file.
Java compiler translates the java source code to bytecodes. Bytecode is high-level, machine-
independent instructions for all machines.
The JVM execute the bytecode with the help of java interpreter. java interpreter is acts like an
intermediary between virtual machine and real machine.
The Java run-time system provides the JVM. The JVM interprets the bytecodes during program
execution. All Java programs run on top of the JVM, The JVM was first implemented inside Web
browsers, but is now available on a wide variety of platforms. The JVM interprets the bytecodes
defined in a machine-independent binary fileformat called a class file

Real machine
Operating system

Java virtual machine

Java object framework (API)

Compiler Interpreter

User application program

Users
Parts of Java:
: Naming Conventions in Java
[DATA TYPES IN JAVA: [UMP-10M]

Every variable in Java has a data type. Data type specifies the size and type of values that
can be stored. Java language has rich data types, that a variable can store such as integer,
floating, character, String, boolean etc.
DATA TYPES OF JAVA

Primitive Data types Non-primitive Data types

Numeric Non-Numeric class interface arrays

integer float character String Boolean


byte
float
short

int double

long

The following are the Data types in Java language


JAVA DATA TYPES
BASIC DATA TYPES TYPE
byte
short
Integer
int
Numeric
long
Primitive Data Types ( Basic Data Types ) float
Floating Point
double
character
Non-Numeric String
boolean
classes
Non-Primitive Data types
interfaces
( Derived Data Types )
arrays

1. PRIMITIVE DATA TYPES (BASIC DATA TYPES) :

The basic data types are integer-based and floating-point based. Java language supports
both integer and Real or Floating point data types. The memory size of basic data types may
change according to operating system. The following are Primitive or basic data types.
Data Java Data Memory
S.No. Minimum Value Maximum Value
types Types Size
I Integer
a. byte 1 byte −128 127
b. short 2 bytes −32,768 32,767
c. int 4 bytes −2,147,483,648 2,147,483,647
d. long 8 bytes −9,223,372,036,854,775,808 9,223,372,036,854,775,807
Primitive
II Floating point
Data
a. float 4 bytes 3.4e−038 3.4e+038
Types
b. double 8 bytes 1.7e−308 1.7e+308
III Character
a. char 2 bytes −32,768 32,767
b. String
c. boolean 1 byte −128 127

2. NON-PRIMITIVE DATA TYPES OR DERIVED DATA TYPES:

In Java, Non-Primitive or Derived Data types are defined by the programmer or user. The
following are the best derived or user defined data types.
[a. Class:[UM-5M]
Class can be defined as a collection of data members and member functions applied on that
data. It is used to create the require classes for a specific purpose like person, bank etc. It is also
used to defined abstract data types (ADT)
b. Interface:
An interface is a named collection of abstract methods and constants. In the Java
programming language, an interface is a reference type, similar to a class that can contain only
constants, method signatures (prototypes), and nested types. There are no method bodies. Interfaces
cannot be instantiated they can only be implemented by classes or extended by other interfaces.
Interface declarations in Java introduce a new data type. In Java, interfaces are used to implement
multiple-inheritance.]
c. Array:
it is a user defined data type and it can be defined as a collection of similar data items which are
stored in a continuous sequence of memory locations which are represented by a single variable. It is
a static memory allocation. It stores the values in memory at the fixed size]

[JAVA OPERATORS: [UMP-10M]


An operator is simply a symbol that is used to perform operations. In Java, there can be many
types of operations like Arithmetic, Relational, Logical and Bitwise Operators etc. The following types
of operators are performs different types of operations in JAVA language.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operator
5. Increment and Decrement Operators
6. Ternary or Conditional Operators
7. Bitwise Operators
8. Special Operators

1. ARITHMETIC OPERATORS:

Arithmetic operators performs basic arithmetic operations like Addition, Subtraction,

Multiplication, Divisionand Modulus division etc., Assume variable a holds 10 and variable b holds 20,
then:
S.NO
OPERATOR DESCRIPTION EXAMPLE
.
1. + Addition - Adds values on either side of the operator a + b will give 30
Subtraction - Subtracts right hand operand from left hand
2. - a - b will give -10
operand
3. * Multiplication - Multiplies values on either side of the operator a * b will give 200
4. / Division - Divides left hand operand by right hand operand b / a will give 2
Modulus - Divides left hand operand by right hand operand and
5. % b % a will give 0
returns remainder

6. ++ (Increment)- Increases an integer value by one A++ will gives 11

7 -- (Decrement) - Decreases an integer value by one A-- will gives 9

2. RELATIONAL OR COMPARISON OPERATORS:

These Operators are used to compare two or more Operands or Variables and then produce
either True or False. These Operators are used to build Relational Or Boolean Expressions. Assume

variable a holds 10 and variable b holds 20, then:


S.NO OPERATO DESCRIPTION EXAMPLE
. R
Checks if the values of two operands are equal or not, if yes
1. == (a == b) is not true.
then condition becomes true.
Checks if the values of two operands are equal or not, if
2. != (a != b) is true.
values are not equal then condition becomes true.
Checks if the value of left operand is greater than the value
3. > (a > b) is not true.
of right operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of
4. < (a < b) is true.
right operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to
5. >= the value of right operand, if yes then condition becomes (a >= b) is not true.
true.
Checks if the value of left operand is less than or equal to the
6. <= (a <= b) is true.
value of right operand, if yes then condition becomes true.
3. LOGICAL OPERATORS:

JAVA Language supports the following logical operators – Logical Operators are used to
combine two or more Relational expressions in to a Logical expression. These Logical expressions

produce either True or False. Assume variable A holds 10 and B holds 20, then –
S.NO OPERATOR AND DESCRIPTION
&& (Logical AND) If both the operands are non-zero, then the condition becomes true.
1
Ex: (A && B) is true.

|| (Logical OR) If any of the two operands are non-zero, then the condition becomes true.
2
Ex: (A || B) is true.

! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT
3
operator will make it false. Ex: !(A && B) is false.

4. ASSIGNMENT OPERATORS:

JAVA Language supports the following assignment operators −


S.NO OPERATOR AND DESCRIPTION
= (Simple Assignment ) Assigns values from the right side operand to the left side operand Ex: C = A +
1
B will assign the value of A + B into C

+= (Add and Assignment) It adds the right operand to the left operand and assigns the result to the
2
left operand. Ex: C += A is equivalent to C = C + A

−= (Subtract and Assignment)It subtracts the right operand from the left operand and assigns the
3
result to the left operand. Ex: C -= A is equivalent to C=C–A

*= (Multiply and Assignment) It multiplies the right operand with the left operand and assigns the
4
result to the left operand. Ex: C *= A is equivalent to C = C * A

/= (Divide and Assignment) It divides the left operand with the right operand and assigns the result to
5
the left operand. Ex: C /= A is equivalent to C = C / A

%= (Modules and Assignment) It takes modulus using two operands and assigns the result to the left
6
operand. Ex: C %= A is equivalent to C = C % A

5. INCREMENT AND DECREMENT OPERATOR IN JAVA :


In Java, ++ and -- are Increment and Decrement Operators. These are also “Arithmetic Operators“.
These Operators are Unary Operators. Unary Operator Operates on One Operand.
1. INCREMENT OPERATOR( ++ ) :

The ++ Operator increments a value by 1. It is Used to Increment Value Stored inside


Variable on which it is operating. This Operator performs two types of Unary operations. They are
a. Pre-Increment Operator:

In Pre-Increment Operation, “++” is written before Variable name. Value is Incremented First
and then incremented value is used in expression. “++” cannot be used over “ constant” of “final
Variable“.During Expression evaluation only pre incremented value is used. The syntax of Pre-

Increment Operator is
Syntax: <++ Operator> <Variable name>;
Example: int i=1; ++i;
b. Post Increment Operator:

In Post-Increment Operation, “++” is written after Variable name, First value is used in
expression then Value is Incremented. It is used just after completion of expression evaluation. The
syntax of Post-Increment Operator is
Syntax: <Variable name> <++ Operator>;
Example: int i=1; i++;

2. DECREMENT OPERATOR( -- ):

The -- Operator decremented a value by 1. It is Used to decrement Value Stored inside


Variable on which it is operating. This Operator performs two types of Unary operations. They are
a. Pre-Decrement Operator:

In Pre-Decrement Operation, “--” is written before Variable name. Value is decremented First
and then decremented value is used in expression. “--” cannot be used over “c onstant” of “final
Variable“. During Expression evaluation only Pre decremented value is used. The syntax of Pre-

decrement Operator is
Syntax: <-- Operator> <Variable name>;
Example: int i=1; --i;
b. Post Decrement Operator:

In Post-Decrement Operation, “--” is written after Variable name, First value is used in
expression then Value is decremented. It is used just after completion of expression evaluation. The
syntax of Post-decrement Operator is
Syntax: <Variable name> <-- Operator>;
Example: int i=1; i--;

6. CONDITIONAL OPERATOR (? :):

conditional operator ? : which can be used to replace if...else statements. It has the following

general form
Syntax: Numeric_Variable=(Test-Condition) ? (const1/Variable1/Exp1) : (const2/Variable2/Exp2);
Where const1,2 or Variable1,2 or Exp1,2 Numeric values. In the above syntax If Test condition
is true then const1/Variable1/Exp1 is evaluated and then result is assigned to Numeric_Variable
otherwise const2/Variable2/Exp2 is evaluated and then result is assigned to Numeric_Variable.
Example: K=(A>B && A>C) ? A : B;

7. BITWISE OPERATORS:

Bitwise Operators are used to perform operations on Bits and Bytes, these operations are
called Boolean Operations. JAVA Language supports the following Bitwise Operators −Assume variable
A holds 2 and B holds 3, then –
S.NO OPERATOR AND DESCRIPTION
1 & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2.

2 | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A | B) is 3.

^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR
3
means that either operand one is true or operand two is true, but not both. Ex: (A ^ B) is 1.

4 ~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4.
<< (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second
5 operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2,
shifting two positions is equivalent to multiplying by 4, and so on. Ex: (A << 1) is 4.

<< (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second
5 operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2,
shifting two positions is equivalent to multiplying by 4, and so on. Ex: (A << 1) is 4.

>> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified
6
by the right operand. Ex: (A >> 1) is 1.

>>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted in on the left
7
are always zero. Ex: (A >>> 1) is 1.

8. SPECIAL OPERATORS:

Java supports some special operators such operators are


a. instanceof Operator
b. member selection ( . ) Operator
a. instanceof Operator:

The instanceof is an object reference operator and returns true if the object on the left hand
side is an instance of the class given on the right hand side. This Operator determines whether the
belongs to a particular class or not. The syntax is
Syntax: <Object Name> instanceof <Class Name>;
Example: obj1 instanceof Parent;

class Parent{}
class instanceof Demo
{
public static void main(String[] args)
{
Parent obj1 = new Parent();
System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
}
}
Output: obj1 instanceof Parent: true

b. Dot operator or member selection operator:

The dot operator “ . ” or selection operator is used to access the instance variables and

methods of class objects.]


OPERATOR PRECEDENCE:
The operators in Java, the order of precedence is from highest to lowest Priority based on
Operators Operation Associativity
JAVA OPERATOR PRECEDENCE TABLE
PRECEDENCE OPERATOR TYPE ASSOCIATIVITY
() Parentheses
15 [] Array Subscript Left to Right
· Member selection
++ Unary post-increment
14 Right to left
-- Unary post-decrement
13 ++ Unary pre-increment Right to left
-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 &: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
[CONTROL STATEMENTS IN JAVA: [M17- 10M]
While writing a program, there may be a situation when you need to adopt one out of a given
set of paths. In such cases, you need to use Control statements that allow our program to make
correct decisions and right actions. These Statements are
1. Decision Making and Branching Statements
2. Decision Making and Looping Statements
1. DECISION MAKING & BRANCHING STATEMENTS:

Java Language supports Decision Making and Branching Statements which are used to perform
different actions based on different conditions. Java Language supports the following forms.
If statements:
The if statement in JAVA language is used to perform operation on the basis of condition.
These statements can perform operations either condition is true or false. There are many ways to use
if statement in JAVA language:

1. Simple if statement
2. if...else statement
3. if...else if... statement.(Nested if )
4. Conditional or Terinory Operator
5. switch-case and default statement
1. Simple if statement:

The simple if statement in Java language is used to execute the code if condition is true. The
syntax of if statement is given below:
Syntax: if(Test-Condition)
{
Single Statement; or Group of Statements; //code to be executed
}
Example: class jack
{
public static void main(String args[])
{
int n=0;
if(n%2==0)
{
System.out.println("The Even Number is " + n);
}
}
}

. if-else Statement:
The if-else statement in Java language is used to execute the code if condition is true or false.
The syntax of if-else statement is given below:
Syntax: if(Test-Condition)
{
Single Statement; or Group of Statements; // code to be executed if condition is true
}
else
{
Single Statement; or Group of Statements; // code to be executed if condition is false
}

Example: class jack


{
public static void main(String args[])
{
int n=0;
if(n%2==0)
System.out.println("The Even Number is " + n);
else
System.out.println("The Odd Number is " + n);
}
}

3. Nested if ( if else-if ladder ) Statement:

The Nested if ( if else-if ladder ) is used to execute one code from multiple conditions. The
syntax of Nested if ( if else-if ladder )statement is given below:
Syntax:
if(Test-condition1)
{
Statement or Statements block //code to be executed if condition1 is true
}
else
if(Test-condition2)
{
Statement or Statements block //code to be executed if condition2 is true
}
else
if(Test-condition3)
{
Statement or Statements block //code to be executed if condition3 is true
}
---
---
---
else
{
Statement or Statements block //code to be executed if all the conditions are false
}
Example: class jack

{
public static void main(String args[])
{
int a,b,c;
if(a>b && b>c)
System.out.println("The big is " + a);
else
if(b>a && b>c)
System.out.println("The big is " + b);
else
System.out.println("The big is " + b);
}
}

4. CONDITIONAL OPERATOR (? :):

conditional operator ? : which can be used to replace if...else statements. It has the following

syntax
Syntax: Numeric_Variable=(Test-Condition) ? (const1/Variable1/Exp1) : (const2/Variable2/Exp2);
Where const1,2 or Variable1,2 or Exp1,2 Numeric values. In the above syntax If Test condition
is true then const1/Variable1/Exp1 is evaluated and then result is assigned to Numeric_Variable
otherwise const2/Variable2/Exp2 is evaluated and then result is assigned to Numeric_Variable.
Examples: K=(A>B && A>C) ? A : B;
R=(X==Y) ? (X+Y) : (X-Y);
N=(A>B) ? 100 : 200;
5. SWITCH-CASE-DEFAULT STATEMENT:

The switch statement in Java language is used to execute the code from multiple conditions. It
is like Nested if( if else-if ladder) statement. The syntax of switch statement in Java language is given
below:
Syntax:
switch(Variable or Constant or any expression)
{
case value1: Statement or Statements block; //code to be executed;
break; //optional
case value2: Statement or Statements block; //code to be executed;
break; //optional
case value3: Statement or Statements block; //code to be executed;
break; //optional
------------- -------------
------------- -------------
------------- -------------
default: Statement or Statements block;
//
code to be executed if all cases are not matched;
}
Rules for switch statement in Java language:
1. The switch expression must be of integer or character type.
2. The case value must be integer or character constant.
3. The case value can be used only inside the switch statement.
4. The break statement in switch case is not must. It is optional. If there is no break statement found
in switch case, all the cases will be executed after matching the case value.
Example:
class jack
{
public static void main(String args[])
{
char ch=’o’;
switch(ch)
{
case ‘v’ : System.out.println(“ Violet “); break;
case ‘i’ : System.out.println(“ Indigo “); break;
case ‘b’ : System.out.println(“ Blue “); break;
case ‘g’ : System.out.println (“ Green “); break;
case ‘y’ : System.out.println (“ Yellow “); break;
case ‘o’ : System.out.println (“ Orange “); break;
case ‘r’ : System.out.println (“ Red “); break;
default : System.out.println (“ Enter right choice”);
}
}
}

1. THE WHILE() LOOP:

The most basic loop in Java language is the while loop. The purpose of a while loop is to
execute a statement or statement block repeatedly as long as an expression or Test-condition is true.
Once the expression becomes false, the loop terminates. It iterates the code until condition is false.
The while loop checks the Test condition at the beginning of the loop. This means that this
loop will always be executed if the condition is True. So, it is called Entry Controlled Loop.
Syntax: Exp1;
while (Test-condition)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
Exp2;
}
Where Test-condition is Boolean Expression, Exp1 is initialization expression and Exp2 is
Increment or Decrement expressions. Exp1 and Exp2 are optional.
Example: class jack
{
public static void main(String args[])
{
int i=1;
while(i<=n)
{
System.out.println(i);
i++;
}
}
}

2. THE DO...WHILE() LOOP:

The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the condition
is false. So, it is called Exit Controlled Loop.
Syntax: Exp1;
do
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
Exp2;
} while (Test-condition);
Where Test-condition is Boolean Expression, Exp1 is initialization expression and Exp2 is
Increment or Decrement expressions. Exp1 and Exp2 are optional
Example: class jack
{
public static void main(String args[])
{
int i=1;

do
{
System.out.println(i);
i++;
}while(i<=n);
}
}
DIFFERENCE BETWEEN ENTRY CONTROLLED AND EXIT CONTROLLED LOOPS:
The following C progrming code shoes the difference between entry controlled and exit
controlled loops
i=6; i=6;
while(i<=5) do
{ {
System.out.println(i); System.out.println(i);
i++; i++;
} } while(i<=5);
This code does not produce the output. This code produces the output

3. FOR LOOP:

The 'for( )' loop is the most compact form of looping. It includes the following three important
parts
1. The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
2. The Test Condition which will test if a given condition is true or not. If the condition is true,
then the code given inside the loop will be executed, otherwise the control will come out of the
loop.
3. The Iteration statement (Increment or Decrement) can increase or decrease counter. We can
put all the three parts in a single line separated by semicolons.
Syntax: for (Initialization Statements; Test Condition; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
}
Example: class jack
{
public static void main(String args[])
{
int i=1;
for(i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
A. BREAK STATEMENT:

The break statement in Java language is used to break the execution of loop (while(), do-
while() and for() ) and switch-case-default. In case of inner loops, it terminates the control of inner
loop only. There can be two uses of Java break keyword: is
1. With loop
2. With switch case
1. break Statement with Loop:
Syntax:
The syntax of for loop is Java language is as follows
for (Initialization Statements; Test Condition; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
jumping Statement
break;
}
The break Statement can be write in while() loop, do-while() loop, for() loop and switch-case-
default() statements.

Example: class jack


{
public static void main(String args[])
{
int i;
for( i=1; i<=5; i++)
{
if (i==3)
break;
System.out.println(i);
}
}
}
2. break statement with switch case:

The break statement in switch case is not must. It is optional. If there is no break statement
found in switch case, all the cases will be executed after matching the case value. The syntax of break
statement with switch case default is.

Syntax:
switch(Variable or Constant or any expression)
{
case value1: Statement or Statements block; //code to be executed;
break; //optional
case value2: Statement or Statements block; //code to be executed;
break; //optional
case value3: Statement or Statements block; //code to be executed;
break; //optional
------------- -------------
------------- -------------
default Statement or Statements block;
// code to be executed if all cases are not matched;
}
Example:
class jack
{
public static void main(String args[])
{
char ch=’o’;
switch(ch)
{
case ‘v’ : System.out.println(“ Violet “); break;
case ‘i’ : System.out.println(“ Indigo “); break;
case ‘b’ : System.out.println(“ Blue “); break;
case ‘g’ : System.out.println (“ Green “); break;
case ‘y’ : System.out.println (“ Yellow “); break;
case ‘o’ : System.out.println (“ Orange “); break;
case ‘r’ : System.out.println (“ Red “); break;
default : System.out.println (“ Enter right choice”);
}
}
}
B. JAVA CONTINUE STATEMENT:

The continue statement in Java language is used to continue the execution of loop (while, do
while and for).It is used with if condition within the loop. In case of inner loops, it continues the
control of inner loop only.
Syntax: for (Initialization Statements; Test Condition; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
if( Test Condition )
continue;
----------
}
Example: class jack
{
public static void main(String args[])
{
int i;
for( i=1; i<=5; i++)
{
if (i==3)
continue;
System.out.println(i); }
} ]

You might also like