Java Unit 1
Java Unit 1
1) Introduction
2) Object Oriented Paradigm
3) Basic Concepts of Object Oriented Programming
4) Benefits of OOPs
5) Applications of OOP
6) Java History
7) Java Features
8) How Java Differs from C and C++
9) Java Environment
10) Constants
11) Data Types
12) Variables
13) Type Conversion and Casting
14) Automatic Type Promotion in Expression
15) Arrays
16) Operators and Expressions
17) Control Statements
1. INTRODUCTION
Programming languages can be classified into 3 primary types
1) Unstructured Programming Languages:
- has sequentially flow of control
- code is repeated throughout the program
2) Structured Programming Languages:
- Has non-sequentially flow of control.
- Use of functions allows for re-use of code.
3) Object Oriented Programming:
- Combines Data& Action Together.
Let's understand these 3 types with an example.Suppose you want to create
a Banking Software with functions like
Deposit
Withdraw
Show Balance
Unstructured Programming Languages
The earliest of all programming language were unstructured
programming language.
For any further deposit or withdrawal operation – you will code repeat the same
lines again and again.
Structured Programming
With the arrival of Structured programming repeated lines on the code
were put into structures such as functions or methods.
Whenever needed, a simple call to the function is made.
Object-Oriented Programming
In fact, having data and performing certain operation on that data is
very basic characteristic in any software program.
Experts in Software Programming thought of combining the Data
and Operations.
Therefore, the birth of Object Oriented Programming which is
commonly called OOPS.
The data of an object can be accessed only by the methods associated with that
object. However, methods of one object can access the methods of other
objects. Some of the features of object-oriented paradigm are:
1) Emphasis is on data rather than procedure.
2) Programs are divided into what are known as Objects.
3) Data Structures are designed such that they characterize the objects.
4) Methods that operate on the data of an object are tied together in the
data structure.
5) Data is hidden and cannot be accessed by external functions.
6) Objects may communicate with each other through methods.
1) Object
Any Real world entity that has state and behavior is called Object. (0r)
Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors – wagging the tail, barking, eating.
Other Examples of Objects are Apple, Orange, Table, Fan etc..In Java, An
Object is an instance of a Class.
2) Class
Collection of similar objects is called class. For Example Apple, Orange,
Mango objects are grouped into a class called “Fruits” where as apple, table,
fan objects cannot be grouped as a class because they are not similar objects.
It is only an logical component and not the physical entity. Other example, if
you had a class called “Expensive Cars” it could have objects like Mercedes,
BMW, Toyota, etc. Its properties (data) can be price or speed of these cars.
While the methods may be performed with these cars are driving, reverse,
braking etc.In Java, Class defines data and methods that manipulate the
data.
3) Inheritance
Inheritance is an OOPS concept in which one object acquires the properties
and behaviors of the parent object. It’s creating a parent-child relationship
between two classes. It offers robust and natural mechanism for organizing
and structure of any software.
4) Polymorphism
Polymorphism refers to the ability of a variable, object or function to take on
multiple forms. Or it refers as “one interface and many forms “ (or) For
example, in English, the verb “run” has a different meaning if you use it with
OOP offers easy to understand and a clear modular structure for programs.
Objects created for Object-Oriented Programs can be reused in other
programs. Thus it saves significant development cost.
Large programs are difficult to write, but if the development and designing
team follow OOPS concept then they can better design with minimum
flaws.
It also enhances program modularity because every object exists
independently.
Through inheritance, we can eliminate redundant code and extend the
use of existing classes.
We can build programs from the standard working modules that
communicate with one another, rather than having to start writing the
code from scratch. This leads to saving of development time and higher
productivity.
The principle of data hiding helps the programmer to build secure programs
that cannot be invaded by code in other parts of the program.
It is possible to have multiple objects to coexist without any interference.
It is possible to map objects in the problem domain to those objects in the
program.
It is easy to partition the work in a project based on objects.
6. Java History
Year Development
1990 Sun Microsystems decided to develop special software that could
be used to manipulate consumer electronic devices. A team of Sun
Microsystems programmers headed by James Gosling was formed
to undertake this task.
1991 After exploring the possibility of using the most popular object-
oriented language C++, the team announced a new language
named “Oak”
1992 The team demonstrated the application of their new language to
control a list of home appliances using a hand-held device with a
tiny touch – sensitive screen
1993 With the advent of Internet and Web, the team came up with the
idea of developing Applets that could run on all computers
connected to the Internet
1994 The team developed a web browser called “HotJava” to locate and
run applet programs on Internet
1995 Oak was renamed “Java” , due to some legal issues
1996 Java Established itself not only as a leader for internet
programming but also as a general purpose, Object-Oriented
programming language
7. Java Features
Features of a language are nothing but the set of services or facilities provided
by the language vendors to the industry programmers. Some
important features of java are;
a) Simple
b) Platform Independent
c) Architectural Neutral
d) Portable
e) Multi Threading
f) Distributed
g) Networked
h) Robust
i) Dynamic
j) Secured
k) Interpreted & High Performance
l) Object Oriented
a). Simple
According to sun, Java language is Simple because
Most of the concepts are drew from c++ thus making Java Learning Simple
i.e Because java inherits the C++ syntax and many of the Object-Oriented
features of C++, most programmers have trouble learning java.
b) Platform Independent
A Language or technology is said to be platform independent if and only if
which can run on all available operating systems with respect to its
development and compilation. (Platform represents O.S).
c) Architectural Neutral
d) Portable
If any language supports platform independent and architectural neutral
feature known as portable.
The languages like C, CPP, Pascal are treated as non-portable language
where as Java is a portable language, According to SUN microsystem.
Java Programs can be easily moved from one computer system to
another, anywhere and anytime.
Changes and Upgrades in Operating Systems, Processors and System
resources will not force any changes in Java Programs
This is the reason why Java has become a popular language for
programming on Internet which interconnects different kinds of systems
worldwide.
e) Multithreaded
Multithreaded means handling multiple tasks simultaneously. This means
that we need not wait for the application to finish one task before beginning
another. This feature greatly improves the interactive performance of
graphical applications. When any Language execute multiple thread at a time
that language is known as multithreaded Language. Java supports
multithreaded programs.
f) Distributed
Using this language we can create distributed application. RMI and EJB are
used for creating distributed applications. In distributed application multiple
client system are depends on multiple server systems so that even problem
occurred in one server will never be reflected on any client system.
Object
Java also adds some new features, while C++ is a superset of C, Java is neither a
superset nor a subset of C or C++.
Java and C
Java is not lot like C but the major difference between Java and C is that Java is an
object-oriented language and has a mechanism to define classes and objects. In an
effort to build a simple and safe language, the Java team did not include some of the
C features in Java.
It does include the unique statement It does not include the C unique statement
keywords sizeof, and typedef. keywords sizeof, and typedef.
It contain the data type struct and It does not contain the data type struct and
union. union.
It define the type modifiers It does not define the type modifiers
keywords auto, extern, register, keywords auto, extern, register, signed, and
signed, and unsigned. unsigned.
It supports an explicit pointer type. It does not support an explicit pointer type.
It has a preprocessor and therefore It does not have a preprocessor and therefore
we can use # define, # include, and # we cannot use # define, # include, and # ifdef
ifdef statements. statements.
It requires that the functions with It requires that the functions with no
no arguments, with the void arguments must be declared with empty
keyword parenthesis, not with the void keyword
C adds have a break and continue Java adds labeled break and continue
statements. statements.
It does not support destructor function It has replaced the destructor function
with a finalize() function. with a finalize() function.
There are header files in Java. There are no header files in Java.
9. Java Environment
Java Environment include a Large number of
Development tools and
Hundreds of Classes and Methods.
Tool Description
appletviewer Enables us to run java applets
java Java Interpreter, runs application
javac Java compiler, which translates java source code into byte code
javadoc Creates HTML_format documentation from java source code files
javah Produces header files for use with native methods
javap Java dissembler, which enables us to convert bytecode files into a program
description
jdb Java debugger, which helps us to find errors in our program
2) API
The Java Standard Library (or API) includes hundreds of classes and methods
grouped into several functional packages . Most commonly used packages are:
Language Support Package : A collection of classes and methods
required for implementing basic features of java.
Utilities Package : A Collection of classes to provide utility functions
such as date and time functions.
Input/output package: A collection of classes required for input/output
manipulation.
Networking Package: A collection of classes for communicating with other
computers via internet.
AWT Package: The Abstract Window Tool Kit Package contains classes
that implements platform-independent graphical user interface.
10. CONSTANTS
Entities that do not change their values in a program are called constants or
literals.
Java literals are classified into 5 types:
1. Integer Literals
2. Floating Point Literals
3. Character Literals
4. Boolean Literals
5. String Literals
1. Integer Literals
A Whole number is called an integer. Eg: 25,27 etc… are integers
Java supports 3 types of integer literals decimal, octal, hexadecimal.
25,27 are example of decimal integer literals.
Octal integer literals start with 0 and are followed by octal digits 0 to 7.
Eg: 0, 037, 032374 are octal integer literals
Hexadecimal integer literals start with OX and are followed by
hexadecimals digits 0 to 9, A to F. Eg: 0*29, 0*2AB9 are hexadecimal
integers literals.
The width of each type is defined by Java language and do not depend on
the machine in which the program is executed.
The width and ranges of these integer types vary widely as shown in the
below table.
Name Width Range
Long 64 -9,223,372,036,854,775,808 TO
9,223,372,036,854,775,807
Int
The most commonly used integer type is int.
It is a signed 32-bit type that has a Range from -2.147,483,648 to
2.147,483,647
Although we might think that using a byte or short would be more
efficient than using an int in situations in which the larger range of an int
is not needed this may not be the case
The reason is that when byte and short values are used in an
expression they are promoted to int when the expression is evaluated.
Therefore, int is often the best choice when an integer is needed
Long:
Long is a signed 64-bit type and is useful for those occasions where an Int
type is not large enough to hold the desired values.
The range of a long is Quite large
This makes it useful when big, whole numbers are needed
2. Floating Point Types
This group includes float and double which represent numbers with
fractional precision.
There are two kinds of floating point types, float and double, which
represent single and double precision numbers, respectively.
Their width and ranges are shown below.
Name Width in bits Appr
o
xi
m
a
t
e
r
a
n
g
e
Double 64 4.9e-
32
4
to
1.8
e+
30
8
‘//[Float 32 1.4e-
04
5
to
3.4
e+
03
8
Float
The type float specifies a single precision value that uses 32 bits of storage.
Single precision is faster on some processors and takes half as much space as
double precision, but will become imprecise when the values are either very
large or very small.
Variables of type float are useful when you need a fractional component but
don’t require a large degree of precision.
float lowtemp, hightemp
R.Padmaja,Asst.Professor,MCA Department Page 22
Object Oriented Programming Through Java UNIT -I
Double
Double precision, as denoted by the double keyword, uses 64 bits to store a
value.
When you need to maintain accuracy over many iterative calculations,
or manipulating large valued numbers, double is the best choice.
double pi, r, a
Note: Single precision called “float” this is a binary format that occupies 32
bits(4 bytes) and its significant has a precision of 24 bits(about 7 decimal
digits).
Double precision called “double”. This is a binary format that occupies 4 bits (8
bytes) and its significant has a precision of 53 bits about 16 decimal digits.
Note: By default, all floating point numbers are treated as double.
Note: The range of data types is defined by Java Language and does not depend on
the computer on which the data are generated.
3.Characters
In Java, the data type used to
store characters in char.
Char in java is not the same as char in C or C++.
C/C++ char is a 8-bit type whereas java char is a 16-bit type.
Why Java take 2 byte of memory for store character ?
12. Variables
A Variable is an identifier that denotes a storage location used to store a data
value. (or) Variables are the names of storage locations. Unlike constants that
remain unchanged during the execution of a program, a variable may take different
values at different tmes during the execution of the program.
Variable names may consists of alphabets, digits, the underscore and dollar
characters, subject to the following conditions.
1. They must not begin with a digit
2. Uppercase and Lowercase are distinct. This means that the variable Total is
not the same as total or TOTAL.
3. It should not be a keyword
4. White space is not allowed
5. Variable names can be any length
Declaration of Variables
A variable must be declared before it is used in the program. The general form of
declaration of a variable is
If we remove the comment symbol on the line y=100, a compile time error will
occur because y is not visible outside of its block.
The final result of an expression is converted to the type of the variable on the left of
the assignment sign before assigning the value to it. However, the following
changes are introduced during the final assignment.
Note − The style type[] arrayname is preferred. The style type arrayname[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++
programmers.
Example
The following code snippets are examples of this syntax −
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayname = new type[arraySize];
The above statement does two things −
It creates an array using new type[arraySize].
It assigns the reference of the newly created array to the variable
arrayname.
Declaring an array variable, creating an array, and assigning the reference of the
array to the variable can be combined in one statement, as shown below −
type[] arrayname = new type[arraySize];
Alternatively you can create arrays as follows −
type[] arrayname = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based;
that is, they start from 0 to arrayname.length-1.
Following picture represents array myList. Here, myList holds ten double values
and the indices are from 0 to 9.
Two-Dimensional Array
Two-dimensional Array is used to store two dimensional data. Two dimensional
array’s are used to store table of data, which contains rows and columns. . The Two
Dimensional Array in Java programming language is nothing but an Array
of Arrays. If the data is linear we can use the One Dimensional Array but to work
with multi-level data we have to use Multi-Dimensional Array.
Creating an Two-Dimensional array
Data_Type[][] Array_Name = new int[Row_Size][Column_Size];
Initialization of Two Dimensional Array in Java
We can initialize the Two Dimensional Array in multiple ways
First Approach
Declaring and Creating an Array int[]
[] Student_Marks = new int[2][3];
Initializing Array elements in more traditional way
Student_Marks[0][0] = 15; // Initializing Array elements at position [0][0] Student_Marks[1]
[1] = 45; // Initializing Array elements at position [1][1]
second Approach
int[][] Employees = { {10, 20, 30}, {15, 25, 35}, {22, 44, 66}, {33, 55, 77} };
Here, We did not mention the row size and column size but the compiler is intelligent enough to
calculate the size by checking the number of elements inside the row and column
third Approach
Above 3 ways are good to store small number of elements into the array, What if we want to store
100 rows or 50 column values. It will be a nightmare to add all of them using any of the above
mentioned approaches. To resolve this, we can use the Nested For Loop in Java concept here:
int rows, columns;
int[][] Employees = new int[100][50];
In Java Operators are symbols that are used to perform some operations on the operands.They are
used to manipulate primitive Data types.Combination of operands and operators are known
as expression.Java provides a rich set of operators to manipulate the variables.There are three types
of operators in Java.
1. Unary operators
2. Binary operators
3. Ternary operators
1. UNARY OPERATOR:
In which we use one operand is called unary operator.It has two types.
1.1 Increment Unary operator
1.2 Decrement Unary operator
In above example first the value of “a” is assign to the variable “b” .Then increment the
value.So the value of b variable is “10”.
Pre-fix Increment operator:
“++” symbol is used to represent Pre-Fix operator.This symbol is used after the
operand. In this operator value is incremented first and then issigned to a variable.
Example
class preincre
{
public static void main(String aa[])
{
int a,b;
a=10;
b=++a;
System.out.println(“b=”+b);
System.out.println(“a=”+a);
}
}
output:
In above example first the increment is done then the value of “a” variable is assigned to the
variable “b”.So the value of “b” variable is 11.
a. Decrement Unary operator
This is used to decrease the value by one. It has two types.
Post-fix decrement operator
Pre-fix decrement operator
In above example first the value of “a” is assign to the variable “b” .Then decrement the
value.So the value of b variable is “10”.
Pre-fix decrement operator:
“–“ symbol is used to represent the pre-fix decrement operator.This symbol is used after the
operand.
In this operator, value is decremented first and then decremented value is used in expression.
Example
class predecre
{
public static void main(String aa[])
{
int a,b;
a=10;
b=–a;
System.out.println(“b=”+b);
System.out.println(“a=”+a);
}
}
output:
In above example first the value of “a” is decrement then assign to the variable “b”.So the
value of b variable is “9”.
2. Binary operators :
In which we use two operand is called Binary operator. Java supports many types ofBinary
Operator.
1. Assignment Operator
2. Arithmetic Operator
3. Logical Operator
4. Comparison Operator
1. Assignment Operator :
This Operator is used to assign the value. This symbol “=” is used to assign the value . e.g
int a=12;
2. Arithmetic Operator :
This Operator is used to perform mathematical operation on operand .Arithmetic operator are
answer = answer / 2;
System.out.println(“Division is = ” +answer);
// answer is now 1
answer = answer % 2;
System.out.println(“Reminder is = ” +answer);
}
}
output :
Logical operators:
The logical operators || (conditional-OR) , && (conditional-AND) and ! (conditional-
NOT)operates on boolean expressions. Here's how they work.
true
false
In above example “if not true” is asking if the variable “a” variable is not true, otherwise known as
false. If “a” variable is false, Java will display “u r win”. “a”variable is set to true, so that code will not
execute. then the else part is execute shown in output.
Relational operator:
This operator is used to compare the two values ,so this operator is also known as“comparison
operator.”
Conditional symbols and their meanings for comparison operator are below.
Example:
class relat
{
public static void main(String aa[])
{
int a=10;
int b=5;
if (a>b) // “>” relational operator
system.out.println(“a is greater”);
else if (a==b) //”==” relational operator
System.out.println(“a is equal to b”);
else
System.out.println(“enter 1 to 10 number”);
}
}
output:
Ternary operator:
In Ternary operator use three operands. It is also called conditional assignment
statement because the value assigned to a variable depends upon a logical expression.
syntax is :
variable=(test expression) ? Expression 1 : Expression 2
Example:
c=(a>b)?a:b;
c= (a>b) ? a : b ;
Test Condition Expression1 Expression2
Example of Ternary operator:
class terna
{
public static void main(String aa[])
{
int a,b,result;
a=10;
b=20;
result=(a>b)?a:b;
System.out.println(“result=”+c);
}
}
output:
Bitwise Operators
Java provides 4 bitwise and 3 bit shift operators to perform bit operations.
| Bitwise OR
& Bitwise AND
~ Bitwise Complement
^ Bitwise XOR
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
Bitwise and bit shift operators are used on integral types (byte, short, int and long) to perform
bit-level operations.
Operator Description
| Bitwise OR
~ Bitwise Complement
^ Bitwise XOR
Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
The | operator compares corresponding bits of two operands. If either of the bits is 1, it gives 1. If
not, it gives 0. For example,
Example 1: Bitwise OR
class BitwiseOR {
public static void main(String[] args) {
29
Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
The & operator compares corresponding bits of two operands. If both bits are 1, it gives 1. If either of
the bits is not 1, it gives 0. For example,
Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It is denoted by ~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.
result = ~number;
System.out.println(result);
}
}
When you run the program, the output will be:
-36
The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36. Hence, the output
is -36 instead of 220.
Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.
The ^ operator compares corresponding bits of two operands. If corresponding bits are different, it
gives 1. If corresponding bits are same, it gives 0. For example,
Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.
The ^ operator compares corresponding bits of two operands. If corresponding bits are different, it
gives 1. If corresponding bits are same, it gives 0. For example,
21
424
212
3392
If the number is a 2's complement signed number, the sign bit is shifted into the high-order
positions.
c = a | b; /* 61 = 0011 1101
*/ System.out.println("a | b = " + c
);
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
Causes the flow of execution to advance and branch based on changes to the state of a program.
In Java, control statements can be divided into the following three categories:
Selection Statements
Iteration Statements
Jump Statements
Selection Statements
Selection statements allow you to control the flow of program execution on the basis of the outcome of
an expression or state of a variable known during runtime.
The if statements
The first contained statement (that can be a block) of an if statement only executes when the specified
condition is true. If the condition is false and there is not else keyword then the first
contained statement will be skipped and execution continues with the rest of the program. The
condition is an expression that returns a boolean value. General form of simple if statement is
if<expression>
{
Statement-block;
}
Output:
o is even number
4 is even number
6 is even number
8 is even number
10 is even number
if else statement:-
if else statement is an extension of the simple if statement. The general form is
if(expression)
{
True-block statements
}
Else
{
False-block statements
}
if the test expression is true, then the true-block statements immediately following the
if statement are executed. Otherwise, the false-block statements are executed .
In either case, Either true-block or false-block will be executed, not both.
In both the cases, the control is transferred subsequently to the statement-x Diagram
Class IfesleTest
{
Public static void main(Stringargs[])
{
Int number[]={50,65,71,81};
Int even=0,odd=0;
For(int i=0;i<number.length;i++)
{
If((number[i]%2)==0)
even+=1;
else
odd+=1;
}
s.o.p(“even nos:”+even+”odd nos:”+odd);
}
}
o/p:
even nos:2 odd nos:3.
{
if<cond2>
{
if<cond3>
stmt 4
else
stmt3
}
else
stmt2
}
else
stmt 1
else
s.o.p(b);
}
}
}
Output:-
Largest value is:712
se if ladder:-
A common programming construct that is based a sequence of nested is based upon a sequence of
nested ifs is the if else if ladder.
General form of if else ladder
if<condition>
stmt
else if<condition>
stmt;
else if<condition>
stmt;
else
stmt;
The if statements are Executed from the top down. As soon as one of the conditions controlling
the if is true, the stmt associated with that if is Executed, and the rest of the ladder is bypassed.
If none of the condition is true, then the final else stmt will be executed.
The final else acts as a default condition; i.e if all other conditional tests fail, then the last else
stmt is performed.
If there is no final else and all other condition are false.
switch statement:-
The switch statement helps to select one out of many chooses.
It often provides a better alternative than a large d=series of if else if statements
General form of switch statement is
Switch(expression)
{
Case value 1:stmt1;
Break;
Case value 2:stmt2;
Break;
.
.
.
Case value N: stamt N;
Break;
Default:stmt;
}
The expression must be of type byte,short,int or char.
Each of the values specified in the case stmts must be of a type compatible with the expression.
Each case value must be unique literal.
Duplicate case value are not allowed.
The switch stmt works like this
The value of the expression is compared with each of the literal values in the case stmt.
It a match is found, the code sequence following that case stmt is executed.
If none of the constants matches the value of the expression, then the default stmt is executed.
However, the default stmt is optional, if no case matches and no default is present, then
no further action is taken.
The break stmt is used inside the switch to terminate a stmt sequence.
When a break stmt is encountered, execution branches to the first case of code that follows the
entire switch stmt.
A switch stmt is usually more efficient than a set of nested ifs faster than the equivalent logic
coded using a sequence of if else.
Season=”Bogus month”;
s.o.p(“April is in the”+season+””);
}
:-
ril is in the spring
java includes a special ternary (three-way) operator that can replace certain types of if-then-else
stmts.
The conditional or ternary operation has general form as
Expression1?expression2:expression3
ITERATION STMTS:-
A loop repeatedly executes the same set of instruction until a termination condition is met
hile:-
The while loop is java’s most fundamental loop stmt
It repeats a stmt or block while its controlling expression is true.
The general form of while stmt is
While <condition>
{
Body of the loop
}
The 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.
The curly braces are unnecessary if only a single stmt is being repeated.
For ex:-
Class nobody
{
Public static void main( )
{
Int I=100,j=200;
While(++i<--j);//no body in the loop.
s.o.p(“mid point is”+i);
}
}
o/p:-
mid point is 150
The value of I is incremented and j value is decremented
These value compared with one another
If the new value of is still less than the new value of j, then loop repeats
If I is equals to or greater than j the loop stops
Do-while:-
If the conditional expression controlling a while loop is initially false, then the body of the loop
will not executed at all
However, it is desirable to execute the of a loop at least once , even if condition expression is
false to begin with
Fortunately, java supplies a loop that does just that : the do while
The do while loop always execute its body at least once, because its conditional expression is at bottom of loop
do
{
Body of the loop
}
While<condition>
Example:
Class dowhile
{
public static void main( String args[])
{
int n=10;
do
{
s.o.p(“tick”+n);
n--;
}while(n>0);
o/p:-
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Each iteration of the do while loop first executes the body of loop and than evaluates the
conditional expression
If these expression is true these loop repeats, otherwise the loop terminates
Condition must be Boolean expression
the do while is useful when you process a menu slection,
because you will usually want the body of a menu lop to execute atleast
once. For Example:
Class menu
{
Psvm()
{
Char choice;
do{
s.o.p(“1:is”);
s.o.p(“2:switch”);
s.o.p(“3.do-while”);
s.o.p(“4.for”);
}while(choice<’1’||choice>’5’);
Switch(choice)
{
Case 1:
s.o.p(“if is branching statement”);
break;
Case 2:
For statement
{
Psvm(string args[])
{
Int n;
For(n=10;n>0;n--)
s.o.p(“tick”+m);
}
Initialization exp is evaluated only once,then condiotino is evaluated if it is true body of the loop
ecutes and comes to iteration portion if it is false out executing body of the loop goes to iteration
rtion.
:
Class fortick
Psvm()
{
For(int n=10;n>10;n--)
s.o.p(“tick”+n);
}
Nested loop:-
Like all other programming languages, java allows loops to be nested.
i.e one loop may be inside another
eg:-
//loops may be nested
Class Nested
{
P s v m( )
{
Int I, j;
For(i=0;i<10;i++)
{
For(j=I;j<10;j++)
s.o.p(“. “);
s.o.p();
}
}
........
... ....
......
.....
....
...
..
.
2. Jmp stmts:_
Java supports 3 jump stmts
1. break
2. continue
3. return.
break stmt:-
it has 3 uses.
1. It terminates a stmnt sequence in a switch stmt.
2. If can be used to exit a loop.
3. If can be used as a “civilized” form of goto.
When a break stmt is encountered inside a loop. The loop is terminated and program control
resumes at the next stmt following the loop.
i.e by using break, we can force immediate termination of a loop, by passing the conditional
expression (eg:i<=10) and any Remaining code in the vody of the loop.
Eg:-
class BreakLopp
{
P s v m( )
{
For(int i=0;i<100;i++)
{
If(i==0)break;//terminate loop it 1=10
s.o.p(“i=”+i);
}
s.o.p(“loop complete”);
}
}
o/p:-
i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
loop complete.
Break stmnt can be used with any of java’s loops (i.e while, do..while and for loops)
When used inside a set of nested loops, the break stmt will only break out of the innermost loop.
Eg:
Class breakloop
{
P s v m( )
{
For(int i=0;i<3;i++)
{
s.o.p(“pass”+i+”:”);
for(int i=0;j<100;j++)
{
If(j==10)break;
s.o.p(j+” “);
}
s.o.p(“loops complete”);
}
}
}
o/p:-
pass 0:0 1 2 3 4 5 6 7 8 9
pass 1:0 1 2 3 4 5 6 7 8 9
pass 2:0 1 2 3 4 5 6 7 8 9
loops complete
continue:-
sometimes, you might want to continue running the loop but stop continue running the
remainder of the code in its body for this particular iteration
the continue stmt performs such as an action.
Eg:-
Class continue.
{
p s v m( )
{
For(int i=0;i<10;i++)
{
s.o.p(“i+” “); if(i
%2==0)continue; s.o.p(“”)’
}
}
}
Here if I is even, the loop continue without printing a
newline. o/p:-
01
23
45
67
89
3.2 Return:-
Return stmt is used to explicitly return from a method
i.e it causes program control to transfer back to the caller of the method
return stmt can be used to cause execution to branch back to the caller at the method.
CONTROL STATEMENT
Selection Jump
statement Iteration statements
statement
Conditional
For break
operator stmt
Do-while
return
If stmt
For each
Simple if
If-else
Nested -if
Else...if ladder