0% found this document useful (0 votes)
1K views

Java Notes 4th Semester (07-10-2022)

The document discusses object oriented programming and Java programming. It defines OOP and lists its key features. It also lists the top 20 most popular OOP languages according to the TIOBE index, with Java, C++, C#, Python and C being the top 5. The document is divided into 5 units covering topics like classes, inheritance, interfaces and exceptions in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Java Notes 4th Semester (07-10-2022)

The document discusses object oriented programming and Java programming. It defines OOP and lists its key features. It also lists the top 20 most popular OOP languages according to the TIOBE index, with Java, C++, C#, Python and C being the top 5. The document is divided into 5 units covering topics like classes, inheritance, interfaces and exceptions in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

Object Oriented Programming Using Java

UNIT -I
Object Oriented Programming: Introduction to OOP, Objects and Classes,
Characteristics of OOP, Difference between OOP and Procedure Oriented
Programming. Introduction to Java Programming: Introduction, Features
of Java, Comparing Java and other languages (C & C++), Java Development
Kit, Structure of Java Program, Prerequisites for Compiling and Running Java
Programs.
UNIT - II
Java Language Fundamentals: Data types, variable declarations,
Operators and Assignment, Control structures, Arrays, Strings, The String
Buffer Class. Java as an OOP Language: Defining classes, Constructors,
Overloading, Modifiers, Packages.
UNIT - III
Inheritance, Interfaces, Exception Handling: Inheritance, Types of
Inheritance, Interfaces, Interface Implementation, Exception Handling in
Java, Throwing User-defined Exceptions, Advantages of Exception.
Multithreading: An Overview of Threads, Creating Threads, Thread Life–
cycle, Thread Priorities, Thread Synchronization, Daemon Threads,
Communication of Threads.
UNIT - IV
Files and I/O Streams: An Overview of I/O streams, Java I/O, File
Streams, File InputStream and File Output Stream, Filter streams, Random
Access File, Serialization. Applets: Introduction, Java applications versus
Java Applets, Applet Life-cycle, Working with Applets, The HTML Applet Tag.
UNIT - V
Database Handling Using JDBC: An Overview of DBMS, JDBC Architecture,
Working with JDBC. Servlets: Introduction, How to run servlets, The Life–
cycle of the servlet, servlet API, Multitier Applications using JDBC from a
servlet.

1
Prescribed books:1. Object Oriented Programming through Java,
Universities Press (2008),by P. Radha Krishna.

List of Lab Experiments


1. Write a Java program that prints all roots of quadratic equation ax2 +bx +
c = 0.
2. Write a Java program that prompts the user for an integer and then prints
out all prime numbers up to that integer.
3. Write a Java program to create a Student class with following fields
i. Hall ticket number
ii. Student Name
iii. Department
Create ‘n’ number of Student objects where ‘n’ value is passed as input to
constructor
4. Write Java program to implement Hierarchical Inheritance
5. Write Java program to implement multiple inheritance through interface
6. Write a Java program to demonstrate String comparison using == and
equals method.
7. Write a Java program that creates three threads.
First thread displays “Good Morning” everyone second, the second thread
displays “Hello” every two seconds and the third thread displays “Welcome”
every three seconds
8. Write a Java program to demonstrate Exception Handling
9. Write a Java program that displays the number of characters, lines and
words in a text file
10. Write a Java Program to create Applet for timer
11. Write a Java program to connect to Database using JDBC
12. Write a Java program to demonstrate Servlet life cycle

2
UNIT -I
Object Oriented Programming: Introduction to OOP, Objects and Classes,
Characteristics of OOP, Difference between OOP and Procedure Oriented
Programming.
Introduction to Java Programming: Introduction, Features of Java,
Comparing Java and other languages (C & C++), Java Development Kit,
Structure of Java Program, Prerequisites for Compiling and Running Java
Programs.
----------------------------------------------------------------------------------
1Q) what is an “OBJECT ORIENTED PROGRAMMING” (OR) Object-
Oriented Paradigm?
In software programming, we have various types of programming languages.
Major languages amongst them are either procedural or object-oriented in
nature.
✓ In procedural programming languages, bigger problems are broken
down into small solvable problems. These small problems are converted into
procedures or functions. This way the procedural programming language
emphasizes functions rather than data. Thus procedural languages neglected
data completely and thus they do not ensure data security at all.
✓ Object-oriented programming is a way of designing and
programming software by manipulating objects and the objects are the main
part of the programming.
✓ Object-oriented programming (OOP) is a fundamental programming
paradigm based on the concept of “objects”. These objects can contain data
in the form of fields (often known as attributes or properties) and code in
the form of procedures (often known as methods).
✓ Object oriented programming is a new approach to overcome the
drawbacks of a procedural oriented approach. It divides programs into the
number of entities called objects that contain data
(variables/fields/attributes/properties) and methods (known functions/tasks
as in java).

3
✓ The core concept of the object-oriented approach is to break complex
problems into smaller objects.

✓ According to the TIOBE index, the top twenty OOP languages


are Java, C++, C#, Python, R, PHP, Visual Basic.NET, JavaScript, Ruby, Perl,
Object Pascal, Objective-C, Dart, Swift, Scala, Kotlin, Common Lisp, MATLAB,
and Smalltalk.

Features of Object-Oriented programming:


▪ OOP treats data as a critical element in the program development and
does not allow it to flow freely around the system.
▪ OOP allows us to decompose a problem into a
number of entities called objects and then build data
and functions (known as methods in Java) around
these entities. The combination of data and
functions(method) make up an object.
▪ Data is hidden and cannot be accessed by
external functions.
▪ Objects may communicate with each other through methods.
▪ New data and methods can be easily added whenever necessary.
▪ Follows bottom-up approach in program design.

There are various object-oriented programming languages are present. But


we have enlisted some popular and widely used OOP languages.

4
According to the TIOBE (“The Importance Of Being Earnest”) index, the top
20 OOP languages are Java, C++, C#, Python, R, PHP, Visual
Basic.NET, JavaScript, Ruby, Perl, Object Pascal, Objective-
C, Dart, Swift, Scala, Kotlin, Common Lisp, MATLAB, and Smalltalk.

Nov Nov Change Programming Ratings Change


2022 2021 Language
1 1 Python 17.18% +5.41%

2 2 C 15.08% +4.35%

3 3 Java 11.98% +1.26%

4 4 C++ 10.75% +2.46%

5 5 C# 4.25% -1.81%

6 6 Visual Basic 4.11% -1.61%

7 7 JavaScript 2.74% +0.08%

8 8 Assembly language 2.18% -0.34%

9 9 SQL 1.82% -0.30%

10 10 PHP 1.69% -0.12%

11 18 Go 1.15% -0.06%

12 15 R 1.14% -0.14%

13 11 Classic Visual Basic 1.10% -0.46%

14 17 Delphi/Object Pascal 1.08% -0.14%

15 20 MATLAB 1.02% -0.15%

16 28 Objective-C 0.93% +0.39%

17 24 Scratch 0.88% +0.11%

18 14 Swift 0.87% -0.56%

19 13 Ruby 0.85% -0.59%

20 29 Rust 0.75% +0.21%

Other programming languages:

Position Programming Language Ratings


5
21 SAS 0.69%
22 Lua 0.61%
23 Perl 0.57%
24 Fortran 0.57%
25 COBOL 0.54%
26 (Visual) FoxPro 0.49%
27 Ada 0.48%
28 Kotlin 0.47%
29 Prolog 0.44%
30 Lisp 0.38%
31 PowerShell 0.37%
32 Julia 0.36%
33 PL/SQL 0.34%
34 Scala 0.34%
35 Dart 0.34%
36 D 0.30%
37 Logo 0.26%
38 X++ 0.25%
39 ABAP 0.25%
40 TypeScript 0.24%
41 Bash 0.23%
42 Scheme 0.23%
43 VBScript 0.21%
44 LabVIEW 0.19%
45 F# 0.19%
46 Awk 0.19%
47 PL/I 0.19%
48 Transact-SQL 0.18%
49 ML 0.18%
50 Haskell 0.17%

6
The Next 50 Programming Languages
The following list of languages denotes #51 to #100. Since the differences
are relatively small, the programming languages are only listed (in
alphabetical order).
❖ ABC, ActionScript, Alice, Apex, AutoHotkey, B4X, bc, Bourne shell, C
shell, CFML, CL (OS/400), Clipper, CLIPS, Clojure, Common Lisp, Crystal,
Curl, Eiffel, Elixir, Erlang, Forth, Groovy, Icon, Inform, Io, J#, Ladder Logic,
Modula-2, MQL5, MUMPS, NATURAL, NXT-G, OCaml, Occam, OpenCL,
OpenEdge ABL, PostScript, Q, Racket, REXX, Ring, RPG, S, Solidity, SPARK,
Stata, Tcl, Vala/Genie, Verilog, VHDL
Very Long Term History:
To see the bigger picture, please find below the positions of the top 10
programming languages of many years back. Please note that these
are average positions for a period of 12 months.
Programming 2022 2017 2012 2007 2002 1997 1992 1987
Language
Python 1 5 8 7 12 28 18 -
C 2 2 1 2 2 1 1 1
Java 3 1 2 1 1 16 - -
C++ 4 3 3 3 3 2 2 6
C# 5 4 5 8 13 - - -
Visual Basic 6 15 - - - - - -
JavaScript 7 7 10 9 8 21 - -
Assembly 8 11 - - - - - -
language
SQL 9 - - - 7 - - -
PHP 10 8 6 5 6 - - -
Prolog 27 32 32 27 16 20 13 3
Lisp 31 31 13 16 14 9 4 2
Pascal 264 121 14 20 99 11 3 5
(Visual) Basic - - 7 4 4 3 5 4

7
2Q) Explain “Basic concepts” OR “components” OR “characteristics”
of Object Oriented Programming:

1. Class:

“A Class is a way of binding the data and associated methods in a single


unit”. Any JAVA program if we want to develop then that should be developed
with respective to Class only i.e., without Class there is no JAVA program.
The entire set of data and code of an object can be made a user defined data
type using the concept of a class. In fact Objects are treated as variables of
the type Class. Once a Class has been defined, we can create any number of
objects belonging to that Class.
2. Object:
Objects are the basic runtime entities in an object oriented system. Program
object should be chosen, such that they match closely with the real world
objects. When a program is executed, the objects interact by sending
messages to one another.
Example: customer and account are two objects in a bank program, then
the customer object may send a message to the account object requesting
for the balance. Each object contains data and code(method) to manipulate
the data.

8
3. Data Encapsulation:
The wrapping (packing) up data and functions into a single unit is known as
Encapsulation. In Java, encapsulation can be achieved by declaring the
class attributes/variables as private. In certain cases, we need to access or
modify the private variables, we can use the public get and set methods.
The data is not accessible to the outside class and only those functions which
are wrapped in the class can access it. This insulation (protection) of the data
from direct access by the program is called Data Hiding.

4. Data Abstraction:
One of the most fundamental concept of OOPs is Abstraction. Abstraction is
a process where you show only “relevant” data and “hide” unnecessary
details of an object from the user.

9
For example: when you login to your bank account online, you enter your
user_id and password and press login, what happens when you press login,
how the input data sent to server, how it gets verified is all abstracted away
from the you.

5. Inheritance:
Inheritance is the process of acquiring (getting) the properties of one class to
another class. In OOP, the concept of inheritance provides the idea of
reusability. This means that we can add an additional feature to an existing
class with out modifying it .This is possible by deriving a new class from the
existing class. The new class will have combined features of both the classes.
The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).

6. Polymorphism:
The process of representing one form in multiple forms is known
as Polymorphism. Polymorphism is derived from 2 greek
words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms. The behavior depends
upon the types of data used in the operation.
Example: consider the operator ”+”. If the operands are numbers, then
operation will generate a sum. If the operands are strings, then the operation
would produce a third string by concatenation. The process of making an
operator to exhibit different behaviors in different instances is known as
Operator over Loading.

7. Dynamic Binding (Late binding):


Binding refers to the linking of a procedure call (function name) to the code
(body of the function) to be executed in response to the call. Dynamic
binding means that the code associated with a given procedure call is not
known until the time of execution.
10
8. Message passing:
An object oriented program consists of a set of objects that communicate
with each other. The process of programming in an object oriented language
is
1. Create classes that defined objects and their behaviors (methods).
2. Creating objects from class definitions.
3. Establishing communication among objects.
A message for an object is a request for execution of a procedure. Message
passing involves specifying the name of the object, the name of the function
and the information to be sent.
Example: employee. salary (name)
Object message information
9. Generic programming: This feature allows declaration of variables
without specifying exact data types. Object-oriented programs can create a
function that can be used for any type of data. The template feature in C++
allows generic programming.

3Q) What are the Benefits of OOP?


Object oriented programming provides several benefits to both the
programmer and the user. Benefits of OOP include:

➢ Modularity. Encapsulation enables objects to be self-contained,


making troubleshooting and collaborative development easier.

➢ Reusability. Code can be reused through inheritance, meaning a team


does not have to write the same code multiple times.

➢ Productivity. Programmers can construct new programs quicker


through the use of multiple libraries and reusable code.

➢ Easily upgradable and scalable. Programmers can implement


system functionalities independently.

➢ Interface descriptions. Descriptions of external systems are simple,


due to message passing techniques that are used for objects communication.
11
➢ Security. Using encapsulation and abstraction, complex code is hidden,
software maintenance is easier and internet protocols are protected.

➢ Flexibility. Polymorphism enables a single function to adapt to the


class it is placed in. Different objects can also pass through the same
interface.

4Q) what are the Applications of OOP:


The most popular application of object-oriented programming, up to now, has
been in the area of user interface design such as windows. There are
hundreds of windows systems developed using OOP techniques.
▪ Real-time systems.
▪ Simulation and modeling.
▪ Object-oriented databases.
▪ Hypertext and hypermedia.
▪ AI (Artificial Intelligence) and expert systems.
▪ Neural networks and parallel programming.
▪ Decision support and office automation systems.
▪ CAM (Computer Aided Manufacturing)/ CAD (Computer Aided Design)

5Q) What are the Difference between OOP and Procedure Oriented
Programming
ProceduralProgramming:
Procedural Programming can be defined as a programming model which is
derived from structured programming, based upon the concept of calling
procedure. Procedures, also known as routines, subroutines or functions,
simply consist of a series of computational steps to be carried out. During a
program’s execution, any given procedure might be called at any point,
including by other procedures or itself.
ObjectOrientedProgramming:
Object oriented programming can be defined as a programming model which
is based upon the concept of objects. Objects contain data in the form of
12
attributes and code in the form of methods. In object oriented programming,
computer programs are designed using the concept of objects that interact
with real world.
Languages used in Procedural Programming:

Procedural Oriented Object Oriented Programming


Programming
In procedural programming, program In object oriented programming,
is divided into small parts program is divided into small parts
called functions. called objects.
Procedural programming follows top Object oriented programming
down approach. follows bottom up approach.
There is no access specifier in Object oriented programming have
procedural programming. access specifiers like private, public,
protected etc.
Adding new data and function is not Adding new data and function is
easy. easy.
Procedural programming does not Object oriented programming
have any proper way for hiding data provides data hiding so it is more
so it is less secure. secure.
In procedural programming, Overloading is possible in object
overloading is not possible. oriented programming.
In procedural programming, function data is more important than
is more important than data. function.
Procedural programming is based Object oriented programming is
on unreal world. based on real world.
Examples: FORTRAN, ALGOL, Examples: Java, C++, C#, Python,
COBOL, BASIC, Pascal and C etc PHP, JavaScript, Ruby, Perl,
Objective-C, Dart, Swift, Scala.

6Q) What is History of Java. (or) introduction of JAVA


✓ Java is a high-level, general-purpose, class based, object-oriented, and
secure programming language developed by “James Gosling” (father of
13
java program) together with Mike Sheridan and Patrick Naughton at
Sun Microsystems, Inc. in 1991. It is formally known as OAK. In 1995, Sun
Microsystem changed the name to Java. In 2009, Sun Microsystem takeover
by Oracle Corporation.

✓ Java is a software platform programming language and that runs on


billions of devices, including notebook computers, mobile devices, gaming
consoles, medical devices TVs, VCRs and other electronic machines. Java
programs are also found in desktops, servers, smart cards and Blu-ray Discs
(BD) .

✓ One major advantage of developing software with Java is its


portability. Once you have written code for a Java program on a notebook
computer, it is very easy to move the code to a mobile device.

✓ When the language was invented in 1991 by James Gosling of Sun


Microsystems (later acquired by Oracle), the primary goal was to be able to
"write once, run anywhere."

✓ When a programmer writes a Java application, the compiled code


(known as bytecode) runs on most operating systems (OS), including
Windows, Linux and Mac OS.

Editions of Java:
Each edition of Java has different capabilities. There are three editions of
Java:
o Java Standard Editions (JSE): It is used to create programs for a
desktop computer.
o Java Enterprise Edition (JEE): It is used to create large programs
that run on the server and manages heavy traffic and complex transactions.
o Java Micro Edition (JME): It is used to develop applications for small
devices such as set-top boxes, phone, and appliances.

6Q) Explain about Java features (Or) Buzzwords of JAVA.


1. Compiled and interpreted:
Usually a computer language is either compiled or interpreted. Java combines
both these approaches in a two stages.

14
✓ Compiled: Java enables the creation of cross-platform programs by
compiling into an intermediate representation called Java Bytecode.
✓ Interpreted: Bytecode is then interpreted, which generates machine
code that can be directly executed by the machine that provides a Java
Virtual machine.
2. Platform-independent and portable:
The most significant contribution of java over other languages is its
portability. Java programs can be easily moved from one computer system to
another.
✓ Changes and upgrades in Operating systems, processors and system
resources will not force any changes in java programs. So java has become a
popular language for internet programming. Java ensures portability in two
ways. First, java compiler generates byte code instructions that can be
implemented on independent. Secondly, the sizes of the primitive data types
are not machine dependent.
3. Object-oriented:
Java is a true Object –Oriented Language. Almost “Everything is an Object”
paradigm. All program code and data reside within objects and classes. The
object model in Java is simple and easy to extend. Java comes with an
extensive set of classes, arranged in packages that can be used in our
programs through inheritance.
✓ Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.
✓ Basic concepts of OOPs are: Object, Class, Inheritance, Polymorphism,
Abstraction, Encapsulation etc….

4. Robust and secure:


The meaning of Robust is “strong”. This means that Java programs are strong
because they do not crash easily like C or C++ programs.

15
✓ Java is a strictly typed language. It checks code both at compile time
and runtime.
✓ It is designed as a garbage-collected language, reliving all memory
management problems.
✓ Java also incorporates the concepts of exception handling (error
handling), which captures series errors and eliminates any risk of crashing
the system.
✓ Security becomes an important issue for a language that is used for
programming on internet.
✓ When a Java Compatible Web browser is used, downloading can be
done safely without fear of viral infection or malicious intent.
✓ Java provides a “firewall” between a networked application and your
computer.
✓ Java achieves this protection by confining a Java program to the Java
execution environment and not allowing it to access other parts of the
computer.
5. Distributed:
Java is designed to support the distributed environment of the Internet
because it handles TCP/IP and UDP protocols(rules).
✓ Using Java, we can make a program to get information and can
distribute it on various computers on a network. Java also supports Remote
Method Invocation (RMI) feature that enable a program to distribute methods
across a network.
6. Simple, Small and Familiar:
Java programming language is very simple and easy to learn, understand,
and code. Most of the syntaxes in java follow basic programming language C
and object-oriented programming concepts are similar to C++.
✓ In a java programming language, many complicated features like
pointers, operator overloading, structures, unions, etc. have been removed.
✓ One of the most useful features is the garbage collector it makes java
more simple.
7. Multithreaded and interactive:
16
Java supports multithreaded programming. Multithreaded means handling
multiple parts of the same program simultaneously, we need not wait for the
application to finish one task before beginning another.
✓ For example, we can listen to an audio clip while scrolling a page and at
the same time download an applet from a distant computer.
8. High performance:
The speed of interpreter inside JVM to execute a program is slow. To
overcome this problem, JavaSoft team has introduced JIT (Just In Time)
compiler which improves the performance of interpreting byte code by
caching interpretations.
✓ Due to which the speed of execution of java program is enhanced.
✓ So, both interpreter and JIT compiler in JVM work together to run the
program.
9. Dynamic and extensible: Java is a dynamic language. Java is capable of
dynamically linking in new class libraries, methods and objects.
Java programs support functions written in other languages such as C and
C++. These functions are known as native methods. This facility enables the
programmers to use the efficient functions available in these languages.
Native methods are linked dynamically at runtime.
10. Easy of development: Java 2 Standard Edition (J2SE) 5.0 supports
features, such as generics, Enhanced for loop, auto boxing or un-boxing, type
safe, enum etc. so we can easily develop applications

17
2. OVERVIEW OF JAVA LANGUAGE
Java is a general-purpose, object-oriented programming language. We can
develop two types of java programs.

● Stand-alone applications. ● Web applets.


Stand-alone applications are programs written in java to carry out certain
tasks on stand-alone computer. HotJava itself is a Java application program.
Executing a stand-alone Java program involves two steps:
1. Compiling source code into byte code using javac compiler.
2. Executing the byte code program using java interpreter.
Applets are small java programs
developed for internet applications. An
applet located on a distant computer
(server) can be downloaded via Internet
and executed on a local computer
(client) using a browser. We can develop
applets for doing everything from simple
animated graphics to games and utilities.
Since applets are embedded in an HTML
(HyperText Markup Language) document and run inside a web page.
Stand-alone programs can read and write files and perform certain operations
that applets cannot do. An applet can only run within a web browser.

Simple Java Program:

class Sample
{
public static void main (String args[])
{
System.out.println(“Welcome to Java”);
}
}
18
● Class declaration: The first line class Sample declares a class,
which is an object-oriented construct. Java is a true object-oriented language
and therefore everything must be placed inside a class. class is a keyword
and declares that a new class definition follows. Sample is a java identifier
that specifies the name of the class to be defined.
● Opening Brace: Every class definition in Java begins with an
opening brace { and ends with a matching closing brace } appearing in the
last line.
● main(): The third line
public static void main (String args[])
defines a method named main (). Every java application program must
include the main () method. This is the starting point for the interpreter to
begin the execution of the program. A java application can have any number
of classes but only one of them must include a main method to initiate the
execution .The java applets will not use the main method.
All parameters to a method are declared inside a pair of parentheses. Here
String args[] declares a parameter named args, which contains an array of
objects of the class type String.
● executable statement in the program is
System.out.println(“Welcome to Java”);
Since Java is a true object oriented language, every method must be part of
an object. The println method is a member of the out object, which is static
data member of System class. The method println always appends a new line
character to the end of the string. This means that any subsequent output
will start on a new line. Every Java statement must end with a semicolon.
Structure of Java Program:
Documentation section Suggested
Package Statement
Import statement
Interface statement Optional
Class Definition
19
Main method class
{
Main method definition Essential
}
▪ Documentation section: The documentation section comprises a set
of comment lines giving the name of the program, the author and other
details, which the programmer would like to refer to at a later stage.
Example: /* Addition of two numbers */
▪ Package statement: The first statement allowed in a java file is a
package statement. This statement declares a package name and informs the
compiler that the classes defined here belong to this package. The package
statement is optional.
Example: package student;
▪ Import statement: This statement instructs the interpreter to load the
Test class contained in the package student. Using import statements, we
can have access to classes that are part of other named packages.
import student.Test;
▪ Interface statement: An interface is like a class but includes a group
of method declarations. This is also an optional section and is used only when
we wish to implement the multiple inheritance features in the program.
interface interface_name;
▪ Class definition: A Java program may contain multiple class
definitions. Classes are the primary and essential elements of a Java
program. The number of classes used depends on the complexity of the
problem.
class class_name
{
Data members;
methods
}
▪ Main method class: Since every Java stand-alone program requires a
main method as its starting point, this class is the essential part of a Java
20
program. The main method creates objects of various classes and establishes
communications between them. On reaching the end of main, the program
terminates and the control passes back to the operating system.
class Sample
{
public static void main (String args[])
{
-------
}
}

Java Tokens:
A Java program is basically a collection of classes. A class is defined by a set
of declaration statements and methods containing executable statements.
Smallest individual units in a program are known as tokens. Java program is
a collection of tokens, comments and white spaces. Java language includes
five types of tokens.
1. Keywords
2. Identifiers
3. Literals (Constants)
4. Operators
5. Separators
1. Keywords: Keywords are an essential part of a language definition. Java
language has 50 keywords. Since keywords have specific meaning in Java,
we cannot use them as names for variables, classes, methods and so on. All
keywords are to be written in lower-case letters. Since Java is case-sensitive.

2. Identifiers: Identifiers refer to the names of classes, methods, variables,


arrays, objects, labels, packages and interfaces in a program. These are
user- defined names and consist of a sequence of letters and digits with a
letter as a first character.
21
Rules for identifiers:
● They can have alphabets, digits and underscore and dollar sign
character.
● They must begin with a letter.
● The upper and lowercase are distinct.
● The variable name should not be a keyword.
● White spaces are not allowed.
● They can be of any length.
3. Literals (Constants): Literals in Java are a sequence of characters that
represent fixed values that do not change during the execution of a program.
▪ Integer literals ▪ String literals
▪ Floating point literals ▪ Boolean literals
▪ Character literals
4. Operators: An operator is a symbol that takes one or more arguments
and performs certain mathematical or logical manipulations.
Types of Operators:
1. Arithmetic 5. Bit wise
2. Relational 6. Assignment
3. Logical 7. Conditional
4. Increment and decrement 8. Special
5. Separators: Separators are symbols used to indicate where groups of
code are divided and arranged. They basically define the shape and function
of our code.
Parentheses () Used to enclose parameters in method definition
braces {} Used to contain the values of automatically initialized
arrays
brackets [] Used to declare array types and for dereferencing
array values.
semicolon : Used to separate statements
comma , Used to separate consecutive identifies in a variable
declaration.

22
Period . Used to separate package names from sub-packages
and classes also used to separate a variable or method from a reference
variable.
Java Statements:
The statements in Java are like sentence in natural languages. A statement is
an executable combination of tokens ending with a semicolon (;) mark.
Statements are usually executed in sequence in the order in which in which

they appear. It is possible to control the flow of execution using special


statements.

➢ Expression: Most statements are expression statements. Java has


seven types of expression statements. Assignment, pre-increment, pre-
decrement, post-increment, post-decrement, method call and allocation
expression.
➢ Labeled statement: Labels in java are used as the arguments of jump
statements. Such labels must not be keywords, already declared local
variables or previously used labels in this module.
➢ Control statement:
▪ Sequential statement: Statements, Which are in between { and }

23
▪ Branching statement: selects one of several control flows. These are
two types of selection statements in java:
o Conditional branching: if, switch, conditional operator
o Unconditional branching: break, continue, return
▪ Iteration statement (Loop): Loop is a statement, which executes a
group of statements for a fixed number of times. There are three types of
iteration statement: and for, while and do while
➢ Synchronization statement: These are used for handling issues with
multithreading.
➢ Guarding statement: Guarding statements are used for safe handling
of code that may cause exceptions (such as division by zero). These
statements use the keywords try, catch and finally.
Implementing a Java Program:
● Creating the program: We can create a program using any text
editor. We must save the program by the class name, which contains the
main method. This file is called the source file. Java source files will have
the extension (.java).
Example:
C:\> EDIT
class Sum
{
public static void main(String args[])
{
int s=0,i;
for(i=1;i<=10;i++)
{
s=s+i;
}
System.out.println(“Sum of 10 natural numbers:”+s);
}
}

24
● Compiling the program: To compile the program, we must run the
java compiler javac, with the name of the source file on the command line
C:\> javac Sum.java
If every thing is OK, the javac compiler creates a file called Sum.class
containing the byte code of the program.

● Running the program: We need to use the java interpreter to run a


stand-alone program. At the command prompt, type
C:\>java Sum
55 (Output)

Machine Neutral: Java compiler converts the source code files into byte
code files. These codes are machine-independent that can be run on any
machine. Java interpreter reads the byte code files and translates them into
machine code for the specific machine on which the java program is running.
Java Virtual Machine: All language compilers translate source code into
machine code for a specific computer. The java compiler produces an
intermediate code known as byte code for a machine that does not exist. This
machine is
called the Java
Virtual
Machine and it exits only inside the computer memory.

The virtual machine code is not machine specific. The machine code is

generated by the java interpreter by acting as an intermediary between the


virtual machine and the real machine.

25
Command line arguments: Command line arguments are parameters that
are supplied to the application program at the time of execution. We can
write java program that can receive and use the arguments provided in the
command line.
public static void main(String args[])
args is declared as an array of strings. Any arguments provided in the
command line are passed to the array args as its elements. We can simply
access the array elements and use them in the program as we wish.
class CommandLine
{
public static void main(String args[])
{
int count, i;
String s;
count=args.length;
System.out.println(“Number of arguments=” +count);
for(i=0;i<count;i++)
{
s=args[i];
System.out.println(s);
}
}
}
C:\> javac CommandLine.java
C:\> java CommandLine Maths Physics Electronics ComputerScience
Number of arguments=4
Maths
Physics
Electronics
Computer science

26
The individual elements of an array are accessed by using an index or
subscript like args[i]. The value of i denotes the position of the elements
inside the array.

27
3. CONSTANTS, VARIABLES AND DATA TYPES
Constants: Constants in Java refer to fixed values that do not change during

the execution of a program.


Integer constant:
● An integer constant refers to a sequence of digits.
● There are three types of integer namely, decimal integer, octal integer
and hexadecimal integer.
● Decimal integers consist of digits 0 through 9, preceded by an optional
minus sign. Embedded spaces, commas and non-digit characters are not
permitted between digits.
Example: 127, -131, 65534 etc.,
● An octal integer constant consists of digits from the 0 through 7, with
leading O.
Example: O37, O435, o346 etc.,
● A sequence of digits preceded by Ox or OX is considered as hexa-
decimal integer. They may also include alphabets A through F or a through f.
A letter A through F represents the numbers 10 through 15.
Example: OX2, OX9F, OXbcd etc.,
Real Constants:
● Numbers containing fractional parts like 17.548. Such numbers are
called real constants.
● A real number may also be expressed in exponential notation. The
general form is
mantissa E exponent

28
● Mantissa is either a real number or an integer. The exponent is an
integer with an optional + or – sign. The mantissa and the exponent can be
written in either lower case or uppercase. Example: 215.65 may be written
as 2.1565e2.
e2 means multiple by 102.
Single character constant:
A single character constant contains a single character enclosed within a pair
of single quote marks.
Examples: ‘5’ ‘x’ ‘;’ ‘’
● Note that the character constant ‘5’ is not the same as the number 5.

String character constant:


● A string constant is a sequence of characters enclosed between double
quotes. The character may be alphabets, digits; special characters and blank
spaces.
“2009” “Programming with Java” “3+6=9” “X”
Backslash character constant:
● Java supports some special backslash character constants that are used
in output methods. For example the symbol ‘\n’ stands for new line character.
Variable: A variable is a data name that may be used to store a data value.
A variable may take different values at different times during execution. A
variable name can be chosen by the programmer in a meaningful way so as
to reflect what it represents in the program.
Rules for a variable:
● They must begin with a letter. ● White spaces are not allowed.
● The upper and lowercase are ● Variable names can be of any
distinct. length.
● It should not be a keyword.

29
Data types: Every variable in Java has a data type. Data types specify the

size and type of values that can be stored. Java language is rich in its data
types.
1. Integer types: Integer types can hold whole numbers. The size of the
values that can be stored depends on the integer data type. Java supports
four types of integers. They are byte, short, int and long. Java doest not
support the concept of unsigned types.

Defaul
Typ
Size t Minimum Value Maximum Value
e
value
byte 1 byte 0 -128 ( -27) 127 (27-1)
shor 2
0 -32,768 ( -215) 32,767 (215-1)
t bytes
4
int 0 -2,147,483,648( -231) 2,147,483,647 (231-1)
bytes
-
9,232,372,036,854,77
8 9,232,372,036,854,775,
long 0L 5,807
bytes 808
(263-1)
63
( -2 )
2. Floating Point Types: Floating point type can hold numbers
containing fractional part such as 22.365 and -89.365. There are two kinds of
floating point storage in java.

30
Minimum Maximum
Type Size Default value
Value Value
float 4 byte 0.0f 3.4e-038 3.4e+038
8
double 0.0d 1.7e-308 1.7e+308
bytes
Floating point numbers are treated as double precision quantities. To force
them to be in single precision mode, we must append f or F to the number.
Double-precision types are used when we need greater precision in storage of
floating point number. All mathematical functions, such as sin, cos and sqt
return double type values.
3. Character type: In order to store character constant in memory, java
provides a character data type called char. The char type assumes a size of 2
bytes but basically it can hold only a single character.
4. Boolean type: Boolean type is used when we want to test a particular
condition during the execution of the program. There are only two values that
a Boolean type can take true or false. Boolean type is denoted by the
keyword Boolean and uses only one bit of storage.
Declaration of variables:
In Java, variables are the name of storage locations. After designing suitable
variable names, we must declare them to the compiler.
● It tells the name of the variable.
● It specifies the type of data.
● The place of declaration decides the scope of the variable.
type variable_1, variable_2, . . . . . variable_n;
Example: int a,b;
Giving values to variables: A variable must be given value after it has
been declared but before it is used in an expression.
1. By using an assignment statement:

31
Syntax: variable name=value; Example: x=0;
It is also possible to assign a value to a variable at the time of its declaration.
Syntax: type variable name=value; Example: int y=2;
The process of giving initial values to variable is known as the initialization. If
the variable is not initialized, it is automatically set to zero.
2. By using a Read statement:

import java.io.*;
Class Reading
{
public static void main(String args[])throws Exception
{
InputStreamReader instr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(instr);
int n=0;
float m=0.0f;
System.out.println(“Enter an integer”);
n=Integer.parseInt(br.readLine());
System.out.println(“Enter a float value”);
m=Float.valueOf(br.readline()).floatValue();
System.out.println(“N=”+ n);
System.out.println(“M=”+ m);
}
}
Scope of variables: The area of the program where the variable is
accessible is called its scope.
1. Instance variables: Instance and class variable are declared inside a
class. Instance variables are created, when the objects are instantiated and
therefore they are associated with the objects. They take different values for
each object.

32
2. Class variables: Class variable are global to a class and belong to the
entire set of objects that class creates. Only one memory location is created
for each class variable.
3. Local variables: Variables declared and used inside methods are
called local variable. They are not available for the outside the method
definition. Local variables can also be declared inside program blocks that are
defined between an opening brace and a closing brace.
Symbolic constants:
final type symbolic-name = value
final float PI= 3.14159;
1. Symbolic names take the same form as variable names. But, they are
written in capitals to visually distinguish them from normal variable names.
2. After declaration of symbolic constants, they should not be assigned
any other values within the program by using an assignment statement.
3. Symbolic constants can not be declared inside a method. They should
be used only as class data members in the beginning of the class.

Type casting: Type casting is a process of convert one data type to another
data type. Casting is often necessary when a method returns a type different
than we require.
type variable_1 = (type) variable_2
Casting into a smaller type may result in a loss of data. The float and double
can be cast to any other type except Boolean. Casting a floating point value
to an integer will result in a loss of the fractional part.
Example: int m=50; byte n = (byte) m;
Automatic type conversion is possible only if the destination type has enough
precession to store the source value. For example, int is large enough to hold
a byte value.
Example: byte b=75; int a=b;

The following conversions will not any loss of data.

33
From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double

▪ The process of assigning a smaller type to a larger one is known as


widening or promotion
▪ The process of assigning a larger type to a smaller one is known as
narrowing.

Giving values of variables: Java supports two output methods that can be
used to send the results to the screen.
● The print()method sends information into a buffer. This buffer is not
flushed until a new line character is sent.
System.out.print(“Hello”);
System.out.print(“Java!”);
Will display the words HelloJava! On one line.
● The println()method takes the information provided and displays it on
a line followed by a line feed(carriage-return) just like ‘\n’ in C.
System.out.println(“Hello”);
System.out.print(“Java!”);

34
Will displays Hello
Java!

Standard Default Values:

In java, every variable has a default value. If we don’t initialize a variable


when it is first created, java provides default value to that variable type
automatically.

Default Values for various Types


S. Type of
Default Value
No variable
1. byte Zero: (byte) 0
2. short Zero: (short) 0
3. int Zero: 0
4. long Zero: 0L
5. float 0.0f
6. double 0.0d
7. char Null character
8. boolean False
9. reference null

35
4. OPERATORS AND EXPRESSIONS
Operators: An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations. Operators are used in
programs to manipulate data and variables.
Types of Operators:
1. Arithmetic 5. Increment and decrement
2. Relational 6. Conditional
3. Logical 7. Bit wise
4. Assignment 8. Special
1. Arithmetic Operators: Arithmetic operators are used to construct
mathematical expressions as in algebra. For arithmetic operations, operands
must be numeric values.
Operato
Meaning
r
+ Addition
- Subtraction
* Multiplication
/ Division
Modulo
%
Division
Arithmetic operations are classified as
1. Integer arithmetic (Both operands are integers)
2. Real arithmetic (Both operands are real numbers)
3. Mixed mode arithmetic (one operand is int and
another one is real)
4. Modulus operator % can be applied to the floating point data as well. It
returns the floating point equivalent of an integer division.
Operato Meaning
r
< Is less than
<= Is less than or equal to

36
> Is greater than
Is greater than or
>=
equal to
== Is equal to
!= Is not equal to
2. Relational Operators: We often compare two quantities, and depending
on their relation, take certain decisions. These comparisons can be done with
the help of relational operators. An expression, which containing a relational
operator is termed as a relational expression. The value of a relational
expression is either true or false
Example: 35>55 false
35==25+10 true
Operato Meaning Example
r
&& AND (a>b)&&(a>c)
|| OR (a>b)||(a>c)
! NOT !(a>b)
3. Logical Operators: An expression, which combines one or more
relational expression, is termed as a logical expression.
Logical Table:
A AND A OR
A B NOT A
B B
T T T T F
T F F T F
F T F T T
F F F F T

37
Example: a=10, b=5, c=15
i=(a>b) &&(b>c) the value of i is false
4. Assignment Operator (=): Assignment operators are used to assign the
result of an expression to a variable.
Syntax: variable = expression
Example: a= 10, b=5, sum=a+b
Java has a set of shorthand assignement operators which are used in the
form
variable operator = expression;
This is equivalent to variable= variable operator (expression);
Example: x+=y+1 this is same as x=x+(y+1)
5. Increment and decrement Operators: The operator ++ adds 1 to the
operand and the operator –- subtracts 1 from operand. We use the increment
and decrement statements in for and while loops extensively.
● A prefix operator first adds 1 to the operand and then the result is
assigned to the variable on left.
m=5; y=++m;
In this case the value of m and y would be 6.
● A postfix operator first assigns the value to the variable on the left
and then increment the operand.
m=5; y=m++;
In this case value of y would be 5 and m would be 6.
6. Conditional operator: Conditional operator is a combination of ? , : and
takes three operands. So it is a ternary operator.
(expression_1) ? (expression_2): (expression_3);
expression_1 is evaluated first. If it is true, then the expression_2 is
evaluated and becomes the value of the expression. If expression_1 is
false, expression_3 is evaluated and its value becomes the value of the
expression.
Example: a=10; if(a>b)
b=15; big=a;
x=(a>b)? a:b; else
38
big=b;
7. Bit wise Operators: Java has a distinction of supporting special
operators known bit wise operators for manipulation of data at bit level.
These operators are used for testing the bits, or shifting them right or left.
Bitwise operators may not be applied to float or double.
Example: a=-4 b=6
Opera
Meaning
tor
& bit wise AND
| bit wise OR
bit wise exclusive
^
OR
<< shift left
>> shift right
shift right with
>>>
zero fill
one’s
~
complement

The equivalent binary value of a = 10000100


The equivalent binary value of b = 00000110
● a&b = 00000100 a | b = 10000110
● a^b = 10000010 a << 2 = 00010000
● b >> 2 = 00000001 a >>> 2 = 00100001
● ~a = 01111011
8. Special Operator:
Instanceof operator: The instanceof is an object reference operator and
return true if the object on the left-hand side is an instance of the class given
on the right-hand side. This operator allows us to determine whether the
object belongs to a particular class or not.
Example: x instanceof student

39
Is true, if the object x belongs to the class student; otherwise it is false.
Dot operator:
The dot operator (.) is used to access the instance variable and methods of
class objects.
x.rno x.name x.average()
It is also used to access classes and sub-packages from a package.
Arithmetic expressions: An arithmetic expression is a combination of
variables, constants and operators arranged as per the syntax of the
language.
Example: (m+n) * (x+y)
Evaluation of expressions: expressions are evaluated using an assignment
statement as
Variable = expression
Variable is any valid java variable name. When the statement is encountered
the expression is evaluated first and the result will replaces the previous
value of the variable on the left-hand side. All variables used in the
expression must be assigned values before evaluation is attempted.
Precedence of arithmetic operators:An arithmetic expression without any
parentheses will be evaluated from the left to right using the rules of
precedence of operators. There are two distinct priority levels of arithmetic
operators in java.
High priority * / %
Low Priority + -
The basic evaluation procedure includes two left to right passes through the
expression. During the first pass, the high priority operators are applied as
they are encountered. During the second pass, the low priority operators are
applied as they are encountered.
UNIT: II
5. DECISION MAKING AND BRANCHING
When a program breaks the sequential flow and jumps to another part of the
code is called branching. If branching is based on a particular decision is

40
known as decision making and branching. Decision making and branching
statement are classified into three types. They are
1. If statement 2. Switch statement 3.
Conditional operator
a. Simple if
b. if …else
c. Nested if …else
d. Else if ladder
1. If statement: The if statement is a powerful decision making statement
and is used to control the flow of execution of statements. It is basically a
two-way decision statement and is used in conjunction with
an expression.
if(test_expression)
It allows the computer to evaluate the test_expression
first and then, depending on whether the value of the test_expression is
true or false, it transfers the control to a particular statement.

a. Simple if statement: If the test_expression is true, then the


statement-1 will be executed. Otherwise the execution will jump to the
statement-2.

b. If_ else statement: If the test expression is true, then the true-block
statements will be executed. Otherwise the false-block statements will be
executed and then the control is transferred to the statement-x

41
c. Nested If_ else: When a series of decisions are involved, we may have to
use more than one if else statement in nested form as follows.

If the test expression is false, then statement_3 will be executed;


otherwise it continues to perform the second test. If the test_condition2 is
true, then statement-1 will be executed, otherwise statement-2 will be
executed and then the control is transferred to the statement-x

d. The else_if ladder: There is another way of putting ifs together when
multi-path decision are involved, A multi-path decision is a chain of ifs in
which the statement associated with each else is an if. The general form is

42
(b). Switch statement: The switch statement tests the value of a given
variable against a list of case values and when a match is found, a block of
statements associated with that case is executed. The general form of the
switch statement is as

Conditional operator: Conditional operator is a combination of ? , : and


takes three operands. So it is a ternary operator.

43
(expression_1) ? (expression_2): (expression_3);

expression_1 is evaluated first. If it is true, then the expression_2 is


evaluated and becomes the value of the expression. If expression_1 is
false, expression_3 is evaluated and its value becomes the value of the
expression.

Example: a=10; if(a>b)


b=15; big=a;
big=(a>b)? a:b; else
big=b;

6. DECISION MAKING AND LOOPING


Loop statement: Loop is a statement, which executes a sequence of
statements until a condition is satisfied. It consists of two segments, one
known as the body of the loop and the other known as the control statement.
The control statement tests certain conditions and then directs the repeated
execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, the control
structure may be classified either as entry controlled loop or as the exit
controlled loop.
● In the entry controlled loop, control conditions are tested before the
start of the loop execution. If the conditions are not satisfied, then the body
of the loop will not be executed. Example: For loop and While loop.
● In the exit-controlled loop, the test is performed at the end of the
body of the loop and therefore the body is executed unconditionally for the
first time.

44
Example: do while loop

A loop generally includes the following four steps:


1. Initialization of a counter.
2. Test for a specified condition for execution of the loop.
3. Execution of the statements in the loop.
4. Incrementing the counter.
1. For loop: The for loop is entry-controlled loop that provides a more
concise loop control structure. The general form is
Syntax: for (initialization; test condition; increment/decrement)
{
body of the loop;
}
Example: for (i=1; i<=n; i++)
{
System.out.println(i);
}
2. The while loop: The while loop is an entry controlled loop statement. The
test-condition is evaluated and if the condition is true, then the body of the
loop is executed. After execution of the body, test-condition is once again
evaluated and if it is true, the body is executed once again.

45
3. do_while loop: The do while loop is an exit controlled loop statement.
This process continues as long as the condition is true. If the condition
becomes false, the loop will be terminated and the control goes to the
statement that appears immediately after the while statement.

Enhanced for Loop: The enhanced for loop, also called for each loop is an
extended language feature introduced with the J2SE 5.0 release. This feature
helps us to retrieve the elements efficiently rather than using array indexes.

for(Type Identifier : Expression) a. Typerepresents the data type or object used.

{ b. Identifier refers to the name of a variable


c. Expressionis an instance of the java.lan.Iterable
statements;
interface or an array.
}

int a[3]={10,20,30}; int a[3]={10,20,30};


for(int i=0;i<3;i++) for(int i:a)
{ {
System.out.print(“ ” + a[i]); System.out.print(“ ” + i );
} }

46
Jumps in Loops:
Java permits a jump from one statement to the end or beginning of a loop as
well as a jump out of a loop. Exit from a loop can be accomplished by using
the break statement. We have already seen the use of the break in the
switch statement. When the break statement is encountered inside a loop,
the loop is immediately exited and the program continues with the statement
immediately following the loop.

Skipping: During the loop operations, it may be necessary to skip a part of


the body of the loop under certain conditions. The continue statement
causes the loop to be continued with the next iteration after skipping any
statements in between. The continue statement tell the compiler
“SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH THE
NEXT ITERATION”.

Labeled loops: In Java, we can give a label to a block of statements. A label


is any valid java variable name. To give a label to a loop, place it before the
loop with a colon at the end.
loop1: for( . .. . )
{
. . ..
}

outer:for(int m=1;m<11;m++) loop1:for(int m=1;m<11;m++)


{ {
inner:for(int n=1;n<11;n++) loop2:for(int n=1;n<11;n++)
{ {
System.out.print(“”+m*n); System.out.print(“”+m*n);
If(m==n) If(m==n)
continue outer; break loop1;
} }
} }
. . . . . . .. . . . . . . .
47
▪ continue outer; statement terminates the inner loop when m==n and
continues with the next iteration of the outer loop.
▪ break loop1 causes the execution to break out of both the loops

48
7. CLASSES, OBJECTS AND METHODS
Java is a true object-oriented language and therefore the structure of all java
programs is classes. A class that defines the state and behavior of the basic
components known as objects. Classes create objects and objects use
methods to communicate between them.
Classes provide a convenient method for packing together a group of logically
related data items and functions that work on them. In Java the data items
are called fields and the functions are called methods. Calling a specific
method in an object is described as sending the object a message.
Defining a class: A class is user-defined data type with a template that
serves to define its properties. Once the class type has been defined, we can
create variables of that type using declarations that are similar to the basic
type declarations. In Java, these variables are termed as instances of classes,
which are the actual objects.
A class is a way to bind the data and its associated methods (functions)
together. It allows the data and functions to be hidden. When defining a class
we are creating a new Abstract Data Type that can be treated like any other
built–in data type.
A Class specification has two parts:
1. Class declaration
2. Methods declaration.

49
The class declaration describes the type and scope of its members. The class
function definitions describe how the class functions are implemented.
Syntax class class_name [exdends superclass_name]
{
[field declarations;]
[methods declarations;]
}
Class_name and super_class_name are any valid java identifiers. The
keyword extends indicates that the properties of the super_class_name class
are extended to the class_name class. This concept is known as inheritance.

Fields declaration: Data is encapsulated in a class by placing data inside


the body of the class definition. These variables are called instance variables
because they are created whenever an object of the class is instantiated.
class Rectangle
{
int l,b;
}

Method declaration: Methods are necessary for manipulating the data


contained in the class. Methods are declared inside the body of the class but
immediately after the declaration of instance variables.
type method_name (parameter-list)
{
method-body;
}
✓ The type specifies the type of value the method would return. This
could be a simple data type such as int as well as any class type. It could
even be void type, if the method does not return any value.
✓ The method_name is a valid identifier.
✓ The parameter_list is always enclosed in parentheses. This list contains
variable names and types of all the values we want to give to the method as
50
input. The variables in the list are separated by commas. In the case where
no input data are required, the declaration must retain the empty
parentheses.
✓ The method body actually describes the operations to be performed on
the data.
Example:
class student
{
int x; //field declaration
int y;
void getdata(int a,int b) // method declaration
{
x=a;
y=b;
}
}

Creating Objects: The declaration of an object is similar to that of a variable


of any basic type. The necessary memory space is allocated to an object at
this stage.
Objects in Java are created using the new operator. The new operator creates
an object of the specified class and returns to that object. Here is an example
of creating an object of type student.
student s; // declare the object;
s=new student(); // instantiate the object;
✓ The first statement declares a variable to hold the object
reference(address).
✓ Second one actually assigns the object reference to the variable.
student s=new student(); // instantiate the object;
The student() is the default constructor of the class. We can create any
number of objects of student.

51
Accessing class members: Each object containing its own set of variables.
All variables must be assigned values before they are used. We cannot access
the instance variable and the method directly, when we are in outside the
class.
object_name.variable =value
▪ object_name is the name of the object.
▪ variable_name is the name of the instance variable inside the object.

object_name.method_name(parameter-list)
▪ object_name is the name of the object.
▪ method_name is the method that we wish to call, and parameter-list is
a list of the parameters.
Example:
s.x = 5;
s.y = 8;
s.getdata(5,8);

Memory allocation for objects: Memory space for objects is allocated when
they are declared and not when the class is specified. The member functions
are created and placed in the memory only once when they are defined as a
part of a class specification. Since all the objects belong to that class use the
same member functions, no separate space is allocated separately for each
object.

Constructor:
1. A constructor is a special member function for automatic initialization of
an object.
2. A constructor is distinct from other member function of the class. It has
the same name as its class.
3. It is executed automatically when an object is created.
52
4. It is generally used to initialize object member.
5. The constructor has no return value.
6. The constructor of a class is the first member function to be executed
automatically when an object of the class is created.
7. The constructor is executed every time an object of that class is
defined.
8. The constructor, which does not take arguments explicitly is called
default constructor.
class Room
{
int l,b;
Room(int x,int y) // Defining constructor
{
l=x;
b=y;
}

int area()
{
return(l*b);
}
}
Class Rectangle
{
public static void main(String args[])
{
Room r1=new Room(15,10); //Calling Constructor
int a1=r1.area();
System.out.println(“AREA=” + a1);
}
}
Method overloading:
53
▪ Create more than one methods that have the same name, but different
parameter lists and different definitions. This is cal
▪ led 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, java matches up the method name
first and then the number and type of parameters to decide which one of the
definitions to execute. This process is known as polymorphism.

class Room
{
int l, b;
Room(int x,int y) // constructor 1
{
l=x;
b=y;
}
Room(int x) // constructor 2
{
l=b=x;
}
int area()
{
return(l*b);
}
}
Class Rectangle1
{
public static void main(String args[])
{
Room r1=new Room(25,15); //Calling Constructor1
Room r2=new Room(15); //Calling Constructor2
54
int a1=r1.area();
int a2=r2.area();
System.out.println(“Area1=” + a1);
System.out.println(“Area2=” + a2);
}
}

Static Data Members:


✴ It is initialized to zero when the first object of its class is created.
✴ Only one copy of that member is created for the entire class and is
shared by all the objects of that class.
✴ It is visible only within the class, but its lifetime is the entire program.
✴ Static variable are normally used to maintain values common to the
entire class.
✴ Static variables can be defined as static int count;

Static methods:
✴ Static methods are called using class names.
✴ They can only call other static methods.
✴ They can only access static data.
✴ They cannot refer to this or super in any way.
✴ Static functions can be defined as static int max(int x,int y);

class Arithmetic
{
static float mul(float x,float y)
{
return x*y;
}
static float div(float x,float y)
{
return x/y;
55
}
}

class Application
{
public Static void main(String args[])
{
float a=Arithmetic.mul(14.0f,5.2f);
Sytem.out.println(“Multiplication is=”+a);
float b=Arithmetic.div(4.2,2.0);
Sytem.out.println(“Division is=”+b);
}
}

Nesting of methods: A method can be called using only its name by


another method of the same class. This is known as Nesting of Methods.

class Nesting
{
int m,n;
Nesting(int x,int y) // constructor method
{
m=x; n=y;
}
int largest()
{
if(m>=n)
return(m);
else
return (n);
}
void display()
56
{
int big=largest(); // calling a method
system.out.println(“Largest value=” + big);
}
}
class NestingTest
{
public Static void main(String args[])
{
Nesting n=new Nesting(50,40);
n.display();
}
}

57
UNIT: III
8. INHERITANCE: EXTENDING A CLASS
Java strongly supports the
concept of reusability. The Java
classes can be reused in several
ways. Once a class has been
written and tested, it can be used
again. The mechanism of deriving
a new class from an old class is
called inheritance. The old class
is referred to as the base class
and the new class is called the
derived class.
The derived class inherits some or all the properties from the base class. A
class can also inherit properties from more than one class or more than one
level.
▪ A derived class with only one base class is called single-inheritance
▪ One with several base classes is called multiple-inheritance.
▪ More than one class may inherit from one base class; this is known as
hierarchical-inheritance.
▪ The process of deriving a class from another derived class is known as
multi-level inheritance.

Defining a subclass: A derived class can be defined by specifying its


relationship with the base class in addition to its own details. The general
form of defining a derived class is:
class sub_class_name: extends super_class_name
{
variable declarations;
methods declarations;
}

58
The keyword extend signifies that the properties of the super_class_name
are extended to the sub_class_name. The subclass will now contain its own
variable and methods as well those of the super class.
class Room1
{
int l,b;
Room1(int x,int y) // Defining constructor
{
l=x;
b=y;
}

int area()
{
return(l*b);
}
}

class Room2 extends Room1 // Inheriting Room1


{
int h;
Room2(int x,int y, int z) // Defining constructor
{
super(x,y); // passing values to super class
h=z;
}
int volume()
{
return(l*b*h);
}
}
59
Class Inher
{
public static void main(String args[])
{
Room2 r1=new Room2(15,12,10);
int a1=r1.area(); // Super class Method
int v1=r1.volume(); // sub class Method
System.out.println(“Area1=” + a1);
System.out.println(“Volume=” + v1);
}
}

Super:
A subclass constructor is use to construct the instance variable of both the
subclass and the super class. The subclass constructor uses the keyword
super to invoke (execute) method of the super class.
● super may only be used within a subclass constructor method.
● The call to super class constructor must appear as the first statement
within the subclass constructor.
● The parameter in the super call must match the order and type of the
instance variable declared in the super class.

60
Overriding methods: Defining a method in the sub class that has the same
name, same arguments and same return type as a method in the super class.
When method is called, the method defined in the subclass is invoked and
executed instead of the one in the super class. This is known as overriding.
Example:

class Superclass
{
int x;
Superclass(int a) // Defining constructor
{
x=a;
}

void display()
{
System.out.println(“Super x=”,+x);
}
}
class Sub extends Superclass // Inheriting super
{

61
int y;
Sub(int a,int b) // Defining constructor
{
super(a); // passing values to superclass
y=b;
}

void display()
{
System.out.println(“Super x=”,+x);
System.out.println(“Sub y=”,+y);
}
}
Class Override
{
public static void main(String args[])
{
Sub s1=new Sub(100,200);
S1.display();
}
}
Output:
Super x=100
Sub y=200
● Note that the method display () defined in the subclass is invoked.

Final variables and methods: All methods and variables can be overridden
by default in subclasses. If we wish to prevent the subclass from overriding
the members of the super class, we can declare them as final using the
keyword final as a modifier.
final int size =100;
62
final void show()
{
}

Final classes: Sometimes we may like to prevent a class being further


subclass for security reasons. A class that cannot be subclass is called a final
class.
final class class_name
{
}

Finalize method: Constructor method is used to initialize an object when it


is declared. This process is called as initialization. Java supports a concept
called finalization, which is just opposite to initialization. In order to free up
the memory resources used by the objects, we must use a finalize method.
The finalize method should explicitly define the task to be performed.
▪ Finalize method cannot be overloaded.
▪ It does not take any arguments.
▪ It does not have return type.

Abstract methods and classes: We can indicate that a method must


always be redefined in a subclass, thus making overriding compulsory. This is
done using the modifier keyword abstract in the method definition.
abstract class shape
{
abstract void draw();
}
● We cannot use abstract classes to instantiate objects directly like.
Shape s =new Shape ();
● The abstract method of an abstract class must be defined in its
subclass.
● We cannot declare abstract constructor or abstract static methods.
63
64
9. ARRAYS
An array is a variable that can store multiple values of same data type;
where as an ordinary variable can store a single value at a time.

One-Dimensional Array: An Array in which list of elements are stored in


continuous memory locations and accessed using only one subscript (index).

● Declaration of one-dimensional array:


type array_name [ ];
(or)
type [ ] array_name;
Where, type is the data type of array elements; array_name is name of array
variable. Remember, we do not enter the size of the arrays in the declaration.

● Creation memory locations: After declaring an array, we need to


create it in the memory. Java allows us to create arrays using new operator
only.
array_name= new type [size];
Example: a=new int[5]

The two statements may be combined as follows:


Type array_name[ ] = new type[size];
int a[]=new int[5];
The total size of the array 5 X 4 =20 bytes, this is because each integer
element requires 4 bytes for storage.

● Initialization of one-dimensional array: Assigning values to an


array when it is created is known as initialization.
type array_name[ ]={list of elements separate by commas};
int a[ ]={5,8,2,6};

65
In the above example, four elements are stored in an array ‘a’. The array
elements are stored in contiguous memory locations. The array elements are
read from 0 i.e. a[0] is assigned the value 5. Similarly a[1] is assigned the
value 8, a[ 2] is 2 and a[3] is 6.

a[0] a[1] a[2] a[3]

5 8 2 6

Subscript of an array is an integer expression, integer constant or integer


variable that refers to different elements in the array. Here array subscripts
start at zero. Therefore the elements are a[0], a[1], . . .a[3].

Array length: In java, we can obtain the length of the array a using
a.length.
Example: int n =a.length
for (i=0;i<=n;i++)
System.out.print(“ “+a[i])

/* Sorting a list of elements*/


class NumberSort
{
public static void main(Strings args[])
{
int a[]={4,8,1,9,6};
int n=a.length;
System.out.println(“Given list:”);
for(int i=0;i<n;i++)
System.out.print(“ ”+a[i]);
System.out.println(“ ”);
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
if(a[i]<a[j])
66
{
int t=a[i];
a[i]=a[j];
a[j]=t;
}
}
System.out.println(“Sorted list:”);
for(int i=0;i<n;i++)
System.out.print(a[i]);
}
}
Two-Dimensional Array: An Array in which list of elements are stored in
some rows and columns (matrix) and accessed using two subscripts.
● Declaration of two-dimensional array:
type array_name [ ][ ];
Where, type is the data type of array elements; array_name is name of array
variable. Remember, we do not enter the size of the arrays in the declaration.

● Creation memory locations: After declaring an array, we need to


create it in the memory. Java allows us to create arrays using new operator
only.
array_name= new type [row_size][col_size];
Example: a=new int a[5][3]
Here array ‘a’ which can hold 5 x 3 = 15 integer elements.

The two statements may be combined as follows:


type array_name[ ][ ] = new type[row_size][col_size];
int a[][]=new int[5][3];
The total size of the array 15 X 4 =60 bytes, this is because each integer
element requires 4 bytes for storage.

67
● Initialization of two-dimensional array: Assigning values to an
array created is known as initialization.
array_name [subscript] [subscript]=value;
Example: a[0][0]=5; a[0][1]=8;
type array_name[ ][ ]={{list of elements in row},{list of elements in
column}};
int a[ ][ ]={{5,-7,2,1},{9,8,5,6},{-1,8,-3,4}};

5 -7 2 1
a[0][0] a[0][1] a[0][2] a[0][3]

9 8 5 6
a[1][0] a[1][1] a[1][2] a[1][3]

-1 8 -3 4
a[2][0] a[2][1] a[2][2] a[2][3]

Subscripts can also be reflected in for loops that the array elements.
for (i=0;i<r;i++)
for(j=0;j<c;j++)
System.out.print(“ ”+a[i][j]);
/* Multiplication table */
class Table
{
final static int r=10;
final static int c=10;
public static void main(String args[])
{
int a[][]=new int[r][c];
System.out.println(“MULTIPLICATION TABLE:”);
for(int i=1;i<=r;i++)
{
for(int j=1;j<=c;j++)
{
a[i][j]=i*j;
System.out.print(“ ”+a[i][j]);
}
68
System.out.println(“ ”);
}
}
}

/* Matrix Multiplication */

import java.io.*;
import java.lang.String.*;
class Matrix
{
public static void main(String args[])throws Exception
{
InputStreamReader instr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(instr);
int a[][],b[][],c[][],r1,r2,c1,c2;
System.out.println("Enter the size of A Matrix");
r1=Integer.parseInt(br.readLine());
c1=Integer.parseInt(br.readLine());
System.out.println("Enter the size of B Matrix");
r2=Integer.parseInt(br.readLine());
c2=Integer.parseInt(br.readLine());
if(c1==r2)
{
a=new int[r1][c1];
b=new int[r2][c2];
System.out.println("Enter the elements of A matrix:");
for(int i=0;i<r1;i++)
for(int j=0;j<c1;j++)
a[i][j]=Integer.parseInt(br.readLine());
System.out.println("Enter the elements of B matrix:");
for(int i=0;i<r2;i++)
69
for(int j=0;j<c2;j++)
b[i][j]=Integer.parseInt(br.readLine());
c=new int[r2][c1];
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
c[i][j]=0;
for(int k=0;k<c2;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
System.out.println("A*B matrix:");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
System.out.print(" "+c[i][j]);
System.out.println(" ");
}
}
else
{
System.out.println("MATRIX MULTIPLICATION NOT POSSIBLE !");
}
}
}
2
Output: 2
Enter the size of A Matrix
2
2
Enter the size of B Matrix Enter the elements of A matrix:
70
1 0
2 0
3 1
4 A*B matrix:
Enter the elements of B matrix: 1 2
1 3 4
Strings: String manipulation is the most common part of many java
programs. Strings represent a sequence of characters.
In Java, strings are class object and implemented using two classes namely
String and StringBuffer. A Java string is an instantiated of the String class.
A Java string is not a character array and is not terminated with NULL.
Syntax: String string_name;
string_name = new String(“string”);
Example: String a;
a = new String(“JAVA”);
The two statements may be combined as follows:
String a = new String(“JAVA”);
It is possible to get the length of string using the length method of the
String class.
int m = a. length()
String c = a + b;
String Arrays: We can also create and use arrays that contain strings
String a[ ]=new String[3];
Will create an array of size 3 to hold three string constants.
Sting methods: The string class defines a number of methods that allow us
to accomplish a variety of string manipulation tasks.
Method Task performed
s2=s1.toLowerCase; Converts the string s1 to all lowercase
s2=s1.toUpperCase; Converts the string s1 to all uppercase
s2=s1.replace(‘x’,’y’); Replace all appearances of x with y
s2=s1.trim(); Remove white space s at the beginning and end of

71
the string s1.
s1.equals(s2); Return ‘true’ if s1 is equals to s2
s1.equalsIgnoreCase(s Return ‘true’ if s1=s2, ignoring the case of
2); characters
s1.lenght(); Gives the length of s1
s1.CharAt(n); Gives nth character of s1
s1.comparTo(s2) Return – if s1<s2 , + if s1>s2 and 0 if s1 =s2
s1.concat(s2); Concatenates s1 and s2
s1.substring(n); Gives substring starting from nth character
Gives substring starting from nth character up to mth
s1.substring(n,m);
character.
Gives the position of the first occurrence of ‘x’ in the
s1.indexOf(‘x’);
string s1
Gives the position of the ‘x’ that occurs after nth
s1.indexOf(‘x’,n);
position in the string s1
StringBuffer Class: StringBuffer Class is a peer (similar) class of String.
While String creates strings of fixed_length, StringBuffer creates strings of
flexible length that can be modified in terms of both length and content. We
can insert characters and substrings in the middle of a string or append string
to the end.

Method Task
s1.setCharAt(n,’x’) Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end

s1.insert(n,s2) Insert the string s2 at the position n of the string s1

Sets the length of the string s1 to n. If n<s1.lenght()


s1.setLength(n)
s1 is truncated. If n>s1.lenght() zeros are added to s1

/* Sorting of Strings*/
class StringOrder

72
{
static String
name[]={“Madras”,”Delhi”,”Ahmedabad”,”Calcutta”,”Bombay”}
public static void main(Strings args[])
{
int size=name.length;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[i].compareTo(name[j])>0)
{
String t=name[i];
name[i]=name[j];
name[j]=t;
}
}
}
for(int i=0;i<size;i++)
System.out.println(name[i]);
}
}

Vectors: Vector class can be used to create a generic dynamic array known
as vector that can hold objects of any type and any number. Vectors are
created like arrays as follows.
Vector a=new vector(); // declaring without size
Vector a=new vector(3); // declaring with size
Advantages:
1. It is convenient to use vectors to store objects.
2. A vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as and when required.
73
The major constraint in using vectors is that we cannot directly store simple
data type in a vector, we can only store objects. Therefore, we need to
convert simple types to objects. This can be done using the wrapper
classes.

/* Example for Vectors */


import java.util.*;
class Example
{
public static void main(Strings args[])
{
Vector v =new Vector();
int l=args.length;
for(int i=0;i<l;i++)
v.addElement(args[i]);
v.insertElementAt(“COBOL”,2)
int s=v.size();
String a[]=new String[s];
v.copyInto(a);
System.out.println(“List of languages:”);
for(int i=0;i<s;i++)
System.out.print(“ ”+a[i]);
}
}
C:\>java VectorExample Ada BASIC C++ FORTRAN JAVA
List of language:
Ada BASIC COBOL C++ FORTRAN
JAVA

Wrapper classes:
74
Vectors cannot handle primitive data types like int, float, long, char and
double. Primitive data types may be converted into object types by using the
wrapper classes contained in the java.lang package.

Wrapper classes for converting simple


types
Simple type Wrapper class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long

75
10. INTERFACES: MULTIPLE INHERITANCES
Interfaces: An interface is basically a kind of class. The difference is that
interfaces define only abstract methods and final fields. This means that
interfaces do not specify any code to implement these methods and data
fields contain only constants.
interface interface_name
{
Variable declaration;
Method declaration;
}

Here, interface is the keyword and interface_name is any valid java


identifier. Variables are declared as follows:
Static final type variable_Name = value;
● Note that all variables are declared as constants. Method declaration
will contain only a list of methods without anybody statement.
return_type method_name (parameter_list);

Example:
interface Area
{
final static float PI=3.14f;
float compute(float x,float y);
}
Extending interfaces: Interfaces can also be extended. An interface can be
sub interfaced from other interfaces. The new sub interface will inherit all the
members of the super interface in the manner similar to subclasses. This is
achieved using the keyword extends as…
interface name2 extends name1
{
Body of name2;
}
76
We can put all the constants in one interface and the methods in the other.
This will enable us to use the constant in classes where the methods are not
required.
interface A
{
final static float PI=3.14f;
}
interface Area extends A
{
float compute(float x,float y);
}

Implementing interfaces: Interfaces are used as super classes whose


properties are inherited classes.
class classname implements interfacename1, interfacename2
{
Body of the class
}
Here, the class class_name implements the interface interface_name.

Example:
class Rectangle implements Area
{
public float compute(float x,float y)
{
return(x*y);
}
}

/* Example for interfaces */


interface Area // interface defined
77
{
final static float PI=3.14f;
float compute(float x,float y);
}
class Rectangle implements Area // interface implemented
{
public float compute(float x,float y)
{
return(x*y);
}
}
class Circle implements Area // other interface implemented
{
public float compute(float x,float y)
{
return(PI*x*y);
}
}
class Interface
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
Circle c=new Circle();
Area a; // Interface object
a=r; // area refers to r object
System.out.println(“Area of Rectangle=”+ a.compute(10,20))
a=c;
System.out.println(“Area of Circle=”+ a.compute(10,0))
}
}
Output:
78
Area of Rectangle: 200
Area of Circle: 314
Any number of dissimilar classes can implement an interface. However, to
implement the methods we need to refer to the class objects as types of the
interface rather than types of their respective classes. Note that if a class that
implements an interface does not implement all the methods of the interface,
then the class becomes an abstract class and cannot be instantiated.

Accessing interface variables: Interfaces can be used to declare a set of


constants that can be used in different classes. The interfaces do not contain
methods. The constant values will be available to any class that implements
the interface. The values can be used in any method, as part of any variable
declaration.
interface A
{
final static int m=10;
final static int n=50;
}
class B implements A
{
int x=m;
void methodB(int size)
{
…………
if(size<n)
………….
}
}
/* Implementing multiple inheritance */

class Student
{
79
int rno;
void get(int n)
{
rno=n;
}
void put()
{
System.out.println(“Roll No:”+rno);
}
}

class Test extends Student


{
float m,p,cs;
void getMarks(float m1,float m2,float m3)
{
m=m1; p=m2; cs=m3;
}

void putMarks()
{
System.out.println(“Maths:”+ m);
System.out.println(“Physics:”+ p);
System.out.println(“Computers:”+ cs);
}
}

interface Sports
{
staic final float sportWt=6.0f;
80
void putwt();
}
class Results extends Test implements Sports
{
float total;
public void putwt()
{
Sytem.out.println(“Sports Weightage =”+sportwt);
}

Void display()
{
total=m+p+cs+sportwt;
put();
putMarks();
putWt();
System.out.println(“Total Score:”+ total)
}

Class Hybrid
{
public static void main(String args[])
{
Results s=new Results();
s.get(1024);
s.getMarks(85.5f,80.0f,90.0F);
s.display();
}
}

81
Output:
Roll NO:1024
Maths=85.5
Physics=80.0
Computers=90.0
Sports Wt=6
Total score=261.5

UNIT: IV
11. MULTITHREADED PROGRAMMING
The ability to execute several programs simultaneously is known as
multitasking. Multithreading is a conceptual programming where a program
is divided into two or more subprograms, which can be implemented at the
same time in parallel.
In computers, we have only a single processor and therefore, the processor is
doing only one task at a time. However the processor switches between the
processes so fast that it appears that all of them are being done
simultaneously.
Thread: A thread is similar to a program that has a single flow of control. A
unique property of java is its support for multithreading. Java enables us to
use multiple flows of control in developing programs. Each flow of control
may be thought of as a separate tiny program known as a thread that runs in

82
parallel to others. A program that contains multiple flows of control known as
Multithreaded Program.
Once initiated by the main thread, the threads A, B and C run concurrently
and share the resources jointly. The ability of a language to support
multithreads is referred to as concurrency. Since threads in Java are
subprograms of a main application program and
share the same memory space, they are known as
lightweight threads or lightweight processes.

✓ Multithreading is a powerful programming tool


that makes java distinctly different from other
programming language.
✓ It enables programmers to do multiple things
at one time.
✓ They can divide a long program into threads and execute them in
parallel.
✓ Threads are extensively used in java-enabled browsers such HotJava.

Creating Threads: Threads are implemented in the form of objects that


contain a method called run(). The run() method is the heart and soul of
any thread. It makes up the entire body of a thread and is the only method in
which the thread’s behavior can be implemented.
public void run()
{
statements for thread
}
The run() method should be invoked by an object of the concerned thread.
This can be achieved by creating the thread and initiating it with the help of
another thread method called start().
A new thread can be created in two ways:

83
1. By creating a thread class: Define a class that extends Thread class
and override its run() method with the code required by the thread.
2. By converting a class to a thread: Define a class that implements
Runnable interface. The Runnable interface has only one method, run() that
is to be defined in the method with the code to be executed by the thread.

1. Extending the thread class: We can make our class runnable as thread
by extending the class java.lang.Thread. This gives us access to all thread
methods directly.
1. Declare the class as extending the Thread class.
Class MyThread extends Thread
{
......
}
2. Implement the run() method that is responsible for executing the
sequence of code that the thread will execute.
public void run ()
{
......
}
3. Create a thread object and call the start() method to initiate the
thread execution.
Mythread T =new MyThread();
T.start(); // invoking run() method
An Example of using the Thread class:
import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
84
System.out.println(“Thread A : i =” + i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println(“Thread B: j=” + j);
}
System.out.println(“Exit from B”);
}
}

class C extends Thread


{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println(“Thread C: k=” + k);
}
System.out.println(“Exit from C”);
}
}

Class ThreadTest
{
public static void main(String args[])
85
{
A t1 =new A();
B t2 =new B();
C t3 =new C();
t1.start();
t2.start();
t3.start();
}
}

✓ Note that the output from the threads is not sequential. They do not
follow any specific order. They are running independently of one another and
each executes whenever it has a chance.

Stopping a thread: Whenever we want to stop a thread from running state,


then call stop() method. t.stop ()
This statement causes the thread to move to the dead state. A thread will
also move to the dead state automatically when it reaches the end of its
method.

Blocking a thread: A thread can also be temporarily suspended or blocked


from entering into the runnable and subsequently running state by using
either of the following thread methods:
sleep() // blocked for a specified time
suspend() // blocked until further order
wait() // blocked until certain condition occurs
These methods cause the thread to go into the blocked state. The thread will
return to the runnable state when the specified time is elapsed in the case of
sleep(), the resume() method is invoked in the case of suspend(), and the
notify() method is called in the case of wait().

86
Life cycle of a thread: During the life of
a thread, there are many states it can
enter. They are:

1. Newborn state.
2. Runnable state
3. Running state.
4. Blocked state.
5. Dead state.

Newborn state: When we crate a thread object, the


thread is born and is said to be in newborn state. The
thread is not yet scheduled for running. At this state, we
can do
▪ Schedule it for running using start() method.
▪ Kill it using stop() method.
If scheduled, it moves to the runnable state. If we
attempt to use any other method at this stage, an exception will be thrown.
1. Runnable state: The runnable state means that the thread is ready for
execution and is waiting for the availability of the processor. The thread has
joined the queue of threads that are waiting for execution. If all threads have
equal priority, then they are given time slots for execution in round robin
fashion (first-come, first-serve manner). This process of assigning time to
threads is known as time-slicing.
Yield means that the current thread is willing to give for another thread.

87
2. Running state: Running means that the processor has given its time
to the thread for its execution. The thread runs until it relinquishes control on
its own or it is preempted by a higher priority thread.
a. It has been suspended using suspend() method. A suspended thread
can be revived by using the resume() method.

88
b. It has been made to sleep. We can put a thread to sleep for a specific
time period using the method sleep(time). The thread re-enters the
runnable state as soon as this time period is elapsed.

c. It has been to wait until some event occurs. This is done using the
wait() method. The thread can be scheduled to run again using the notify()
method.

3. Blocked state: A thread is said to be blocked when it is prevented


from entering into the runnable state and subsequently the running state.
This happens when the thread is suspended, or waiting in order to satisfy
certain requirements.

4. Dead State: Every thread has a life cycle. A running ends its life when
it has completed executing its run() method. It is a natural death. However,
we can kill it by sending the stop message to it at any state.

Example for using thread-methods


import java.lang.Thread;
class A extends Thread
{
public void run()

89
{
for(int i=1;i<=5;i++)
{
if (i==1)
yield();
System.out.println(“Thread A: i=” + i);
}
System.out.println(“Exit from A”);
}
}

class B extends Thread


{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println(“Thread B: j=” + j);
if (j==3)
stop();
}
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println(“Thread C: k=” + k);
if (k==1)
90
try
{
sleep(1000);
}
catch(Exception e) { }
}
System.out.println(“Exit from C”);
}
}
Class ThreadMethods
{
public static void main(String args[])
{
A tA =new A();
B tB =new B();
C tC =new C();
System.out.println(“Start thread A”);
tA.start();
System.out.println(“Start thread B”);
tB.start();
System.out.println(“Start thread C”);
tC.start();
System.out.println(“End of main thread”);
}
}

Thread Exceptions: Note that the call to sleep() method is enclosed in a


try block and followed by a catch block. This is necessary because the
sleep() method throws an exception, which should be caught. If we fail to
catch the exception, program will not complete.
Java run system will throw IllegalTheadStateException whenever we
attempt to invoke a method that a thread cannot handle in the given state.
91
For example a sleeping thread cannot deal with the resume () method
because a sleeping thread cannot receive any instructions. The same is true
with the suspend() method when it is used on a blocked thread.
When we call a thread method that is likely to throw an exception, we have
to supply an appropriate exception handler to catch it. The catch statement
may take one of the following forms:
catch(ThreadDeath e)
{
.... // Killed thread
}
catch(InterruptedException e)
{
.... // Cannot handle it in the current state
}
catch(IllegalArgumentException e)
{
.... // Illegal Method argument
}
catch(Exception e)
{
.... // Any other
}
Thread Priority: In Java each thread is assigned a priority, which affects the
order in which it is scheduled for running. The threads of the same priority
are given equal treatment by the Java scheduler and therefore, they share
the processor on a first-come, first-serve basis.
Java permits us to the priority of a thread using the setPriority() method as
follows:
ThreadName.setPriority(intNumber)
The intNumber is an integer value to which the thread’s priority is set. The
Thread class defines several priority constants:
MIN_PRIORITY = 1
92
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1
to 10. Note that the default setting is NORM_PRIORITY.
Whenever multiple threads are ready for execution, the Java system chooses
the highest priority thread and executes it.
1. It stops running at the end of run().
2. It is made to sleep using sleep().
3. It is told to wait using wait().

/* Example for using thread priority */

class A extends Thread


{
public void run()
{
System.out.println(“A started”);
for(int i=1;i<5;i++)
{
System.out.println(“Thread A: i=” + i);
}
System.out.println(“Exit from A”);
}
}

class B extends Thread


{
public void run()
{
System.out.println(“B started”);
93
for(int j=1;j<5;j++)
{
System.out.println(“Thread B: j=” + j);
}
System.out.println(“Exit from B”);
}
}

class C extends Thread


{
public void run()
{
System.out.println(“C started”);
for(int k=1;k<5;k++)
{
System.out.println(“Thread C: k=” + k);
}
System.out.println(“Exit from C”);
}
}

Class ThreadPriority
{
public static void main(String args[])
Output:
{ Start thread A
Start thread B
A tA =new A(); Start thread C
Bstarted
Thread B: j=1
B tB =new B(); Thread B: j=2
Cstarted
C tC =new C(); Thread C: k=1
Thread C: k=2
tA.setPriority(Thread.MIN_PRIORITY); Thread C: k=3
Thread C: k=4
tB.setPriority(tA.getPriority()+1); Exit from C
End of main thread
tC.setPriority(Thread.MAX_PRIORITY); Thread B: j=3
Thread B: j=494
Exit from B
Astarted
Thread A: i=1
Thread A: i=2
Thread A: i=3
System.out.println(“Start thread A”);
tA.start();
System.out.println(“Start thread B”);
tB.start();
System.out.println(“Start thread C”);
tC.start();
System.out.println(“End of main thread”);
}
}

Synchronization: synchronization generally means sharing data between


multiple or threads. One thread may try to read a record from a file while
another thread is still writing to the same file. Depending on the situation, we
may get strange results. Java enables us to overcome this problem using a
technique known as synchronization.
The keyword synchronized helps to solve such problems by keeping a watch
on such locations. For example, the method that will read information from a
file and the method that will update the same file may be declared as
synchronized. Example:
Synchronized void update()
{
……
}

Deadlock: Resource locking solves the problem of concurrent access (more


than one thread accessing the same resource) but brings a new problem
called deadlock. Deadlock is an infinite locking of two resources one by each
user and each user wanting for the other resource for his next immediate
use.

95
User1 locks the Record A first and after performing the action in it, he waits
for Record B for the next immediate part of his transaction complete.
Similarly, User 2 locks Record B first and after performing the action in it, he
waits for Record A for the next immediate part of his transaction to complete.
The main assumption made here is that the next immediate part of his
transaction of each user will require the current record as well as the record
locked by the other user. Under this situation, each user will be holding his
current record and waiting for his next immediate required record infinitely.
Implementing the ‘Runnnable’ interface:
The Runnable interface declares the run() method that is required for
implementing threads in our programs.
1. Declare the class as implementing the Runnable interface.
2. Implementing the run() method.
3. Create a thread by defining an object that is instantiated from this
runnable class as the target of the thread.
4. Call the thread’s start() method to run the thread.
import java.lang.Thread;
class X implements Runnable // Step 1
{
public void run() // Step 2
{
for(int i=1;i<=10;i++)
{
System.out.println(“Thread X: i=” + i);
}
System.out.println(“Exit from X”);
}
}
Class RunnableTest
96
{
public static void main(String args[])
{
X r=new X();
Thread threadX=new Thread(r); // Step 3
threadX.start(); // Step 4
System.out.println(“End of the main thread”);
}
}
Output:
End of main Thread ThreadX : 6
ThreadX : 1 ThreadX : 7
ThreadX : 2 ThreadX : 8
ThreadX : 3 ThreadX : 9
ThreadX : 4 ThreadX : 10
ThreadX : 5 End of ThreadX

12. MANAGING ERRORS AND EXCEPTIONS


An error may produce an incorrect output or may terminate the execution of
the program abnormally or even may cause the system to crash. Errors may
be classified into two categories:
● Compile-time errors ● Run-time errors.

97
Compile-time errors: All syntax errors will be detected and therefore these
errors are known as compile-time errors. Whenever the compiler displays an
error, it will not create the .class file. It is therefore necessary that we fix all
the errors before we can successfully compile and run the program. Java
compiler does a nice job of telling us where the errors are in the program.
Most of the compile-time errors are due to typing mistakes.
● Missing semicolons. ● Misspelling of identifiers and
● Missing brackets in classes keywords.
and methods. ● Use of = in the place of = =
operator.
Run-Time Errors:
A program may compile successful creating the .class file but may not run
properly. Such programs may produce wrong results due to wrong logic or
may terminate due to errors such as stack overflow. Most of the run-time
errors are.
● Dividing an integer by zero
● Accessing an element that is out of the bounds of an array.
● Try to store a value into an array of an incompatible class or type.
Exceptions: An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions. When an error occurs
within a method, the method creates an object called an exception object,
contains information about the error, including its type and the state of the
program. Creating an exception object and handing it to the runtime system
is called throwing an exception.

98
If the exception object is not caught and handled properly, the interpreter will
display an error message and will terminate the program. If we want the
program to continue with execution of the remaining code, then we should
try to catch the exception
object thrown by the error condition
and then display an appropriate
message for taking corrective
actions. This is known as exception
handling.

99
Error handling code that performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
The error handling code basically consists of two segments,
● To detect errors and to throw exceptions
● To catch exceptions and to take appropriate actions.
Syntax of Exception Handling Code: The basic concepts of exception
handling are throwing an exception and catching it.
try
{
Statements; // generate an exception
}
catch (Exception-Type e)
{
Statement; // process the exception
}
Java uses a keyword try to preface a block of code that is likely to cause an
error condition and throw an exception. A catch block defined by the keyword
catch catches the exception thrown by thee try block and handles it
appropriately. The catch block is added immediately after the try block.
Class Error1
{
public static void main(String args[])
{
int a=10;
int b =5;
int c=5;
int x,y;
try
{
100
X=a / (b-c);
}
catch (ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
y= a/(b+c);
System.out.println(“Y=” + y);
}
}

Output:
Division by zero
y=1

Multiple catch statements: when an exception in a try block is generated,


the java treats the multiple catch statements like cases in a switch

101
statement. The first statement whose parameter matches with the exception
object will be executed and the remaining statements will skipped.
try
{
Statement;
}
catch (Exception-Type-1 e)
{
Statement;
}

catch (Exception-Type-2 e)
{
Statement;
}
....
catch (Exception-Type-n e)
{
Statement;
}
. . . .
. . .
❖ Note that Java does not require any processing of the exception at all.
We can simply have a catch statement with an empty block to avoid program
abortion.
Catch (Exception e);
The catch statement simply ends with a semicolon, which does noting.

Class Error2
{
public static void main(String args[])
102
{
int a[]={5,10};
int b =5;
try
{
int x=a[2] / b-a[1];
}
catch (ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
catch (ArrayIndexOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch (ArrayStoreException e)
{
System.out.println(“Wrong data type”);
}

int y= a[1]/a[0];
System.out.println(“Y=” + y);
}
}
Output:
Array index error
y=2

Using Finally Statement:


Java supports another statement known as finally statement that can be
used to handle an exception that is not caught by any of the previous catch
statements. Finally block can be used to handle any exception generated
103
within a try block. It may be added immediately after the try block or after
the last catch block as follows.
try try
{ {
.... ....
} }
catch() catch()
{ {
..... .....
}
} finally
{
.....
}
When a finally block is defined, this is guaranteed to executed regardless of
whether or not in exception is thrown. As a result, we can use it to perform
certain house-keeping operations as closing files and releasing system
resources.

Throwing our own exceptions: We can throw our own exceptions using
the keyword throw as follows: throw new
throwable_subclass;

Example: throw new ArithmeticException();

import java.io.*;
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{

104
Super(message);
}
}
Class TestMyException
{
public static void main(String args[])throws Exception
{
InputStreamReader instr= new InputStreamReader(System.in);
BufferedReader br=new Buffered(instr);
int m;
System.out.println(:Enter marks:”);
try
{
m=Integer.parseInt(br.readLine());
If(m<0 || m>100)
{
Throw new MyException(“Invalid Marks!”);
}
}
Catch(MyException e)
{
System.out.println(“Caught my exception”);
System.out.println(e.getMessage());
}
}
}
Output:
Enter Marks:
105
Invalid Marks!

105
106
UNIT: V
13. APPLET PROGRAMMING

Applets are small java programs that are primarily used in Internet
computing. They can be transported over the internet from one computer to
another and run using the Applet Viewer or any web browser that support
Java. Applets can perform arithmetic operations, display graphics, play
sounds, accept user input, create animation and play interactive games.
Applets can develop in two ways.
✓ We can write our own applets and embed them into web pages
✓ We can download an applet from a remote computer and then embed it
into a web page.
An applet developed locally and stored in a local system is known as a
local applet. When a web page is trying to find a local applet, it simply
searches the directories in the local system and loads the 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 onto our system though
internet and run it.
In order to locate and load a remote applet, we must know the applet’s
address on the web. This address is known a Uniform Resource Locator
(URL) and must be specified in the applet’s HTML document as the value of
the CODEBASE attribute.
CODEBASE = http://www.netserver.com/applets

Difference between Applets and Applications:

107
Applets are not full-featured application programs. They are usually written to
accomplish a small task.
Limitations and restrictions are:
● Applets do not use the main() methods for initiating the execution of
the code.
● Unlike stand-alone applications, applets cannot be run independently.
They are run from inside a web page using a special feature known as HTML
tag.
● Applets cannot read from or write to the files in the local computer.
● Applets cannot communicate with other server on the network.
● Applets cannot run any program from the local computer.
● Applets are restricted from using libraries from other languages such as
C or C++.
Advantages of applets:
1. When we need something dynamic to be included in the display of a
web page.
2. When we require some flash outputs. For example, applets that
produce sounds, animations or some special effects would be useful when
display certain pages.
3. When we want to create a program and make it available on the
internet foe us by other on their computers.
Steps for developing and testing applets:
1. Building an applet code (.java file)
2. Creating an executable applet(.class file)
3. Designing a web page using HTML tags.
4. Preparing <APPLET> tag.
5. Incorporating <APPLET> tag into the web page.
6. Creating HTML file.
7. Testing the applet code.
Building an applet code (.java file): It is essential that our applet code
uses the services of two classes, namely Applet and Graphics from the Java
class library. The Applet class which is contained in the java.applet package
108
provides life and behavior of the applet through its methods such as init(),
start() and paint(). Unlike the applications, where Java calls the main()
method directly to initiate the execution of the program, when an applet is
loaded, Java automatically calls a series of Applet class methods for starting
running and stopping the applet code. The Applet class therefore maintains
the lifecycle of an applet.
The paint() method of the applet class, when it is called, actually displays
the result of the applet code on the screen. The output may be text, graphics
or sound. The paint() method, which requires a Graphics objects as an
argument,
public void paint(Graphics g)
This requires that the applet code imports the java.awt package that contains
the Graphics class. All output operations of an applet are performed using the
methods defined in the Graphics class.
import java.awt.*;
import java.applet.*;
Public class appletclassname extends Applet
{
....
Public void paint(Graphs g)
{
... // Applet operations code
}
...
...
}

The appletclassname is the main class for the applet. When the applet is
loaded, Java creates an instance of this class, and then a series of Applet
class methods are called on that instance to execute the code.
Import java.awt.*;
Import java.applet.*;
109
Public class HelloJava extends Applet
{
Public void paint(Graphs g)
{
g.drawSring(“Hello Java”, 10,100);
}
}
4Q) Explain about “Applet Life Cycle”
Every Java applet inherits a set of default behaviors from the Applet class.
● Born on initialization state: Applet enters the initialization state
when it is first loaded. This is achieved by calling the init() method of applet
Class. The applet is born.
▪ Create objects needed by the applet.
▪ Set up initial values.
▪ Load images or fonts.
▪ Set up colors.
The initialization occurs only once in the applet’s life cycle. To provide any of
the behaviors, we must override the init() method.
Public void init()
{
....
}
● Running state: Applet enters the running state when the system calls
the start() method of Applet class. This occurs automatically after the applet
is initialized. Starting can also occur if the applet is already in stopped state.
Public void start()
{
....
}
● Idle or stopped state: An applet becomes idle when it is stopped
from running. Stopping occurs automatically when we leave the page
containing the currently running applet. We can do so by calling the stop()
110
method explicitly. If we use a thread to run the applet, then we must use
stop() method to terminate the thread.
Public void stop()
{
....
}
● Dead or destroyed state: An applet is said to be dead when it is
removed from memory. This occurs automatically by invoking the destroy ()
method when we quit the browser. Like initialization, destroying stage occurs
only once in the applet’s life cycle. If the applet has created any resources,
like threads, we may override the destroy () method to clean up these
resources.
Public void destroy()
{
....
}
● 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. Almost every applet will have a
paint() method. Like other methods in the life cycle, the default version of
paint() method does absolutely nothing.
Public void paint (Graphics g)
{
....
}

Creating an Executable Applet: Executable applet is nothing but the .class


file of the applet. Compiling an applet is exactly the same as compiling an
application. Therefore, we can use the java compiler to compile the applet.
Steps for compiling the applet:
1. Move to the directory containing the source code and type the following
command:
111
Javac filename
2. The compiled output file called .class file is placed in the same directory
as the source.
3. If any error message is received, then we must check for errors, correct
them and compile the applet again.

112
14. PACKAGES
Package: Grouping a variety of classes and / or interfaces together is known
as package. The grouping is usually done according to functionality.
Advantages:
1. The classes contained in the packages of other programs can be easily
reused.
2. In packages, classes can be unique compared with classes in other
packages.
3. Packages provide a way to hide classes, thus preventing other
packages from accessing classes.
4. Packages also provide a way for separating “design” from coding.
First we can design classes and decide their relationships and then we can
implement the java code needed for the methods.
Java packages are classified into two types. The first category is known as
Java API (Application Programming Interface) Packages and the
second is known as user defined packages.
Java API Packages: Java API provides a large number of classes grouped
into different packages according to functionality. The packages are
organized in a hierarchical structure.
Package Contents
name
Language support classes.
java.lang They include classes for primitive types, strings, math,
functions, threads and exception
Language utility classes such as vectors, hash tables, random
java.util
numbers, date etc.
Input/output support classes. They provide facilities for the input
java.io
and output of data.
java.awt
Set of classes for implementing graphical user interface. They
(abstract
include classes for windows, buttons, lists, menus and so on.
Window tool)

113
Classes for networking. They include classes for communicating
java.net
with local computer as well as internet servers.
java.applet Classes for creating and implementing applets.

Using System packages: Accessing the classes stored in a package by use


the fully qualified class name that we want to use. This is done by using the
package name containing the class and then appending the class name to it
using the dot operator. For example, if we want to refer to the class Color in
the awt package.
import java.awt.Color;
Notice that awt is a package within the package java and the hierarchy is
represented by separating the level with dots.
Naming convention: Packages can be named using the standard java
naming rules. By convention, packages begin with lowercase letters. This
makes it easy for users to distinguish packages names from class names.
java.lang.Math.sqrt(x);
Steps for creating packages:
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where main
source files are stored.
D:\MPCS101> md aditya
D:\MPCS101> cd aditya
D:\MPCS101\aditya>edit
3. Declare the package at the beginning of a file using the following
syntax
package packagename;
4. Define the class that is to be put in the package and declare it public.
Remember that case is significant and therefore the subdirectory
name must the package name exactly.
package aditya
public class Mpcs

114
{
public int add(int x,int y)
{
return(x+y);
}
}
5. Save the source file by class name Mpcs.java
6. Switch to the subdirectory created earlier and compile each source file.
When completed, the package would contain .class files of all the source
files.
● Remember that the .class file must be located in a directory that has
the same name as the package
● Java also supports the concept of package hierarchy. This is done by
specifying multiple names in a package statement, separated by dots.
Example:
package firstPackage.secondPackage;
Accessing a Package: The import statement can be used to search a list of
packages for a particular class. The general form of import statement for
searching a class is as following:
import package1[.package2][.package3].classname;
Here package1 is the name of the top level package; package2 is the name of
the package that is inside the package1, and so on.
import aditya.Mpcs;
class Test
{
public static void main(String args[])
{
Mpcs c1 = new Mpcs();
int s=c1.add(5,6);
System.out.println(“Sum=”+s);
}
}
115
116
Adding a class to a package: The package aditya contains one public class
by name Mpcs. suppose we want to add another class Mecs to this package.
1. Define the class and make it public.
2. Place the package statement before the class definition as follows:
package aditya;
public class Mecs
{
public int sub(int x,int y)
{
return(x-y);
}
}
3. Store this as Mecs.java file under the directory aditya.
4. Compile Mecs.java file. This will create a Mecs.class file and place it
in the directory aditya.
✓ Now the package aditya will contain both the classes Mpcs and Mecs.
Statement like
import aditya.*
Hiding classes:
package1 p1;
When we import package using asterisk (*), all
public class X // public
public classes are imported. However, we may {
body of X;
prefer to “not import” certain classes. This is, }
class Y // hidden
we may like to be hide these classes from {
body of Y
accessing from outside of the package.
}
Static import:
Static import is another feature eliminates the need of qualifying a static
member with the class name. The static import declaration is similar to that
of import. We can use the import statement to import class from packages
and use them without qualifying the package. Similarly, we can use the static
import statement to import static members form classes and use them
without qualifying the class name.

117
import static package-name.subpackage-name.class-
name.staticmember–name;
import static java.lang.Math.*;
public class Mathop
{
public void circle(double r)
{
double area=PI*r*r*;
System.out.println(“Area=”+area);
}
public static void main(String args[])
{
Mathop obj=new Mathop();
obj.circle(2,3);
}
}

118
15. MANAGING INPUT / OUTPUT FILES IN JAVA
A File is a collection of related records placed in a particular area on the disk.
A record is composed of several fields and a field is a group of characters.
Characters in java are Unicode characters composed of two bytes, each
containing eight binary digits, 1 or 0.
Storing and managing data using files
is known as file processing, which
includes tasks such as creating files,
updating files and manipulating of
data. Java supports many powerful
features for managing input and
output of data using files. Reading and
writing of data in a file can be done at
the level of bytes or characters or
fields depending on the requirements
of a particular application. Java also provides capabilities to read and write
class objects directly. Note that a record may be represented as a class
object in java. The process of reading and writing objects is called object
serialization.

Concept of Streams:

119
In file processing, input refers to the
flow of data into a program and output
means the flow of data out of a
program. Input to a program may
come from the keyboard, the mouse,
the memory, the disk, a network, or
another program. Similarly, output from a program may go to the screen, the
printer, the memory, the disk, a network, or another program. Although
these devices look very different at the hardware level, they share certain
common characteristics such as unidirectional movement of the data treating
data as a sequence of bytes or characters and support to the sequential
access to the data.
Java uses the concept of streams to represent the ordered sequence of data.
A stream presents a uniform, easy-to-use, object-oriented interface between
the program and the input / output devices.
A stream in java is a path along which data flows
(like a river or a pipe along which water flows).
Both the sources and the destination may be
physical devices or programs or other streams in
the same program.

120
The concept of sending data from one
stream to another has made streams in
java a powerful tool for file processing.
We can build a complex file processing
sequence using a series of simple
stream operations. This feature can be
used to filter data along the pipeline of streams so that we obtain data in a
desired format. For example, we can use one stream to get raw data in
binary format and then use another stream in series to convert it to integers.
Java streams are classified into two basic types, namely, input stream and
output stream. An input stream extracts (reads) data from the source (file)
and sends it to the program, Similarly, an output stream takes data from the
program and sends (writes) it to the destination (file) the program concepts
and open an output stream on the data source and then reads the data
serially. Similarly, the program connects and opens an output stream to the
destination place of data and Writes data out serially.

Stream Classes
The java.io package contains a large number of streams classes that provide
capabilities for processing all types of data.
These classes may be categorized into two
groups based on the data type on which they
operate.
1. Byte stream classes that provide
support for handling I/O operations on bytes.
2. Character stream classes that provide
support for managing I/O operations on
characters.
These two groups may further be classified based on their purpose. Byte
stream and character stream classes contain specialized classes to deal with
input and output operations independently on various types of devices. We
can also cross-group the streams based on the type of source or destination
121
they read from or write to. The source (or destination) may be memory or a
file.

BYTE STREAM CLASSES


Byte stream classes have been designed to provide functional features for
creating and manipulating streams and files for reading and writing bytes.
Since the streams are unidirectional, they can transmit bytes in only one
direction and therefore, java provides two kinds of byte stream classes: input
stream classes and output steam classes.
Input Stream Classes
Input steam classes that are used to read
8–byte include a super class known as
INPUT STREAM and a number of sub classes
for supporting variables input-related
functions.
The super class input stream is an abstract
class and therefore we cannot create
instances of this class. Rather, we must use
the subclasses that inherit from the class.
The input Stream class defines methods for
performing input functions such as
● Reading bytes
● Closing streams
● Marking positions in streams
● Skipping ahead in a stream
● Finding the number of bytes in a stream
INPUT STREAM METHODS
S.No Method Description
1. read() Read a byte from the input stream
2. read(byte b[]) Read an array of bytes into b
3. read(byte b[], int n, int m) Read m bytes into b starting from

122
nth byte.
Gives number of bytes available in
4. available()
the input.
Skip over n bytes from the input
5. skip()
stream
Goes back to the beginning of the
6. reset()
stream.
7. close() Goes the input stream
Output Stream Classes
Out stream classes are derived from the base class OUTPUT STREAM, like
output stream, the output stream is an abstract class and therefore we
cannot instantiate it. The several subclasses of the output stream can be
used for performing the output operations.
The output stream includes methods that are designed to perform the
following tasks.
● Writing bytes
● Closing streams
● Flushing streams
OUTPUTSTREAM METHODS
S.No Method Description
1. write() Write a byte to the output stream
Write all bytes in the array b to the
2. write(byte b[])
output stream.
Write m bytes from b starting from nth
3. write(byte b[], int n, int m)
byte.
Goes back to the beginning of the
4. reset()
stream.
5. close() Goes the output stream
6. flush() Flushes the output stream
CHARACTER STREAM CLASSES

123
Character stream classes were not a part of the language when it was
released in 1995.They were added later when the version 1.1 announced.
Character streams can be used to read and write 16-bit Unicode character.
Like byte streams, there are two kinds of character stream classes, namely
reader stream classes and writer stream classes.
Reader Stream classes
Reader stream classes are designed to
read character from files. Reader classes
are the base class for all other classes in
the group as shown in the figure. These
classes are functionally very similar to
the input stream classes, except input
streams use bytes as their fundamental
unit of information, while reader
streams use characters.
The reader class contains methods that are identical to those available in
Input stream class, except reader is designed to handle characters
.Therefore, reader classes can perform all the functions implemented by the
input stream classes.
Writer stream classes
Like output stream classes, the writer stream classes are designed to perform
all output operations on files. Only differences
is that while output stream classes are
designed to write bytes the writer stream
classes are designed to write characters.
The writer class is an abstract class which
acts as a base class for all the writer stream
classes as shown in the figure. This base class
provides support for all output operations by
defining methods that are identical to those in
Output steam class
USING STREAMS
124
We have seen briefly various types of input and output streams classes used
for handling both the 16-bit characters and 8-bit bytes. Although all the
classes are known as i/o classes not all of them are used for reading and
writing operations only. Some perform operations such as buffering, filtering,
data conversion, counting and concatenation while carrying out I/O tasks.
As pointed out earlier, both the character stream group and the byte stream
group contain parallel pairs of classes that perform the same kind of
operation but for the different data type. Table 16.3.gives a list of tasks and
the character streams and byte streams that area available to implement
them.

READING / WRITING CHARACTERS:


Sub classes of Reader and Writer
implement streams that can handle
characters. The two subclasses used for
handling characters in files are FileReader
and FileWriter.
import java.io.*
class CopyChar
{
public static void main(String args[])
{
File inFile = new File(“input.dat”);
File outFile = new File(“output.dat”);
FileReader ins = null;
FileWriter outs = null;
try
{
ins=new FileReader(inFile);
outs=new FileWriter(outFile);
int ch;
while((ch=ins.read())!=-1)
125
{
outs.write(ch);
}
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close();
outs.close();
}
catch(IOException e) { }
}
}
}

ADIKAVI NANNAYA UNIVERSITY


III SEMESTER MODEL QUESTION PAPER UNDER CBCS PATTERN
PART –II COMPUTER SCIENCE
Object Oriented Programming using JAVA
SECTION – A
I. ANSWER ANY FIVE QUESTIONS 5 X 5
= 25 M
1.

2.

3.
126
4.

5.

6.

7.

8.

SECTION – B
I. ANSWER ALL QUESTIONS 5 X
10 = 50 M
9. a)
OR
b)
10. a)
OR
b)
11. a)
OR
b)
12. a)
OR
b)
13. a)
OR
b)

127

You might also like