Object Oriented Programming Using Java
Object Oriented Programming Using Java
III Semester 1
Unit - I
Fundamentals of object - Oriented programming:
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 2
Year Progress
1990 Sun decided to developed software that could be used for electronic devices. And the
project called as Green Project head by James Gosling.
1991 Announcement of a new language named “Oak”
1992 The team verified the application of their new language to manage a list of home
appliances using a hand held device.
1993 The World Wide Web appeared on the Internet and transformed the text-based
interface to a graphical rich environment.
1994 The team developed a new Web browser called “Hot Java” to locate and run Applets.
1995 Oak was renamed to Java, as it did not survive “legal” registration. Many companies
such as Netscape and Microsoft announced their support for Java.
Version 1.0 of Java Development kit (JDK) was released for free by sun micro
systems.
1996 Java language is now famous for Internet programming as well as a general purpose
Object oriented language.
1997 Sun releases Java Development Kit(JDK 1.1)
1998 Sun releases Software Development Kit (SDK 1.2)
1999 Sun releases Java 2 platform Standard Edition (J2SE) and Enterprise Edition J2EE).
This comes to three editions.
J2SE – Java 2 standard edition
J2ME- Java 2 Micro Edition
J2MEE – Java 2 Enterprises Edition
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released. ( Previously numbered 1.5)
2006 Java SE 6 ( Previously numbered 1.6)
2011 Java SE 7 ( Previously numbered 1.7)
2014 Java SE 8 ( Previously numbered 1.8)
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 3
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 4
Advantages:
The goal of structured programming is to write correct programs that are easy to
understand and modify.
Modules enhance the programmer‟s productivity.
With modules, many programmers can work on a single large program, with each
working on different module.
A structured program can be written in less time than an unstructured program.
Modules or procedures written for one program can be reused in both programs as
well.
A structured program is easy to debug.
Individual procedures are easy to change as well as understand.
Method Method
Object = Data + Methods
Data
Method Method
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 5
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 6
Class is structure representing the data and its related and corresponding functions.
For example Mango, Apple and Orange are objects of the class “Fruit”.
Fruit Mango;
Object:
Object is the basic run time entity in a object oriented
system.
Object may represent a person, a place, a bank account
or any item that the program may handle.
Each object contains both data and code to manipulate
the data.
Objects are the variables of classes.
Encapsulation:
The concept of binding the data along with its corresponding and related functionalities
is known as encapsulation.
The concept of encapsulation was invented in order to provide highest security for the
data part of an application and make programming simple.
Example: Company – in company, the department access and work with their data (on their
own). One department cannot access the data of other department directly
Inheritance:
The mechanism of deriving a new class from an old one is called inheritance. The old
class is referred to as base class and new one is called as derived class.
Example: Automobiles and pulled vehicles are sub class of vehicles, vehicles is the base class of
automobiles and pulled vehicles.
Car and bus are sub classes of „automobiles‟. „Automobiles‟ is the base class of car and bus.
Vehicles
Car Bus
Data abstraction:
It refers to the act of representing essential features without including the background
details or explanation.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 7
Example: Switch board- you only press certain switch according to your requirement. What is
happening inside, how it is happening etc. you need to know, again this is abstraction. You
only the essential things to operate on switch board without knowing the background details of
the switchboard.
Polymorphism:
(Poly means ―many and morph means ―form). Polymorphism means the ability to take
more than one form. Polymorphism is broadly used in implementing inheritance.
Polymorphism is the ability for a message or data to be processed in more than one form.
Example: If you give 5+7, it results into 12, the sum of 5&7. If you give ‘A+ BC’ it results
into ‘ABC’ the concatenated strings. The same operation ‘+’ is able to distinguish between
the two operations depending upon the type it is working on.
The following diagram shows that a single method name draw() can be used to
handle different numbers and types of arguments.
Shape
Draw () Draw ()
Message Passing
Draw ()
An OOP consists of the set of objects that communicate with each other. Objects
communicate with one another by sending and receiving information in the same
way people pass messages to one another as shown below.
Object1
Object3
Object2
Object4 Object5
The message passing involves specifying the name of the object, name of the
method and information to be sent. For example consider a statement:
Student .marks (htno);
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 8
1) Through inheritance we can eliminate redundant code and extend the use of extend
the use of existence class.
2) It is possible to have multiple instances of an object to co-exist without any interface.
3) It is easy to partition the work in a project based on objects.
4) User defined data types can be easily created.
5) Software complexity can be easily managed.
6) Inheritance enforces inventions of new data types.
7) Object oriented systems can be easily upgraded from small to large systems.
8) It is possible to map objects in problem domain to those objects in the program.
9) The principle of data hiding helps the programmer to build secure programs that can
be accessed by code in other parts of the program.
10) We can build programs from standard working modules this leads saving of
development time.
6. Applications of OOP:
OOP is used in the development of most software systems.Today oops is used in the design of
Graphical User Interface (GUI) on systems such as windows operating system.
Artificial Intelligence and expert system.
Simulation and modeling studies.
Object oriented data bases systems.
Object oriented operating systems.
Real time systems.
Office Automation system.
CAD/CAM systems.
Multimedia applications and Graphical User Interface (GUI).
Computer based training educations.
Data recovery systems.
Distributed systems.
Audio and Video manipulation tools.
Image processing tools.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 9
Simple: - Java programming language is very easier. It is syntactically similar to C and C++.
Complex features of these languages are either simplified or totally eliminated in Java.
Object Oriented:-Unlike C++, Java purely object oriented programming language. Java
programs use classes and objects. We call any language as object oriented programming
language when it has the five features. 1. Classes and objects 2.Encapsulation 3.Abstraction
4.Inheritance 5.Polymorphism.
Robust (Strong/ Powerful): -Java is a most strong language which provides many securities to
make certain reliable code. Java programs will not crash because of its exception handling and
its memory management features.
Secure: - Java is designed for use on Internet. Security problems like eyes dropping; tampering,
impersonation and virus can be eliminated. Thus java programs are useful in construction of
highly secure systems.
High- Performance:- When compared to other interpreted languages, Java offers high
performance. Along with interpreter there will be JIT (Just In Time) compiler which enhances
the speed of execution.
Architectural-neutral:- This feature is in accordance with the sun Microsystems slogan about
java programs. “Write once and run anywhere”. This feature is famously known as platform
independence. Java byte code is not machine dependent; it can run on any machine with any
processor and with any OS.
Interpreted:- Java programs are both compiled and interpreted. JVM interprets the class file
into machine code.
Multithreaded: - A thread is an individual process in a program. Each thread (or process) can
execute block of statements and perform a separate task. Thus multiple threads can perform
multiple tasks. This is an essential feature to design server side programs.
Distributed:- Java has rich libraries for network programming and distributed computing. As
java is mainly meant for Internet based programming, it is no surprise that java is distributed.
An application is said to be distributed if the business objects are geographically dispersed in the
network and communicating one another.
Dynamic: - Java is also dynamic language. Java is capable of dynamically linking in new class,
libraries, methods and objects. We can develop programs in Java which dynamically change on
Internet (e.g.: Applets).
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 10
Document section
Package Statements
Import Statements
Interface Statements
Class Definitions
1) Document Section:
This is an optional section
This section consist information about the program
It is not understand by compiler
This documenttation is provided by using comments.
Java supports three methods of documentation.
// ………….. ……. Single line comment
/* ……………… */ Multiline comment
// * …………. *// Document comment
2. Package Statement:
It is an optional section.
This statement declares a package name and informs the compiler that the classes
defined here are belongs to this package.
package student;
3. Import statement:
Similar to #include statement in C.
This statement is used for importing existing packages.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 11
Attributes;
Methods;
class Simple
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 12
Class declaration:
The first line class “Simple” declares a class; everything must be placed inside a class. „Simple‟
is a java identifier that specifies the name of the class. „class’ is a keyword and declares a new
class definition.
Opening brace:
Every class definition in Java begins with an opening brace and ends a matching closing brace.
The main line:
The third line “public static void main(String args[])” defines a method named main. Every
Java program must include main() method.
Public – The keyword public is an access specifier that declares the main
method is accessible to all other classes.
Static – The keyword static declares the method that belongs to entire class.
There is no need to create an object to invoke the static method.
Void – The type modifier void specifies that the main method doesn‟t return any
value.
String args[] – Declares a parameter args[],is used for command line argument.
The output line:The statement “System.out.println(“Java is better than
C++”);”This is similar to the printf() statement of „C‟. The println method is a
member of out object, which is static data member of System class. This line
prints the string
Helo Good Morning, I am Mahesh
The method println always appends a new line character to the end of the string. Every Java
statement must end with a semicolon.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 13
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 14
Identifiers
An identifier is a name given to the program elements such as variables, arrays, classes,
objects, methods, labels, packages and interfaces. Identifiers may consist of sequence of
letters, numerals, or underscores.
Rules for forming identifier names:
Identifiers cannot include any special characters or punctuation marks (like #, ,
^,?,., etc) except $ and underscore.
Keywords cannot be used as identifiers.
Length of identifier is unlimited.
In identifier declarations name of the variable must starts with alphabet or
underscore only.
Examples: roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code
Literals:
Literals are sequence of characters(digits, letters, and other characters) that represent constant
values to be stored in variables. Java language specifies 5 types of literals.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 15
Statement Description
7. Synchronization Statement
These are used for handling multithreading.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 16
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 17
Hello
Welcome to Java
The virtual machine code is not machine specific. The machine code is
generated by the java interpreter by acting an intermediary between the virtual
machine and real machine.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 18
This command line contains 4 arguments. These are assigned to the array args as follows
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 19
Integer Constants:
Real Constants:
The numbers with decimal point is called as real constants or floating point
constants. Real constants are expressed either in decimal notation or exponential
notation.
String Constants:
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 20
Data types are the keywords and tell the compiler which type of data (information)
is maintained in memory.Data types will decide what type of values need to be
hold into variables.
In Java, we have eight data types which are organized in four groups. They are
integer category data types, float category data types, character category data
types and Boolean category data types.
DATA TYPES
Byte Float
Char Boolean
Short Double
int
long
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 21
1. Integer Category data types: These are used to represent integer data type
contains four data type which are given in the following table.
17. What is variable and write the rules to follow while selecting a variable?
Variable:
A variable is defined as a meaningful name given to a data storage location in computer
memory. Or
A Variable is a quantity that does change during the program execution.
Rules for forming identifier names:
The variable must begin with an alphabet.
Upper and lower case letters are different.
It should not be a keyword.
White space is not allowed.
Variables names can be of any length.
Name of the memory location is called variable.
Before using any variable in the program it must be declare first.
Declaration of variable means need to mention data type, name of the
variable followed by semicolon.
In variable declarations name of the variable must starts with alphabet or
underscore only.
In variable declaration existing keywords operators, separators, constants
and any other special characters will be not allowed.
Declaration of variables
The general form is
Here, variables are separated by commas and the declaration must end with a
semicolon.
Syn: variablename=value;
Eg: a=10;
We can also assign a value to variable at the time of declaration.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 23
Statement n = s.nextInt(); is used to input the value of an integer variable 'n' from the user.
Method Inputs
nextInt() Integer
nextFloat() Float
nextDouble() Double
nextLong() Long
nextShort() Short
next() Single word
nextLine() Line of Strings
nextBoolean() Boolean
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 24
Scope is how far a variable can be accessed. The scope of variables is depends on
location where a variable is declared. A block is begin with an opening curly brace
and ended by a closing curly brace. Java allows variables to be declared with in
any block. A block defines a scope.
The scope defined by a method begins with it‟s opening brace. However, if that
method has parameters, they are also included within the method‟s scope. So we
can protect from unauthorized access and modification. Java variables are
classified into three kinds.
1. Instance variables.
2. Static Variables (Class variables)
3. Local variables.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 25
Local variables:
Variables declared and used inside methods are called local variables.
They are not available for use outside the method definition.
Local variables can also be declared inside program blocks that are defined
between an opening brace { and a closing brace }.
There is no special keyword for declaring local variable.
int x = 0;
{
------- Block 1
int n = 5; Block 2
-------
}
{
-------
int m = 10; Block3
-------
}
Each block contains its own set of local variable declarations. In the above figure
the variable x declared in block 1 is available in all the three blocks. The variable
n declared in block 2 and is available only in block 2. Similarly m is accessible in
block3.
class VariableType
{
int a=10; //instance variable
static int b=20; //static variable
public int m1()
{
int c = 30; //local variable
System.out.println("c = "+c);
return 0;
}
public static void main(String args[])
{
VariableType v = new VariableType ();
System.out.println("a = "+v.a+" b = "+b);
v.m1(); //invoke the m1 method
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 26
When we don‟t want to change the value of the variable, then that variable must
be declared as final.
A symbolic constants can be declared with the following format
For example:
Final int a=10;
a=a+20; //invalid
a=30; //invalid
Symbolic names take the same from as variable names. But they are written in
CAPITALS to make difference from normal variable names.
After declaration of symbolic constants they shouldn‟t be assigned any other
value in the program.
They cannot be declared inside a method. They should be used only as class
data members in the beginning of the class.
Type casting is the process of converting the value in one data type to another
data type. It uses the following syntax.
type var1 =( type ) var2;
Ex:- int m=50;
byte b = (byte) m;
short b = (short) m;
Casting is often necessary when a method returns a type different than one we
required. Four integer types can be casted to any type other than Boolean. Casting
into smaller type may result in the loss of data. Similarly the float and double can
be casted into any type except Boolean. Casting a floating point value to an integer
will result in the loss of fractional part.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 27
From To
byte short,int,long,float,double.
short int,long,float,double.
char int,long,float,double.
Int long,float,double.
long float,double.
float double
double
For some types, it is possible to assign a value of one type to a variable of a different type
to a cast.java does the conversion of the assigned value automatically this is known as
automatic conversion. Automatic type conversion is possible only if the destination type has
enough precision to store the source value.
Automatic type conversion is possible only the process of assigning a smaller type to a
large is known as promotion or widening.
Eg: byte a=10;
int a=b;
Narrowing:
The process of assigning a large type to a smaller type is known as “narrowing”. This may
result in the loss of information. Narrowing is also known as explicit type casting. It is
programmers responsibility to cast(convert) large type to small data type.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 28
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 29
And (&&)operator: Logical and(&&) returns when both operands are true otherwise it returns
false.
A B A && B
T T T
T F F
F T F
F F F
Or (||)operator : Logical or (||)returns true when either of it‟s operands are true and returns
false if both the operands are false.
A B A || B
T T T
T F T
F T T
F F F
Not (!) operator: This operator negates the result of a expression. It means if the condition is
true then it gives false and if the condition is false then it gives true.
A !A
T F
F T
4. Assignment operator: It is a binary category operator which is used to assign
the right side value to left side. When we are working with binary operators it
should require and among those two operands.
Syntax: L=R;
When we are working with left side argument must be variable type only, and right
argument is optional.
Simple Assignment :
The general form of the simple assignment is
Ex : a=b=1;
M=n=g=a+b;
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 30
Pre-increment: If the „++‟ operator precedes the operand then it is called “Pre
increment”. In this method, the pre-increment operator increments the value of
variable first and then the new value is used in the expression.
For example: c = ++a; means a = a + 1;
c = a;
Post-increment: If the „++‟ operator succeeds the operand then it is called “Post
increment”. In this method, the old value of the variable is used in expression and
then it is incremented.
For example: c = a++; means c = a;
a = a + 1;
Decrement Operator (– –):
The decrement operator is a unary operator. It is used to decrease the
value of an operand by 1. The operand must be a variable. The decrement
operator „– –‟ has different meaning depending on the position it is used. It means
this operator is used in two ways. They are pre-decrement and post-decrement.
Pre-decrement: If the „– –‟ operator precedes the operand then it is called “Pre
decrement”. In this method, the pre-decrement operator decrements the value of
variable first and then the new value is used in the expression.
For example: c = – –a; means a = a – 1;
c = a;
Post-decrement: If the „– –‟ operator succeeds the operand then it is called “Post
decrement”. In this method, the old value of the variable is used in expression and
then it is decremented.
For example: c = a– –; means c = a;
a = a – 1;
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 31
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 32
Operator Meaning
& Bitwise AND
¦ Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ 1‟s complement
<< Left shift
>> Right shift
>>> Right shift with Zero fill
Bitwise AND (&) operator: If all the bits are “1” then this operator returns “1”
otherwise it returns “0”.
Truth table:
& 1 0
1 1 0
0 0 0
Example: Let x = 15 and y = 19, then z = x & y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00000011
(x & y)
Bitwise OR ( ¦ ) operator: If any or all the bits are “1” then it returns “1”
otherwise it returns “0”.
Truth table:
¦ 1 0
1 1 1
0 1 0
Example: Let x = 15 and y = 19, then z = x ¦ y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00011111
(x ¦ y)
Bitwise XOR ( ^ ) operator: If one bit is “1” and other is “0” then it returns “1”
otherwise it gives “0”.
Truth table:
^ 1 0
1 0 1
0 1 0
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 33
Value of x : 00001111
Value of y : 00010011
Value of z : 00011100
(x ^ y)
1‟s complement (~) operator: This operator is a unary operator that reverses the
state of each bit. That means it changes “0” as “1” and “1” as “0”.
Example: Let x = 19, then z = ~x is as follows
Value of x : 00010011
Value of z : 11101100
( ~x )
Left Shift (<<) operator:
This operator is used to move bit patterns to the left. It is used in the following
form op<<n
Here, „op‟ is an integer value and „n‟ is number of bit positions. The left shift
operator shifts all the bits of operand „op‟ to the left by „n‟ positions. The left most
„n‟ bits in the original bit pattern will be lost and right most „n‟ bit positions are
filled with zeros.
Example: Let us consider „a‟ is an unsigned integer whose bit pattern is as
follows:
a 1100110011001111
a<<3 0110011001111000
a<<5 1001100111100000
The left shift operator is used for multiplication purpose. It means, x<<n gives the
result as x*2n.
Example : 5<<1 gives 10, 5<<2 gives 20, 5<<3 gives 40
Right Shift (>>) operator:
This operator is used to move bit patterns to the right. It is used in the following
form
op>>n
Here, „op‟ is an integer value and „n‟ is number of bit positions. This operator shifts
all the bits of operand „op‟ to the right by „n‟ positions. The right most „n‟ bits in
the original bit pattern will be lost and left most „n‟ bit positions are filled with
zeros.
Example: Let us consider „a‟ is an unsigned integer whose bit pattern is as
follows:
a 1100110011001111
a>>3 0001100110011001
a>>5 0000011001100110
The right shift operators can also be used for division purpose. It means, x>>n
gives the result as x
n
Example : 15>>1 gives 2 7, 15>>2 gives 3, 15>>3 gives 1
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 34
8. Special Operators: The following are the special operators used in Java.
1) Instanceof Operator
2) Dot Operator
3) Cast Operator
4) new Operator
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 35
Arithmetic Expression:
When an expression uses arithmetic operators then it is called arithmetic or
numeric expression. An arithmetic or numeric expression always represents
numeric value.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 36
OPERATOR PRECEDENCE:
Example: x=3*2/2+3/2+2–2+3*2
=6/2+3/2+2–2+3*2
=3+3/2+2–2+3*2
=3+1+2–2+3*2
=4+2–2+6
=6–2+6
=4+6
= 10
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 37
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 38
UNIT-II
The control structures are used to control the flow of program execution. In C
language there are there are three types of flow statements are exist.
Control statements
if for continue
if- else-if
do-while
switch
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 39
System.out.println("Hello !");
System.out.println("Welcome to JAVA world");
}
System.out.println("This is Mahesh!"); }
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 40
Working: if the Condition is true then the statement – block 1 will be executed.
Otherwise the statement – block2 will be executed.
class Exifelse
{
public static void main(String[] args)
{
System.out.println("Hello World!");
if(2>3)
{
System.out.println("Welcome !");
System.out.println("Hello!");
}
else
{
System.out.println("Mahesh!");
System.out.println("MCA!");
}
}
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 41
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 42
class SwitchDemo{
public static void main(String[] args){
char grade = 'B';
switch ( grade )
{
case 'A':
System.out.println( " Excellent ! " );
break ;
case 'B':
System.out.println( " Outstanding ! " );
break ;
case 'C':
System.out.println( " Good ! " );
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 43
break ;
case 'D':
System.out.println( " Can do better " );
break ;
case 'E':
System.out.println( " Just passed " );
break ;
case 'F':
System.out.println( " You failed " );
break ;
default :
System.out.println( " Invalid grade " );
}
} }
2. Iteration Statements: Set of instructions give to the compilers to execute set of statements
until condition became false that is loop.
The way of repetitions are forms the circle, that‟s why iteration statements are called loops. i.e.
loops means forming a circle. The basic purpose loop is code repetition.
In implementation whenever the repetition are occurred when instance of writing statement go
for loops.
In JAVA programming language loops are classified into three types.
1. While
2. For
3. Do-while
While loop: This loop repeatedly executes a group of statements as long as condition is true. When we
are working with while loop always pre-checking process will occur and it repeats in clock direction.
Syntax to while
While(condition)
{
Statement 1;
Statement 2;
………….
………….
Statement n;
inc /dec;
}
Working: The „while‟ statement executes all the statements in the statement-block as
long as the condition returns true (non-zero) value. When the condition returns false (0)
then the loop is terminated and the control is transferred to the statement after the
statement-block.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 44
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 45
}
The Enhanced for loop:
The enhanced for loop is also called for each loop, is an extended language
feature introduced with J2SE 5.0. This feature is used to retrieve the array elements
efficiently rather than using array indexes.
Syntax:
for( type identifier : Array Name )
{
statement-block;
}
In the above example “type” represents the data type, identifier represents the name of
the variable, Array Name indicates an Array.
Do-while:
In implementation if at least need to be executed the statement block once. Then go for do-while. When
we are working with do-while always post checking process will occur I.e. after execution of the
statement block only condition will be evaluated.
Syntax to do-while
do
{
Statement 1;
Statement 2;
Statement 3;
Inc/dec;
}
While (condition);
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 46
break statements:
„break‟ is a keyword by using break we can terminate loop body of switch body.
Using break is always optional. But it should be exist within the loop body or switch
body only.
In implementation where we know maximum number of repetitions but certain
condition is there we need to stop the repetition process, and then go for break. A
break is usually associated with an „if‟.
Syntax: break;
Write a JAVA Program to demonstrate break
class BreakExample1
{
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
if(i==6)
break;
System.out.println("Mahesh");
i=i+1;
}
}
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 47
Return statement:
Return statement in used to explicitly return from a method.
Return causes program control to transfer back to the caller of the method.
The return statement immediately terminates the method in which it is
executed.
Return statement does not terminate any method only main method will
terminate.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 48
Syntax:
return;
Ex: return x value;
return -1;
return (x+y-10);
return arr;
return obj;
Write a java program to demonstrate the effect of return statement.
class Return1
{
public static void main(String args[])
{
int num=1;
System.out.println("Before the return.");
if(num==1) return; // return to caller
System.out.println("After return.");
}
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 49
Class:
A class is a group of objects that share common properties and relationships.
A class is user-defined data type which holds both data and member functions
Class is structure representing the data and its related and corresponding functions.
For example Mango, Apple and Orange are objects of the class “Fruit”.
Fruit Mango;
Class declaration
In java, the data items are called fields and functions are called methods.
Once a class is defined, we can create any number of objects belonging to that
class. In java these “variable” are called as instances of classes. Classes are
defined using the keyword “class”.
Syntax :
class <classname >
{
[fields declaration ; ]
[methods declaration ;]
}
Fields Declaration :
The variables which are declared inside a class are called fields. These variables
are also called instance variables because they are created whenever an object of
the class is instantiated.
Ex: class Rectangle
{
int length;
int width;
}
The class Rectangle contains two integer type instance variables. No memory
space is reserved for these instance variables.
Methods Declaration
Methods are declared inside the body of the class immediately after the
declaration of instance variables. The general form is
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 50
length=x;
width=y;
}
int area()
{
int a=length*width;
return(a);
}
}
Object:
Instance of a class is called an object. Objects are the basic run-time entities in an
object Oriented system which can represent a person, a place, a bank account (or)
a table of data etc which have state and behavior. Identifying the state and
behavior for real-world objects is a great way to begin thinking in terms of object-
oriented programming.
Creating Objects
Creating an object is also referred as instantiating an object. Objects in java are
created using the new operator.
Rectangle r1;
r1=new Rectangle();
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 51
objectname.variable=value;
object.methodname(parameter-list);
Here, objectname is the name of the object and variable is the name of the member
variables, methodname is the name of the method that we call, and parameter-list
is separated by commas of actual values that must match in the type and number
with parameter list of method declared in the class.
r1.length=4;
r1.width=6;
Another way of assigning values to the instance variables by using methods
declared inside the class.
r1.getdata(4,6);
Eg: class Rectarea
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.length=4;
r1.width=6;
r2.getdata(10,5);
int area1=r1.length*r1.width;
int area2=r2.area();
System.out.println(“Rectangle R1 area=”+area1);
System.out.println(“Rectangle R2 area=”+area2);
}
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 52
int area=r1.area();
System.out.println(“area=”+area);
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 53
In java, it is possible to create methods that have same name, but different
parameters list. This is called method overloading.
Method overloading is used when objects are required to perform similar tasks
but using different input parameters. When we call a method in an object, it
matches the method name first and then the number and type of parameters is
to decide which definition to execute. This process is known as polymorphism.
Eg: class Room
{
float l,b;
Room(float x, float y) //Constructor1
{
l=x;
b=y;
}
Room(float x) //Constructor2
{
l=b=x;
}
float area()
{
return(l*b);
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 54
int largest()
{
if(a>b)
return a;
else
return b;
}
void display()
{
int large=largest();
System.out.println(“Big=”+large);
}
}
class Biggest
{
public static void main(String args[])
{
Big t= new Big(5,7);
t.display();
}
}
In the above example class big defines one constructor and two methods, namely
largest() and display(). The method display() calls the method largest() to
determine the largest number and display the result.
Defining a Subclass
variables declaration;
members declaration;
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 55
UNIT-III
Inheritance: The mechanism of deriving a new class from an old one is called
inheritance. In which new class is called subclass or derived class and old class is
called super class or base class.
Advantages of INHERITANCE: Benefits of Inheritance:
Types of inheritance:
1) Single Inheritance
2) Multiple Inheritance
3) Multi-level Inheritance
4) Hierarchical Inheritance
5) Hybrid Inheritance/ Multipath Inheritance
Single inheritance: A class is derived from only one super class and that super
class contains only one subclass then it is known as single inheritance.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 56
Multiple inheritances: A class is derived from two or more super classes then it
is known as multiple inheritances.
Hierarchical inheritance: A super class contains two or more sub classes then it
is known as hierarchical inheritance.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 57
It is possible to inherit all the members of a super class to its subclass by using
the keyword extends. However, it may be necessary to restrict the access to
certain variables and methods from outside the class.
In java we achieve this by applying visible modifiers to the member variables and
methods. The visibility modifiers are also called as access modifiers such as
public, private and protected.
Public: If we declare variables and methods as public, then these variables and
methods are accessible to all the classes outside this class.
Private: The members which are declared in private section can be accessed only
from within the class. By default all members are private.
Public: The members which are declared in public section can be accessed from
both inside and outside of the class.
Protected: The protected members are also same as private members. But
protected members can be also directly accessed in the subclass.
Friendly Access
When no access modifier is specified, then the members and methods defaults friendly.
Private Protected:
A member can be declared with two keywords private and protected. It is
accessible only the subclasses in same package and other package. But not
accessible other classes in same package and other packages.
Subclass in same
Yes Yes Yes No Yes
package
Subclass in other
Yes No Yes No Yes
package
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 58
Introduction to Arrays
Definition: An array is a collection of memory locations which can share same data
name and same data type values.”
Syntax:
Data type array name [size];
Properties:
An array is a collection of similar data type values in a single variable.
In implementation when we require „n‟ number of similar data type values then go
for array.
The array variables are created at the time of compilation.
When we are working with arrays all elements will allocated in continuous memory
location only.
When we are working with arrays we can access the elements randomly. Because
continuous memory locations are created.
When we are working with arrays all elements will share same name with unique
identification value called index. Which starts from zero and ends with „size-1‟?
When we are working with arrays we need to use array subscript operator i.e. [ ]
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 59
int[] a;
Array initialization:
After array creation we can put values into the array, this process is known
as initialization.
We can initialize the elements of the array in the same way as the ordinary
variables when they are declared. The general form of initialization of array
is:
<Data type> array name [size] = {value1, value2, …., values};
Where the value1 refers to the first array element, value2 refers to the value
of the second array element. …so on.
Examples of initializing arrays:
int num[5]={10,20,30,40,50};
float cost [4]={0.45, 1.25, 3.75,0.35};
arr[0] arr[1] arr[2] arr[3] arr[4] arr[5]
22 56 89 10 99 43
Syn: arrayname[index]=value;
Eg: a[0]=10;
a[1]=12;
a[2]=14;
a[3]=16;
a[4]=18;
Creating memory locations: After the declaration, we need to create the memory
for arrays. Java allows creating arrays using new operator.
Syn: arrayname=new datatype[size];
We can also initialize arrays automatically in the same way as the ordinary
variables when they are declared.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 60
In the above example the list of values are separated by commas and enclosed
within the braces.
class ArrEx1
{
public static void main(String args[] )
{
int arr[]={10,20,30,40,50};
System.out.println("start array"+arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
System.out.println(arr[4]);
}
}
Two dimensional arrays?
Two Dimensional Arrays
Collection of single dimensional array in a single variable is called two dimensional array
or array (array).
In 2D array elements are arranged in rows and columns.
When we are working with 2D array we need to use two subscript operators which
indicate row size and column size.
The main memory of 2D array is row and sub memory is columns.
In „2D array‟ array name always gives base address of the array i.e. first row base
address, arr+1 is next main memory of the array. i.e. second row base address.
0 1 2
(or)
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 61
This creates a table with 2 rows and 3 columns. i.e. it stores 6 integers.
Array length
int size=a.length;
Prog1:
import java.util.Scanner;
class A4{
System.out.println("Student" + (i+1));
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 62
STRINGS
A string is the sequence of characters enclosed within double quotes. Strings are
very useful because most of the data on internet will be in the form of strings
only.
For example: name, vehicle number, address, credit card number etc. will come
under strings.
In order to deal with strings we have two classes. They are java.lang.String and
java.lang.StringBuffer.
A java string is not a NULL terminated.
We can declare a String variable and directly store a String literal using
assignment operator.
We can create String object using new operator with some data.
String stringname;
stringname=new String(“string”);
college=new String(“gminformatics”);
Like arrays, it is also possible to get the length of the string using the length
method of the class String.
int m=college.length();
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 63
String methods
s2=s1.replace(„x‟,‟y‟)
Replace all appearance of x with y.
s1.equals(s2)
Return true, if s1 is equal s2.
s1.equalsIgnoreCase(s2)
Returns true, if s1=s2, ignoring the
case of characters.
STRINGBUFFER CLASS
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 64
VECTORS
The vector class can be used to create a generic dynamic array known as vector.
It can be hold the elements of different type.
The vector class is contained in java.util package.
Vectors are created like arrays as follows:
Vector a=new Vector(); //declaring without size.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 65
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 66
Variables declaration;
Methods declaration;
In the above syntax, interface is the keyword and interfacename is any valid java
identifier.
Extending interfaces
Like classes, interfaces can also be extended. That is the new sub interface
will inherit all the properties of super interface. This is can be achieved by using
the keyword extends.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 67
…………………
…………………
The interface itemcost will inherit both the variables CODE and NAME into it. We
can also extends several interfaces together into a single interface.
interface item
………….
………….
interface discount
………….
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 68
………….
………….
………….
Implementing interface
Syn:
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 69
Eg: interface A
int m=10;
int n=20;
class B implements A
int x=m;
……………..
…………….
if(size<n)
…………….
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 70
UNIT –IV
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 71
During the lifetime of a thread there are many states. They include.
1) Newborn state.
2) Runnable state.
3) Running state.
4) Blocked state.
5) Dead state.
A thread is always is one of the 5 states. It can move from one state to another
in the following way.
New Born
start() stop()
Newborn state:
Running Dead
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 72
Running state:
The thread is executing by the processor.
A B C
. . .
Runnable
Running
Runnable state :
The runnable state means that the thread is ready for execution and is
waiting for the processor. That is the thread has joined in the queue.
A B C
. . .
Runnable
Running
Blocked state :
A thread is said to be blocked from the running state and runnable state.
This happens when the thread is suspended, sleeping or waiting. A blocked thread
is considered as “not runnable”, but not dead so it is run once again.
A B C
. . .
Runnable
Running resume()
notify()
Dead state:
Every thread ends its life when it has completed executing its run() method.
It is a natural dead. However, we can kill a thread by a stop() method at any state,
so it is a premature dead.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 73
Types of Errors:
Errors may be classified into two types. They are
Compile-time errors
Run-time errors
Compile-time Errors:
All syntax errors will be detected and displayed by the java compiler and
therefore these errors is known as compile-time errors. Whenever the compiler
displays an error, it will not create the .class file. Therefore it is necessary to fix
the errors for to successfully compile and run the program.
class Error1
{
public static void main(String args[])
{
System.out.println(“Welcome to Java”) //Missing
}
}
The compiler displays the following message on the screen.
Error 1.java:5: ; expected
System.out.println(“Welcome to Java”)
1 error
Sometimes, a single error may be the source of multiple errors in the
compile-time. For example, an undeclared variable in a number of places will
cause a series of errors of type “undefined variable”. The most common errors are
Missing semicolon
Missing double quotes in strings.
Use of undeclared variable.
Misspelling of identifiers and keywords.
Missing brackets and methods.
Incompatible types in assignments.
Use of „=‟ in the place of „==‟ operator.
Run-time Errors:
Sometimes, a program may compile successfully creating the .class file but
may not run properly. Such programs may produce wrong results due to wrong
logic or may terminate. The most common Run-time errors are
Dividing an integer by 0(zero).
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 74
When such errors are encountered, java generates an error message and aborts
the program.
class Error2
{
public static void main(String args[])
{
int a,b,c;
a=10;
b=5;
c=5;
int x=a/(b-c);
System.out.println(“x=”+x);
int y=a/(b+c);
System.out.println(“y=”+y);
}
}
While executing, it displays following message and terminate the program without
executing remaining statements.
java.lang.ArithmeticException : / by zero
at Error2.main
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 75
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 76
UNIT – V
What is an applet? What do you mean by remote and local applets?
Applets are small java programs that are basically used in internet
programming. They can be transported over the internet from one computer to
another and run using appletviewer” (or)any web browsers that supports java .An
applet can perform the following tasks.
Arithmetic operations, play sounds, display graphics, create animation, and
accept user input and interactive games.
We can embed applets into web pages in two ways. They are
1. Local applets
2. Remote applets
Local applets:-
An applet developed locally and stored in a local system is known as a “local
applet”. We can write our own applets and embedded them into the web pages,
local applet does not need to use the internet. It simply searches the directories in
the local system and locates and loads the specified applet.
The following shows the loading of local applet.
(Local applet)
(L (Local computer)
Remote applet: - A remote applet is that which is developed by someone else and
stored on a remote computer connected to the internet. If our system is connected
to the internet we can download the Remote applet on to our system via at the
internet and run it. The following diagram shows the loading a remote applet.
local applet
Internet Internet
Remove applet
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 77
In order to locate and load a remove applet ,we must know the applet address on
the web. This address is known as “Uniform Resource Locater”(URL) and must be
specified in the applets HTML documents as the value of the CODE BASE
ATTRIBUTE
CODE BASE = http://www.netserve.com/applets
How Applets Differ From Applications:-
Both the applets and standard alone applications are java
programs there are significant differences between them they are:-
1. Applet do not use the main() method for start the execution of the code. Applets
when loaded automatically call certain methods of “Applet” Class to start and
execute the applet code.
2. Applets are executed from inside a webpage using a special feature known as
HTML Tag.
3. Applet cannot read from or write to the files in the local computer.
4. Applets cannot run any program from the local computer.
5. Applets are restricted from using libraries from other languages such as C or
C++.
6. Applets can‟t communicate with other servers on the network.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 78
-----------
public void paint (Graphics g)
{
----------- //Applets Operation Code.
-----------
}
-----------
- - - - - - - - - - -}
Ex: Program:-
import java.awt.*;
import java.applet.*;
public void HelloJava extends Applet
{
public void paint (Graphics g)
{
g.drawString (“Hello Java”,10,100);
}
}
start ()
stop ()
paint() start ()
destroy()
Dead
The applet states includes:
Born on initialization state
Running
Idle state
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 79
}
Display state:-
Applet moves to the display state whenever it has to perform some
output operations on the screen. This happens immediately after the applet enters
into the running state. The paint() method is called to perform these task. Almost
every applet will have a paint() method. We must override this method if we went
anything to be displayed on the screen.
public void paint (Graphics g)
{
---------
--------- (display statements)
}
Java
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 81
For example, if we want to refer the class String in the lang package, then
we use the statement.
The second approach is imports all the classes contained in the specified
package. We may use the statement
Syn: import java.packagename.*;
Naming conventions
Packages can be named using the standard java naming rules. Packages begin
with lower case letters. This makes easy to make difference between packages
and classes. All class names begin with an uppercase letters.
Eg: import java.lang.String;
Package Class
name name
Every package name must be different. Duplicate names will cause runtime
errors.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 82
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory.
4. Save the file as the „classname. java‟.
5. Compile the file. This creates .class file in the subdirectory.
package aaa;
{ ………….
………….
………….
………….
In the above example, the package name is „aaa‟ and the class name is
„Pack‟. We can compile this file as „javac –d . Pack.java‟
Using package
Consider the following package named „aaa‟ containing a single class „Pack‟.
return(x+y);
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 83
This file should be save as Pack.java. After compiled this program the file
Pack.class will be stored in the subdirectory „aaa‟. Consider the following program
that imports the class „Pack‟ from the package „aaa‟.
class testpack
int sum=a.add(10,20);
System.out.println(“Sum=”+sum);
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 84
Stream
A stream is a sequence of data. In Java a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached
with console.
System.out: standard output stream
System.in: standard input stream
System.err: standard error stream
Byte Stream: byte streams are used to handle input and otput of binary data
and hence they are also known as binary streams. java.io.InputStream
java.io.OutputStream are the top level classes that represent binary or byte
streams.
Input Stream
The InputStream class is used for reading the data such as a byte and array of
bytes from an input source. An input source can be a file, a string, or memory
that may contain the data. An input stream is automatically opened when you
create it. You can explicitly close a stream with the close( ) method.
OutputStream
Java application uses an output stream to write data to a destination, it may be a
file, an array, peripheral device or socket.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 85
If you have to write primitive values into a file, use FileOutputStream class. You
can write byte-oriented as well as character-oriented data through
FileOutputStream class. But, for character-oriented data, it is preferred to
use FileWriterthan FileOutputStream.
Method Description
protected void finalize() It is used to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to
the file output stream.
void write(byte[] ary, int It is used to write len bytes from the byte array starting at
off, int len) offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 86
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 87
Method Description
int available() It is used to return the estimated number of bytes that can be read
from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.
int read(byte[] b, int It is used to read up to len bytes of data from the input stream.
off, int len)
long skip(long x) It is used to skip over and discards x bytes of data from the input
stream.
protected void finalize() It is used to ensure that the close method is call when there is no
more reference to the file input stream.
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 88
3. A Stream can carry data from keyboard to memory or from memory to printer.
4. Basically there are two types of streams. They are input streams and output streams.
5. Input streams are used to receive or read data coming from some other place. Output
streams are used to send or write data to some other place.
6. All streams are represented by classes in java.io (input and output) package. This
package contains a lot of classes. These classes are classified into input streams and output
streams.
7. Keyboard is represented by a field, called in the System class. System class is found in
java.lang package and has three fields. They are
System.in : This is InputStream object. It represents standard input device i.e., Keyboard.
System.out : This is PrintStream object. It represents standard output device i.e., Monitor.
System.err : This field also is PrintStream object, which by default represents monitor.
Example : System.out.println(“Welcome”);
System.err.println(“Welcome”);
In java stream classes are classified into two categories. They are
1. Byte stream classes: Byte stream classes are defined from two abstract classes:
InputStream and OutputStream. Each of these abstract classes has several concrete
subclasses that handle various input and output operations.
a. BufferedInputStream
b. BufferedOutputStream
c. DataInputStream
d. DataOutputStream
e. FileInputStream
f. FileOutputStream
g. ByteArrayInputStream
h. ByteArrayOutputStream
2. Character Stream classes: Character stream classes are defined from two abstract
classes: Reader and Writer. Each of these abstract classes has several concrete
subclasses that handle various input and output operations.
a. BufferedReader
b. BufferedWriter
c. CharArrayReader
d. CharArrayWriter
e. FileReader
f. FileWriter
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 89
g. FilterReader
h. FilterWriter
i. InputStreamReader
j. OutputStreamWriter
k. LineNumberReader
To read the data from the key board, follow the following steps
1) Create InputStreamReader object and connect the keyboard(System.in) to it.
InputStreamReader obj=new InputStreamReader(System.in);
2) Create BufferedReader object and connect the InputStreamReader to it.
BufferedReader br=new BufferedReader(obj);
3) These two steps can be combined and written in a single statement as
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
4) Now we can read the data coming from the keyboard using read( ) and readLine( )
methods available in BufferdReader class.
Ex : String str = br.readLine( );
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 90
2. The InputStreamReader class serves as a bridge between byte streams and character
streams.
3. It reads bytes from the input stream and translates them into characters according to a
specified character encoding.
4. It reads bytes and decodes them into characters using a specified charset.
5. Calling of read() method it gets some bytes of information from input stream.
Syntax :
String str=br.read( );
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA
B.Sc. III Semester 91
Methods :
ready( ) : This method tells us whether this stream is ready to be read or not.
getEncoding( ) : This method is used to know the name of the character encoding being used
by this stream.
Paper III: Object oriented programming using JAVA Prepared by Mahesh MCA