Javamaterial

Download as pdf or txt
Download as pdf or txt
You are on page 1of 142

SRI KRISHNA ADITHYA

COLLEGE OF ARTS AND SCIENCE


(Affiliated to Bharathiar University)
Kovaipudur, Coimbatore-42

DEPARTMENT OF COMPUTER SCIENCE

COURSE MATERIAL UNIT WISE

SEMESTER III

CORE III- JAVA PROGRAMMING


UNIT – I

Fundamentals of Object Oriented Programming


Object-Oriented Paradigm
Basic Concepts of Object-Oriented Programming
Benefits of Object-Oriented Programming
Application of Object-Oriented Programming
Java Evolution:
History
Features
How Java differs from C and C++
Java and Internet
Java and www
Web Browsers
Overview of Java: simple Java program
Structure
Java Tokens
Statements
Java Virtual Machine

1.1 What is Programming Language


 A programming language is a formal language comprising a set of instructions that
produce various kinds of output. Programming languages are used in computer
programming to
implement algorithms.
 The portion of the language that a
computer can understand is called a
“binary.” Translating programming
language into binary is known as
“compiling.”
 Each language, from C Language to
Python, has its own distinct features,
though many times there are commonalities between programming languages.
 These languages allow computers to quickly and efficiently process large and complex
swaths of information.
 For example, if a person is given a list of randomized numbers ranging from one to ten
thousand and is asked to place them in ascending order, chances are that it will take a
sizable amount of time and include some errors.

1.2 Fundamentals of Object Oriented Programming


 Object Oriented Programming used to develop programs revolving around the real
world entities.
 In OOPs programming model, programs are developed around data rather than
actions and logics.
 In OOPs, every real life object has properties and behavior which is achieved through
the class and object creation.
 They contains properties (variables of some type) and behavior (methods).
 Most popular programming languages like Java, C++, C#, Ruby, etc. follow an object-
oriented programming paradigm.
 As JAVA being the most sought-after skill, we will talk about object-oriented
programming concepts in Java.

1.3 Object Oriented Programming Paradigm

 Object-oriented programming (OOP) is a programming paradigm based


upon objects (having both data and methods) that
aims to incorporate the advantages of modularity and
reusability. Objects, which are usually instances of
classes, are used to interact with one another to
design applications and computer programs.

 It utilizes several techniques from previously


established paradigms, including inheritance,
modularity, polymorphism, and encapsulation.

 Today, many popular programming languages (such


as Ada, C++, Delphi, Java, Lisp, SmallTalk, Perl, PHP,
Python, Ruby, VB.Net, Visual FoxPro, and Visual Prolog)
support OOP.

1.3.1Some of the striking features of object-oriented programming are


 Emphasis is on data rather than procedure.

 Programs are divided into what are known as objects.

 Data structures are designed such that they characterize the objects.

 Data is hidden and cannot be accessed by external functions.

 Objects may communicate with each other through functions.

 New data and functions can be easily added whenever necessary.

 Follows bottom-up approach in program design.

1.4 Basic Concepts of Object-Oriented Programming

 Object oriented programming is a type of programming which uses objects and


classes its functioning.
 The object oriented programming is based on real world entities like inheritance,
polymorphism, data hiding, etc.
 It aims at binding together data and function work on these data sets into a single
entity to restrict their usage.

Some basic concepts of object oriented programming are −


 CLASS

 OBJECTS

 ENCAPSULATION

 POLYMORPHISM

 INHERITANCE

 ABSTRACTION

Class
 A class is a data-type that has its own members i.e. data members and member
functions. It is the blueprint for an object in object oriented programming language.
 It is the basic building block of object oriented programming in c++. The members of a
class are accessed in programming language by creating an instance of the class.

Some important properties of class are −


 Class is a user-defined data-type.
 A class contains members like data members and member functions.
 Data members are variables of the class.
 Member functions are the methods that are used to manipulate data members.
 Data members define the properties of the class whereas the member functions define
the behaviour of the class.
A class can have multiple objects which have properties and behaviour that in common for all
of them.
Syntax
class class_name {
data_tpye data_name;
return_type method_name(parameters);
}

Object

 An object is an instance of a class. It is an entity with characteristics and


behaviour that are used in the object oriented programming.

 An object is the entity that is created to allocate memory. A class when


defined does not have memory chunk itself which will be allocated as soon as objects
are created.
Syntax
class_name object_name;

Encapsulation

 In object oriented programming, encapsulation is the concept of wrapping


together of data and information in a single unit.

 A formale defination of encapsulation would be: encapsulation is binding


togather the data and related function that can manipulate the data.

Let’s understand the topic with an easy real life example,

 In our colleges, we have departments for each course like computer science,
information technology, Computer Application, etc. each of these departments have
their own students and subjects that are kept track of and being taught.
 let's think of each department as a class that encapsulates the data about students of
that department and the subjects that are to be taught.
 Also a department has some fixed rules and guidelines that are to be followed by the
students that course like timings, methods used while learning, etc. this is
encapsulation in real life, there are data and there are ways to manipulate data.

Polymorphism
 The name defines polymorphism is multiple forms. which means polymorphism is the
ability of object oriented programming to do some work using multiple forms. The
behaviour of the method is dependent on the type or the situation in which the method
is called.
 Let‟s take a real life example, A person can have more than one behaviour depending
upon the situation. like a woman a mother, manager and a daughter And this define
her behaviour. This is from where the concept of polymorphism came from.
 In C++ programming language, polymorphism is achieved using two ways. They are
operator overloading and function overloading.

Operator overloading

 In operator overloading and operator can have multiple behaviour in different


instances of usage.

Function overloading
 Functions with the same name that can do multiple types based on some condition.

Inheritance

 It is the capability of a class to inherit or derive properties or characteristics other


class.
 It is very important and object oriented program as it allows reusability i.e. using a
method defined in another class by using inheritance.
 The class that derives properties from other class is known as child class or subclass
and the class from which the properties are inherited is base class or parent class.

C ++ programming language supports the following types of inheritance

 single inheritance

 multiple inheritance

 multi level inheritance

 Hierarchical inheritance

 hybrid inheritance

Abstraction

 Data abstraction or Data Hiding is the concept of hiding data and showing only
relevant data to the final user. It is also an important part object oriented programing.
 let's take real life example to understand concept better, when we ride a bike we only
know that pressing the brake will stop the bike and rotating the throttle will accelerate
but you don't know how it works and it is also not think we should know that's why this
is done from the same as a concept data abstraction.
 In C++ programming language write two ways using which we can accomplish data
abstraction −

 using class

 using header file

1.5 Benefits of OOP

There are several benefits of OOP to both program designer and the user. Object orientation
solves many problems which are associated with the development and quality of software
products. New technology gives greater programmer productivity, good quality of software
and low maintanance cost. The main advantages are:
 We can eliminate redundant code and extend the use of existing classes.

 Programs can be build from the standard working modules that


communicate with one another and to start writing the code from scratch. This shows
to saving of development time and higher productivity.

 The data hiding rules helps the programmer to make secure programs that
cannot be invaded by code in other parts of the program.

 It has multiple objects to coexist without any interference.

 It has map objects in the problem domain to those objects in the program.

 partition of work is easy in a project based on objects.

 The data-centered design approach capture more details of a model in an


implementable form.

 Object oriented systems can be easily upgraded from small to large


systems.

 It is possible to easily manage software complexity.

1.6 Applications of OOP

If there is complexity in software development, objecet-oriented programming is the best


paradigm to solve the problem. The following areas make the use of OOP:

1. Image Processing
2. Pattern Recognition
3. Computer Assisted Concurrent Engineering
4. Computer Aided Design and Manufacturing
5. Computer Aided Teaching
6. Intelligent Systems
7. Database Management Systems
8. Web based Applications
9. Distributed Computing and Applications
10. Component based Applications
11. Business Process Reengineering
12. Enterprise resource planning
13. Data security and management
14. Mobile Computing
15. Data Warehouse and Data Mining
16. Parallel Computing

 Object concept helps to translate our thoughts to a program. It provides a way of


solving a problem in the same way as a human being perceives a real world problem
and finds out the solution.
 It is possible to construct large reusable components using object-oriented techniques.
Development of reusable components is rapidly growing in commercial software
industries.

1.7 Java Evolution

Java History:

 Java is a programming language originally developed by


James Gosling at Sun Microsystems (which has since
merged into Oracle Corporation) and released in 1995 as
a core component of Sun Microsystems' Java platform.

 The language derives much of its syntax from C and C++,


but it has fewer low-level facilities than either of them.
Java applications are typically compiled to bytecode (class
file) that can run on any Java virtual machine (JVM)
regardless of computer architecture.

 Java is a general-purpose, concurrent, class-based,


object-oriented language that is specifically designed to
have as few implementation dependencies as possible.

 It is intended to let application developers "write once, run anywhere" (WORA),


meaning that code that runs on one platform does not need to be recompiled to run on
another.

 Java is as of 2012 one of the most popular programming languages in use, particularly
for client-server web applications, with a reported 10 million users.

 The original and reference implementation Java compilers, virtual machines, and class
libraries were developed by Sun from 1991 and first released in 1995.
 As of May 2007, in compliance with the specifications of the Java Community
Process, Sun relicensed most of its Java technologies under the GNU General Public
License.

 Others have also developed alternative implementations of these Sun technologies,


such as the GNU Compiler for Java and GNU Classpath.

Milestones of Java
1.5 Java features:
The inventors of java wanted to design a language which could offer solutions to some
of the problems encountered in modern programming they wanted the language to be not
only reliable, portable and distributed but also simple, compact and interactive
Sun micro System officially describes java with the following attributes:
 Compiled and interpreted
 Platform _independent and portable
 Object-oriented
 Robust and secure
 Distributed
 Familiar, simple and interactive
 High performance
 Dynamic and Extensible
 Ease of development
 Scalability of performance
 Monitoring and manageability
 desktop client
 Core XML support
 Supplementary character support
 JDBC Rowset
These features have made java the first application language of the World Wide Web java
will also become the premier language for general purpose standalone application
Simple and powerful
 Object oriented to java
 You can learn to program in java quickly once the basic concepts of object-oriented
programming are understood.
 You once need to understand a few concepts in order to write productive and
satisfying program.
 This style of simplicity has often produced inefficient and non-expressive “scripting
language”.
 Java is not scripting language.
Safe
 Java is protocol, it provide security and safe.
 Even your word processor documents can carry viruses.
 One of the key design principles of java is safety and security.
Object-oriented
 Class and object are used in java.
 Most other object-oriented systems have chosen to have rigid, hard-to –manage
object hierarchies.
 It is not a direct derivative of any other programming language, nor is‟t in any way
upward compatible with one.
Robust
 It is very strong it is a case sensitive language.
 You might think that robustness is a luxury in these times of adventure on the internet.
 Java is a very strict language when it comes to type and declarations, most common
errors can be caught time.
Interactive
 Requirements real word event It is very interactive to use.
 Java was designed to meet the real-word requirement of creating interactive network
program.
 Most systems have a hard time dealing with either
 One, let alone interactivity and networking at once.
Architecture neutral
 Portable language.
 Run anywhere at any time.
 It‟s work on “macintosh, pc, unix” and whatever the platforms can offer.
Interpreted and high performance
 Java is the byte code format it‟s carefully design.
 All platforms are independent.
 It‟s easy to translate directly into native machine code for very high performance.
Easy to learn
 The language features feel like the natural way to do things and encourage good
programming style.
 Java is more complicated then a scripting language.
 It‟s an object-oriented program.
Java is Compiled and Interpreted

Java compiler

Architecture Neutral & Portable


 Java Compiler - Java source code (file with extension .java) to bytecode (file with
extension .class)
 Bytecode - an intermediate form, closer to machine representation
 A interpreter (virtual machine) on any target platform interprets the bytecode.
 Porting the java system to any new platform involves writing an interpreter.
 The interpreter will figure out what the equivalent machine dependent code to run
 Core Classes

Total Platform Independence


Rich Class Environment
 Language
 Utilities
 Input/Output
 Low-Level Networking
 Abstract Graphical User Interface
 Internet Classes
 TCP/IP Networking
 WWW and HTML
 Distributed Programs

1.6 How JAVA differs from C and C++


Java and C

Java is not lot like C but the major difference between Java and C is that Java is an object-
oriented language and has a mechanism to define classes and objects. In an effort to build a
simple and safe language, the Java team did not include some of the C features in Java.

1. Java does not include the C unique statement keywords size of and typedef.
2. Java does not contain the data type struct and union.
3. Java does not define the type modifiers keywords auto, extern, register, signed, and
unsigned.
4. Java does not support an explicit pointer type.
5. Java does not have a preprocessor and therefore we cannot use # define, # include,
and # ifdef statements.
6. Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
7. Java adds new operators such as instanceof and >>>.
8. Java adds labelled break and continue statements.
9. Java adds many features required for object-oriented programming.

C Programming Java Programming

It does include the unique statement It does not include the C unique statement
keywords sizeof, and typedef. keywords sizeof, and typedef.

It contain the data type struct and union. It does not contain the data type struct and union.
C Programming Java Programming

It define the type modifiers keywords It does not define the type modifiers keywords
auto, extern, register, signed, and auto, extern, register, signed, and unsigned.
unsigned.

It supports an explicit pointer type. It does not support an explicit pointer type.

It has a preprocessor and therefore we It does not have a preprocessor and therefore we
can use # define, # include, and # ifdef cannot use # define, # include, and # ifdef
statements. statements.

It requires that the functions with no It requires that the functions with no arguments
arguments, with the void keyword must be declared with empty parenthesis, not
with the void keyword

C has no operators such as instanceof Java adds new operators such as instanceof and
and >>>. >>>.

C adds have a break and continue Java adds labeled break and continue statements.
statements.

C has no object-oriented programming Java adds many features required for object-
features. oriented programming.

Java and C++

Java is a true object-oriented language while C++ is basically C with object-oriented


extension. That is what exactly the increment operator ++ indicates. C++ has maintained
backward compatibility with C. Is is, therefore, possible to write an old style C program and
run it successfully under C++. Java appears to be similar to C++ when we consider only the
“extensions” part of C++. However, some object -oriented features of C++ make the C++
code extremely difficult to follow and maintain.

Listed below are some major C++ features that were intentionally omitted from Java or
significantly modified.

1. Java does not support operator overloading.


2. Java does not have template classes as in C++.
3. Java does not support multiple inheritances of classes. This is accomplished using a
new feature called “Interface”.
4. Java does not support global variables. Every variable and method is declared within
classes and forms part of that class.
5. Java does not use pointers.
6. Java has replaced the destructor function with a finalize() function.
7. There are no header files in Java.

C++ Programming Java Programming

It support operator overloading. It does not support operator overloading.

It support has template classes. It does not have template classes as in C++.

It supports multiple inheritances It does not support multiple inheritances of classes.


of classes. This is accomplished using a new feature called
“Interface”.

It supports global variables. It does not support global variables. Every variable and
method is declared within classes and forms part of that
class.

It supports pointers. It does not use pointers.

It does not support destructor It has replaced the destructor function with a finalize()
function with a finalize() function. function.

There are header files in Java. There are no header files in Java.

Differences among C, C++ and Java Programming Languages: C vs C++ vs Java


 The purpose of learning a programming language is to become a better programmer
i.e. to become more effective at designing and implementing new systems and at
maintaining old ones.
 C, C++, and Java are the most popular programming languages used today at a broad
level.
 They have a pretty similar syntax for basic concepts. Most of the basic constructs like
if statements, loops, function syntax, switch case statements and concepts like
recursion are still valid.
 Many other concepts like the syntax for comments, and the idea of static class
variables, also held in both Java and C++.

Java uses the syntax of C and structure of C++ language.

Aspects C C++ Java


The developed year 1972 1979 1991
Developed By Dennis Ritchie Bjarne Stroustrup James Gosling
C(Syntax) & C++
Successor of BCPL C
(Structure)
Paradigms Procedural Object Oriented Object Oriented
Platform Dependency Dependent Dependent Independent
50 defined (goto, const
Keywords 32 63
unusable)
Datatypes: union,
Supported Supported Not Supported
structure
Pre-processor Supported (#include, Supported (#include,
Not Supported
directives #define) #define)
Header files Supported Supported Use Packages (import)
Multiple Inheritance not
Inheritance No Inheritance Supported
Supported
Operator Overloading not
Overloading No Overloading Supported
Supported
Pointers Supported Supported No Pointers
Code Translation Compiled Compiled Interpreted
Storage Allocation Uses malloc, calloc Uses new, delete uses garbage collector
Multithreading and
Not Supported Not Supported Supported
Interfaces
No Exception
Exception Handling Supported Supported
handling
Templates Not Supported Supported Not Supported
Storage class: auto,
Supported Supported Not Supported
extern
No Constructor or
Destructors Supported Not Supported
Destructor
Database Connectivity Not Supported Not Supported Supported

Object Oriented Languages -A Comparison


Java Integrates Power of Compiled Languages and Flexibility of Interpreted Languages
 We can develop two types of Java programs:
o Stand-alone applications
o Web applications (applets)
 Different ways to run a Java executable are:
Application- A stand-alone program that can be invoked from command line . A program
that has a “main” method
Applet- A program embedded in a web page , to be run when the page is browsed . A
program that contains no “main” method
 Different ways to run a Java executable are
 Different ways to run a Java executable are
 Application –Executed by the Java interpreter.
 Applet- Java enabled web browser.

1.8 JAVA and Internet


 Java is strongly associated with the internet because of the first application program is
written in Java was hot Java.
 Web browsers to run applets on the internet.
 Internet users can use Java to create applet programs & run then locally using a Java-
enabled browser such as hot Java.
 Java applets have made the internet a true extension of the storage system of the local
computer.
1.9 JAVA and WWW – Web Browsers

World Wide Web and internet

1. World Wide Web is a collection of information stored on internet computers.


2. World Wide Web is an information retrieval system designed to be used in the
internet‟s distributed environment.
3. World Wide Web contains web pages that provide both information and
controls.
4. Web pages contain HTML tags that enable us to find retrieve, manipulate and
display documents worldwide.
5. Before Java, the World Wide Web was limited to the display of still images &
texts.
6. With the help of Java WWW is capable of supporting animation graphics,
games and wide rage special effects.
1. Java communicates with a web page through a special tag called <applet>.
2. Java user sends a request for an HTML document to the remote computers net
browser.
3. The web-browser is a program that accepts a request, processes the request and
sends the required documents.
4. The HTML document is returned to that user browser.
5. The document contains the applet tag which identifies the applet. The corresponding
applet is transferred to the user computer.
6. The Java enabled browser on the user's computer interprets the byte code and
provide output.

Web Browsers

 The internet is a vast sea of information represented in many formats and stored on many
computers. a browser is a software application used to locate, retrieve and display
content on the World Wide Web, including Web pages, images, video and other files.
 As a client/server model, the browser is the client run on a computer that contacts the
Web server and requests information. The Web server sends the information back to the
Web browser which displays the results.
 The browser application retrieves or fetches code, usually written in HTML (Hypertext
Markup Language) and/or another language, from a web server, interprets this code, and
renders (displays) it as a Web page for you to view. on the computer or another Internet-
enabled device that supports a browser.

An example of Web Browsers:

 Hot Java
 Netscape Navigator
 Internet Explorer
 Google Chrome

Java Support System

Web Browser
local computer should be connected to the internet
Web Server
A program that accepts a request from a user and gives output as per the requirement.
Apache TomCat server is one of the major web servers.
Web Browser
The web browser is a software that will allow you to view web pages on the internet. it is a
program that you use to access the Internet. It reads and knows how to display and
download files that are put on servers for people to read. A program that provides the access
of WWW and runs java applets. Chrome and Firefox are two major web browsers.
HTML
HTML is short for Hypertext Markup Language. HTML is used to create electronic documents
(called pages) that are displayed on the World Wide Web. Each page contains a series of
connections to other pages called hyperlinks. Every web page you see on the Internet is
written using one version of HTML code or another.

Turning the Web into an Interactive and Application Delivery Platform


 Web is an open-ended information retrieval system designed to be used in the
Internet wide distributed system.
 It contains Web pages (created using HTML) that provide both information and
controls.
 Unlike a menu driven system--where we are guided through a particular direction
using a decision tree, the web system is open ended and we can navigate to a new
document in any direction.

Execution of Applets

Significance of downloading Applets

 Interactive WWW
 Flashy animation instead of static web pages
 Applets react to users input and dynamically change
 Display of dynamic data
 WWW with Java - more than a document publishing medium
 http://www.javasoft.com/applets/alpha/applets/StockDemo/standalone.html
Power of Java and the Web
 Deliver applications, not just information
 Eliminate porting
 Eliminate end-user installation
 Slash software distribution costs
 Reach millions of customers - instantly
Java Development Kit
 javac - The Java Compiler
 java - The Java Interpreter
 jdb- The Java Debugger
 appletviewer -Tool to run the applets
 javap - to print the Java bytecodes
 javaprof - Java profiler
 javadoc - documentation generator
 javah - creates C header files

1.9 Overview of Java- Simple JAVA Program.

 Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun
Microsystems' Java platform (Java 1.0 [J2SE]).
 The latest release of the Java Standard Edition is Java SE 8. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit various types
of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.
 The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively.
Java is guaranteed to be Write Once, Run Anywhere.
 When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do
class, object, methods, and instance variables mean.
 Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
 Class − A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type supports.
 Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
 Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.

The Basic Structure of a Simple Java Program.

You can use any editor like notepad or any Java IDE for writing java programs.

/*

This is a sample java program

Save this file as Welcome.java

*/

class Welcome

// A java program will start from here.

public static void main(String args[])

System.out.println(" Welcome to Java-Sample!!! ");

Compiling the program

After we have written our program we need to compile and run the program. For that we
need to use the compiler called javac which is provided by java.

Go to the command prompt and type the file name as shown here.

c;\>javac Welcome.java
The javac compiler will create a class file called Welcome.class that contains only bytecodes.
These bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the
bytecodes into machine codes. Once we successfully compiled the program, we need to run
the program in order to get the output. So this can be done by the java interpreter called java.
In the command line type as shown here.

c:\>java Welcome

So the output will be displayed as

Welcome to Java-Sample!!!

Java Tokens

 Token: A unit of user input. Tokens are separated by whitespace (spaces, tabs, new
lines).
 Example: If an input file contains the following:

23 3.14

"John Smith"

 The tokens in the input are the following, and can be interpreted as the given
types:

Token Type(s)

1. 23 int, double, String

2. 3.14 double, String

3. "John String

4. Smith" String

JVM

A Java Virtual Machine (JVM) is a virtual machine capable of executing Java


bytecode.

JVM is a piece of software that is implemented on non-virtual hardware and on standard


operating systems. A JVM provides an environment in which Java bytecode can be
executed, enabling such features as automated exception handling, which provides "root-
cause" debugging information for every software error (exception), independent of the source
code. A JVM is distributed along with a set of standard class libraries that implement the
Java application programming interface (API). Appropriate APIs bundled together form the
Java Runtime Environment (JRE).

JVMs are available for many hardware and software platforms. The use of the same
bytecode for all JVMs on all platforms allows Java to be described as a "compile once, run
anywhere" programming language, as opposed to "write once, compile anywhere", which
describes cross-platform compiled languages. Thus, the JVM is a crucial component of the
Java platform.

Java bytecode is an intermediate language which is typically compiled from Java, but it can
also be compiled from other programming languages. For example, Ada source code can be
compiled to Java bytecode and executed on a JVM.
Important University Question Bank

Section - B

1. List out the benefits of OOP.(2008,2010,2019)


2. Write a note on java virtual machine. (2007,2011,2013,2015)
3. Enumerate the various application of oops.(2014,2018,2019)
4. Discus any five java statements.(2014,2017)
5. Brief a note on vector.(2014)
6. Explain interface in java.(2014)
7. Discuss the various common java exception.(2013, 2018)
8. How you will draw a polygon? Explain.(2008,2016)
9. Describe the contribution of java to world wide web.(2009,2015)
10. Write down the need of java virtual machine.(2014,2019)
11. Write the general form of „switch‟ statement with example.(2015,2016)
12. What is a static variable? Explain.(2016,2017).

Section-C (8 MARK)
1. Discuss basic concept of oops.(2017,2010)
2. Describe the structure of java program with an example(2012)
3. Discuss basic concept of oops.(2019)
4. Describe the structure of java program with an example.(2013)
5. Briefly describe about any four OOP concepts.( 20072014,2019)
6. Explain the basic concept of oops.(2015)
7. How java differs from c and c++.(2017,2019)
8. Describe the various feature of java.(2013,2019)
9. Discuss the application and benefit of OOP. (2013,2015,2019)
10. Explain the following concept with an example(2016,2018)
i. Web browser ii. Java tokens
11. Explain the basic concept of object oriented programming.(2011,2019)
12.Write a note on java tokens. (2011,2014)

Expected Questions

1. Enumerate the various application of oops.

2. Explain the basic concept of OOPS with an example

3. Explain the basic concept of object oriented programming

4. How java differs from C and C++.


Course Material

Subject: Java Programming Class: II B.Sc CS A

Semester: III

Unit – II

Title Page No.

2.1. Constants 2
2.2. Variables 4
2.3. Data Types 7
2.4. Operators and Expressions 11

2.5. Decision Making Statements 19


2.6. Loop Statements 26
2.7. Class 36
2.8. Creating Method 39

1
2.1. Constants

• A constant value is the one which does not change during the execution of a program.
• Constants can be of any of the basic data types.

Integer Numeric Constant

• An Integer Numeric Constant is a sequence of digits (combination of 0-9 digits without


any decimal point or without precision), optionally preceded by a plus or minus sign.
• There are 3 types of integer numeric constant
o Decimal integer constants
o Octal integers constants
o Hexadecimal integer constants
• Decimal Integer Numeric Constant: These have no decimal point in it and are either
be alone or be the combination of 0-9 digits. These have either +ve or -ve sign. For
example: 1214, -1321, 10,254, -78, +99 etc.
• Octal Integer Numeric Constant: These consist of combination of digits from 0-7 with
positive or negative sign. It has leading with 0 or 0 (upper or lower case) means Octal
or octal. For example: 0317,003, -045 etc.
• Hexadecimal Integer Numeric Constant: These have hexadecimal data. It has leading
ox, OX, Ox or x, X. These have combination of 0-9 and A-F (a-f) or alone. The letters a-f
or A-F represents the numbers 10-15. For example: 0x232, 0x92, 0xACD, 0xAEF etc.

Floating or Real numeric constants

• Float Numeric Constants consists of a fractional part in their representation; Integer


constants are inadequate to represent quantities that vary continuously. These quantities
are represented by numbers containing fractional parts like 26.082.

2
• Examples of real constants are: 0.0026, -0.97, 435.29, +487.0, 3.4E-2, 4.5E5
• A floating-point constant consists of a sequence of decimal digits, a decimal point, and
another sequence of decimal digits. A minus sign can precede the value to denote a
negative value. Either the sequence of digits before the decimal point or after the decimal
point can be omitted, but not both.

Single Character Constant

• Single Character constants are enclosed between single quotes('). For example, 'a' and
'%' are both character constants. So these are also called single quote character
constant.
• For example: 'a', 'M', '5', '+', '1' etc. are some valid single character constant.

String Character Constant

• A string is a set of characters enclosed in double quotes ("). For example: "Punar
Deep" is a string.
• You must not confuse strings with characters. A single character constant is enclosed
in single quotes, as in 'a'. However, "a" is a string containing only one letter.
• For example: "Dinesh", "Hello", "2013", "2013-2020", "5+3", "?+!" etc. are some valid
string character constant. These are used for printing purpose or display purpose in the
java program's output statements. These can also be used for assigning the string data
to the character (string) type variables.

Backslash Character Constants

• Java Also Supports Backslash Constants those are used in output methods For Example
\n is used for new line Character These are also Called as escape Sequence or backslash
character Constants For Ex: \t For Tab ( Five Spaces in one Time ) \b Back Space etc.

3
2.2. Variables

• Variable is an identifier which holds data or another one variable is an identifier whose
value can be changed at the execution time of program. Variable is an identifier which
can be used to identify input data in a program.

• A variable is a data name that may be used to store a data value.


• A variable may take different values at different time during execution.
• Java variable is a named location in a memory where a program can manipulate the
data, this location is used to hold the value of the variable.
• The value of the java variable may get change in the program.
• Java variable might be belonging to any of the data type like int, float, char etc.
• Variables should be declared in the java program before to use

Rules for naming Java variable:

• Every variable name should start with either alphabets or underscore (_) or dollar ($)
symbol. Note: Actually a variable also can start with ¥,¢, or any other currency sign.(in
advance version of java)
• Variables are case sensitive eg. int var must be used ‘var’ not ‘Var’
• They can be constructed with digits, letters. Eg. var12 or var2 must not be 12var

4
• No space is allowed in the variable declarations.
• Except underscore ( _ ) no special symbol are allowed in the middle of variable
declaration
• Variable name always should exist in the left hand side of assignment operators.
• int Sum, float height, double a_value are some examples for variable name
• White space is not allowed. Eg. int var1 is valid int va r1 is not valid
• Upper case lower cases are significant.
• Maximum length of variable is 64 characters
• No keywords should access variable name.
• Variable initialization means assigning a value to the variable. int a=10;

Variable declarations

• In which sufficient memory will be allocated and holds default values.

Variable initialization

• It is the process of storing user defined values at the time of allocation of memory
space.

5
Variable assignment

• Value is assigned to a variable if that is already declared or initialized.

Over all example

Types of variable

• Type of Variables: There are three (3) types of variables in java:

6
1) Local Variable

• A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
• A local variable cannot be defined with "static" keyword.

2) Instance Variable

• A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
• It is called instance variable because its value is instance specific and is not shared
among instances.

3) Static variable

• A variable which is declared as static is called static variable. It cannot be local. You
can create a single copy of static variable and share among all the instances of the class.
Memory allocation for static variable happens only once when the class is loaded in the
memory.

2.3. Data Types

• Data type is a special keyword used to allocate sufficient memory space for the data, in
other words Data type is used for representing the data in main memory (RAM) of the
computer.

7
Three categories of data types

• Fundamental or primitive data types


• Derived data types
• User defined data types

Primitive data types

• Primitive data types are those whose variables allows us to store only one value but
they never allows us to store multiple values of same type.
• This is a data type whose variable can hold maximum one value at a time.

8
• Here "a" store only one value at a time because it is primitive type variable.

Derived data types

• Derived data types are those whose variables allow us to store multiple values of same
type. But they never allow to store multiple values of different types.
• These are the data type whose variable can hold more than one value of similar type.
In general derived data type can be achieve using array.

• Here derived data type store only same type of data at a time not store integer, character
and string at same time.

User defined data types

• User defined data types are those which are developed by programmers by making use
of appropriate features of the language.
• User defined data types related variables allows us to store multiple values either of same
type or different type or both. This is a data type whose variable can hold more than one
value of dissimilar type, in java it is achieved using class concept.
• Note: In java both derived and user defined data type combined name as reference
data type.
• In C language, user defined data types can be developed by using struct, union, enum
etc. In java programming user defined datatype can be developed by using the features
of classes and interfaces.

In java we have data type which are organized in four groups

o Integer category data types


o Character category data types
o Float category data types
o Boolean category data types

9
Integer category data types

• These category data types are used for storing integer data in the main memory of
computer by allocating sufficient amount of memory space.
• Integer category data types are divided into four types which are given in following table

Character category data types

• A character is an identifier which is enclosed within single quotes. In java to represent


character data, we use a data type called char. This data type takes two byte since it
follows Unicode character set.

Float category data types

• Float category data type are used for representing float values. This category contains
two data types, they are in the given table

Boolean category data types

• Boolean category data type is used for representing or storing logical values is true or
false. In java programming to represent Boolean values or logical values, we use a data
type called Boolean.

10
2.4. Operators and Expressions

• An operator is a symbol that tells the compiler to perform specific mathematical or


logical functions.
• Operators are used in programs to manipulate data and variables.
• Java language is rich in built-in operators and provides the following types of operators
▪ Arithmetic operators
▪ Relational operators
▪ Logical operators
▪ Assignment operators
▪ Increment/decrement operators
▪ Conditional operators (ternary operators)
▪ Bit wise operators

11
Arithmetic Operators

• Java Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus.
• Given table shows the entire Arithmetic operator supported by Java Language. Let’s
suppose variable A hold 8 and B hold 3.

12
Relational Operators

• Relational operators are used to find the relation between two variables. i.e. to compare
the values of two variables in a java program
• Given table shows the entire relatinal operator supported by Java Language. Let’s
suppose variable A hold 8 and B hold 3.

13
Logical Operators

• These operators are used to perform logical operations on the given expressions.
• There are 3 logical operators in java language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).
• Which can be used to combine more than one Condition?. Suppose you want to
combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B)
&& (B>C). Here && is Logical Operator.

Assignment Operators

• In java programs, values for the variables are assigned using assignment operators.
• Let’s suppose variable A hold 8 and B hold 3.

14
Increment/Decrement Operators

• Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
• Increment / Decrement operator are two types as follows:
o Post increment / decrement
o Pre increment / decrement
• Syntax:
o Increment operator: ++var_name; (or) var_name++;
o Decrement operator: – -var_name; (or) var_name – -;
• Example:
o Increment operator : ++ i ; i ++ ;
o Decrement operator : – – i ; i – – ;

15
Conditional Operators (Ternary Operators)

• Conditional operators return one value if condition is true and returns another value is
condition is false.
• This operator is also called as ternary operator.
• Syntax : (Condition? true_value: false_value);
• Example : (A > 100 ? 0 : 1);

16
Bit Wise Operators

• These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
• Bit wise operators in java language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR),
^ (XOR), << (left shift) and >> (right shift).

17
18
2.5. Decision Making Statements

• Decision making structures require that the programmer specifies one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed.
• if the condition is determined to be true, and optionally, other statements to be executed
if the condition is determined to be false.

Types of Decision Making Statements

o Simple if statement
o If else statement
o Nested If-else statement
o Switch statement
o Conditional or Ternary operator statement

Simple If Statement

• The if statement is powerful decision making statement and is used to control the flow
of execution of statements.
• It allows the computer to evaluate the expression first and then, depending on whether
the value of the expression is ‘true’ or ‘false’, it transfer the control to a particular
statement.
• An if statement consists of a Boolean expression followed by one or more statements
• If the expression is true, then 'statement-inside' it will be executed, otherwise 'statement-
inside' is skipped and only 'statement-outside' is executed.

19
If else statement

• An if statement can be followed by an optional else statement, which executes when


the Boolean expression is false.
• If the Boolean expression evaluates to true, then the if block will be executed,
otherwise, the else block will be executed.

20
21
Nested if...else statement

• The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
• The nested if...else statement allows you to check for multiple test expressions and
execute different codes for more than two conditions.

22
• if 'expression' is false the 'statement-block3' will be executed, otherwise it continues to
perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is
executed otherwise 'statement-block2' is executed.

Switch Statement

• Switch statement is used to solve multiple option type problems for menu like program,
where one value is associated with each option.
• The expression in switch case evaluates to return an integral value, which is then
compared to the values in different cases, where it matches that block of code is
executed, if there is no match, then default block is executed.
• The general form of switch statement is,

23
• The expression is an integer expression or character value1, value-2 ----- are constants
or constant expressions

24
• You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
• When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached
• When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached
• A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.

The ?: operator or Conditional or Ternary operator

• Conditional operators return one value if condition is true and returns another value is
condition is false.
• The conditional operator (? :) is a ternary operator (it takes three operands). The
conditional operator works as follows:

• Where
o expression1 is Condition
o expression2 is Statement Followed if Condition is True
o expression2 is Statement Followed if Condition is False

25
2.6. Loop Statements

• Execution of a statement or set of statement repeatedly is called as looping.


• The loop may be executed a specified number of times and this depends on the
satisfaction of a test condition.
• A program loop is made up of two parts one part is known as body of the loop and the
other is known as control condition.
• Depending on the control condition statement the statements within the loop may be
executed repeatedly.
• Depending on the position of the control statement in the loop, a control structure may
be classified either as an
o Entry controlled loop
o Exit controlled loop

Entry Control Loop

• Entry controlled loop, the condition is tested before the execution of the loop. If the test
condition is true, then the loop gets the execution, otherwise not.

Exit Control Loop

• The types of loop where the test condition is stated at the end of the body of the loop,
are know as the exit controlled loops.
• In the case of the exit controlled loops, the body of the loop gets execution without
testing the given condition for the first time.

26
• Then the condition is tested. If it comes true, then the loop gets another execution and
continues till the result of the test condition is not false.

Block diagram of entry control loop exit control loop

• In Java the Looping Statements are


o For loop
o While Loop
o Do...While Loop

For Loop

• for loop is used to execute a set of statements repeatedly until a particular condition is
satisfied. we can say it an open ended loop.

27
• Initialization: This step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize any loop control
variables.
• Condition: This is next step after initialization step, if it is true, the body of the loop is
executed, if it is false then the body of the loop does not execute and flow of control goes
outside of the for loop.
• Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is execute. This
statement allows to update any loop control variables.

28
29
While Loop

• In while loop first check the condition if condition is true then control goes inside theloop
body otherwise goes outside of the body. while loop will be repeats in clock wise direction.
• While loop can be addressed as an entry control loop. It is completed in 3 steps
o Variable initialization.( e.g int x=0; )
o condition( e.g while( x<=10) )
o Variable increment or decrement ( x++ or x-- or x=x+2 )

• The while loop evaluates the test expression.


• If the test expression is true (nonzero), codes inside the body of while loop is evaluated.
Then, again the test expression is evaluated. The process goes on until the test
expression is false.
• When the test expression is false, the while loop is terminated.

30
31
Do..While Loop

• In some situations it is necessary to execute body of the loop before testing the condition
• Such situations can be handled with the help of do-while loop.
• do statement evaluates the body of the loop first and at the end, the condition is checked
using while statement (or) The do..while loop is similar to the while loop with one
important difference is the body of do...while loop is executed once, before checking the
test expression. Hence, the do...while loop is executed at least once.

32
• The code block (loop body) inside the braces is executed once
• Then, the test expression is evaluated. If the test expression is true, the loop body is
executed again. This process goes on until the test expression is evaluated to 0 (false).
• When the test expression is false (nonzero), the do...while loop is terminated.

Jump in Loops

• Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or
to leave the loop as soon as certain condition becomes true, that is called jumping out
of loop.
• The types of jump in loops are
o Continue
o Break

Continue

• Continue statement is mostly used inside loops. Whenever it is encountered inside a


loop, control directly jumps to the beginning of the loop for next iteration, skipping the
execution of statements inside loop’s body for the current iteration
• The continue statement works somewhat like the break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in
between.

33
• Syntax Continue;

34
APT
Break

• When break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop
• When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement Syntax break;

36
APT

2.7. Class

• The classes are the most important feature of java that leads to Object Oriented
programming.
• Class is a user defined data type, which holds its own data members and member
functions, which can be accessed and used by creating object of that class.
• The variables inside class definition are called as data members and the functions are
called member functions
• A class definition starts with the keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces.
• A class definition must be followed either by a semicolon or a list of declarations.
• For example, we defined the Box data type using the keyword class as follows:

• A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.

Objects

• Once a class is defined, you can declare objects of that type. The syntax for declaring a
object is the same as that for declaring any other variable.
• Objects are instances of class, which holds the data variables declared in class and the
member functions work on these class objects.
• To use the data and access functions defined in the class, you need to create objects.

37
APT
• The new keyword is used to allocate memory at run time. All objects get memory in
Heap memory area.
• Creating multiple objects by one type only

Method in Java

• In java, a method is like function i.e. used to expose behavior of an object.


• Advantage of Method
o Code Reusability
o Code Optimization

38
APT

39
APT
2.8. Creating Method

• A Java method is a collection of statements that are grouped together to perform an


operation.
• When you call the System.out.println() method, for example, the system actually
executes several statements in order to display a message on the console.

Method declaration has four major parts

• The name of the method (method name)


• The type of the value method returns (return type)
• A list of parameters (parameter list)
• A body of the method

Method Calling

• By using a method-name, it should be called.


• There are Two ways in which a method is called
o Method returns a value
o Method returning nothing (no return value)
• The process of method calling is simple. When a program invokes a method, the program
control gets transferred to the called method. This called method then returns control to
the caller in Two Conditions, when

40
APT
o The return statement is executed.
o It reaches the method ending closing brace

41
Course Material

Subject: Java Programming Class: II B.Sc CS A

Semester: III

Unit – III

Title Page No.

3.1. Java Array 2


3.2. Java String 6
3.3. Vector in Java 8

3.4. Java Interface 11

3.5. Java Packages 16


3.6. Multithread Programming 21
3.7. Life cycle of thread 22

3.8. Creating Threads 24


3.9. Thread Priority 27

1
2
3.1. Java Array

• Array is a collection of similar type of data. It is fixed in size means that you can't
increase the size of array at run time
• An array is a collection of similar types of data. It is a container that holds data (values)
of one single type. For example, you can create an array that can hold 100 values of int
type.

How to declare an array?

• In Java, here is how we can declare an array.


o dataType[] arrayName;
• dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
o arrayName - it is an identifier

But, how many elements can array this hold?

• Good question! We have to allocate memory for the array. The memory will define the
number of elements that the array can hold.
o data = new Double[10];
• Here, the size of the array is 10. This means it can hold 10 elements (10 double types
values). The size of an array is also known as the length of an array.

Java Array Index

• In Java, each element in an array is associated with a number. The number is known
as an array index. We can access elements of an array by using those indices. For
example,
• int[ ] age = new int[5];

• It stores the value on the basis of the index value.

3
How to initialize arrays in Java?

• In Java, we can initialize arrays during declaration or you can initialize later in the
program as per your requirement.
• Initialize an Array During Declaration
• we can easily access and alter elements of an array by using its numeric index
• Here's how you can initialize an array during declaration.
o int[] age = {12, 4, 5, 2, 5};

Advantage of Array

• One variable can store multiple value: The main advantage of the array is we can
represent multiple value under the same name.
• Code Optimization: No, need to declare a lot of variable of same type data, We can
retrieve and sort data easily.
4
• Random access: We can retrieve any data from array with the help of the index value.

Disadvantage of Array

• The main limitation of the array is Size Limit when once we declare array there is no
chance to increase and decrease the size of an array according to our requirement,
Hence memory point of view array concept is not recommended to use.

Array creation

• Every array in a Java is an object, Hence we can create array by using new keyword.

• Note: At the time of array creation we must be specify the size of array otherwise get
an compile time error.
o For Example
o int[] a=new int[]; Invalid (some times).
o int[] a=new int[5]; Valid
• If we specify the array size as negative int value, then we will get run-time error,
• The maximum allowed size of array in Java is 2147483647 (It is the maximum value of
int data type)

5
Difference Between Length and Length() in Java

• length: It is a final variable and only applicable for array. It represent size of array.

• length(): It is the final method applicable only for String objects. It represents the
number of characters present in the String.

Types of Array

• Single Dimensional Array

• Multidimensional Array

6
3.2. Java String

• Strings represents sequence of char values. An array of characters works same as java
string.

• In Java programming language, strings are treated as objects.


• The java.lang.String class is used to create string object.

How to create String object

• There are two ways to create String object:


o String literal
o New keyword

String literal

• Java String literal is created by using double quotes.

7
• Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance is returned. If string
doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:

New keyword

• In such case, JVM will create a new string object in normal(non pool) heap memory and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer
to the object in heap(non pool).

8
3.3. Vector in Java

• Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit.

Creating a Vector

• Here is how we can create vectors in Java.

Vector<Type> vector = new Vector<>();

• Here, Type indicates the type of a linked list. For example,

// create Integer type linked list

Vector<Integer> vector= new Vector<>();

// create String type linked list

Vector<String> vector= new Vector<>();

9
Methods of Vector

• The Vector class also provides the resizable-array implementations of the List interface
(similar to the ArrayList class). Some of the Vector methods are:

Add Elements to Vector

• add(element) - adds an element to vectors


• add(index, element) - adds an element to the specified position
• addAll(vector) - adds all elements of a vector to another vector

Access Vector Elements

• get(index) - returns an element specified by the index

Remove Vector Elements

• remove(index) - removes an element from specified position


• removeAll() - removes all the elements
• clear() - removes all elements. It is more efficient than removeAll()

10
• Vector implements a dynamic array. It is similar to ArrayList
• Vector class object organizes the data in the form of cells
• Vector proves to be very useful if you don't know the size of the array in advance or you
just need one that can change sizes over the lifetime of a program


• The default capacity of the Vector v=10 cells
• Vector are Synchronized
• Vector uses Enumeration interface to traverse the elements
• Vector class object organizes the data in the form of cells

11
• The default size of the Vector=0 (size is nothing but number of values available in the
cells)
• In Vector cell values are storing in Heap Memory and cell address

3.4. Java Interface

• An interface is similar to class. It is a collection of abstract methods (function) and


variables with major differences.
• The difference is that interface define only abstract methods and final fields, This
means that interfaces do not specify any code to implement these methods and data
fiedls contain only constants.
• Therefore, it is the responsibility of the class that implements an interface to define the
code for implementation these methods.
• Java Interface also represents IS-A relationship.
• It is used to achieve abstraction and multiple inheritance in Java.

12
• All the methods of an interface are by default public. So, it is not required to use the
keyword public when declaring a method in an interface.

How interface is different from class?

• An interface can contain any number of methods


• All methods in an interface are abstract (only declaration of method).
• Interface is cannot extended by a class; it is implemented by a class.
• Interface can extend multiple interfaces. It means interface support multiple inheritance

Understanding relationship between Classes and Interface

• As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.

Creating interface:

• The interface keyword is used to declare an interface.

13
• In the above syntax Interface is a keyword interface name can be user defined name
the default signature of variable is public static final and for method is public abstract.

Extending interface

• An interface can extend another interface in the same way that a class can extend
another class.
• The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface, this means an interface can be sub-interface from
other interfaces, the new sub-interface will inherit all the members of the super-
interface in the manner similar to subclass

Implementing Interface:

• A class uses the implements keyword to implement an interface. The implements


keyword appears in the class declaration following the extends portion of the
declaration.

14
Rules for implementation interface

• A class can implement more than one interface at a time.


• A class can extend only one class, but implement many interfaces.
• An interface can extend another interface, similarly to the way that a class can extend
another class.

15
16
3.5. Java Packages

• A java package is a group of similar types of classes, interfaces and sub-packages.


• Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces.
• The purpose of package concept is to provide common classes and interfaces for any
program separately. In other words if we want to develop any class or interface which is
common for most of the java programs than such common classes and interfaces must
be place in a package.

Advantage of Java Package

• Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
• Java package provides access protection.
• Java package removes naming collision.
• Application development time is less, because reuse the code
• Package in java can be Categorized in two form
o Built-in package
o User-defined package

Built-in package

• These packages consist of a large number of classes which are a part of


Java API.Some of the commonly used built-in packages are:

17
• java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
• java.io: Contains classed for supporting input / output operations.
• java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
• java.applet: Contains classes for creating Applets.
• java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
• java.net: Contain classes for supporting networking operations.

User-defined packages

• If any package is design by the user is known as user defined package.


• Any package program can be compile but cannot be execute or run. These program
can be executed through user defined program which are importing package program.

Rules to create user defined package

• Package statement should be the first statement of any package program.


• Choose an appropriate class name or interface name and whose modifier must be
public.
• Any package program can contain only one public class or only one public interface
• Package program should not contain any main class (that means it should not contain
any main())
• Every package program should be save either with public class name or public
Interface name
• Compile package programs - javac -d . a.java
• To Run: java mypack.a

18
• Import above class in below program using import packageName.className
• Explanations: In above syntax "-d" is a specific tool which is tell to java compiler
create a separate folder for the given package in given path. When we give specific
path then it create a new folder at that location and when we use . (dot) then it crate a
folder at current working directory.

• Explanations: In the above program first we create Package program which is save
with A.java and compiled by "javac -d . A.java". Again we import class "A" in class Hello
using "import mypack.A;" statement.

Difference between package keyword and import keyword

• Package keyword is always used for creating the undefined package and placing
common classes and interfaces.
• Import Is A Keyword which is used for referring or using the classes and interfaces of
a specific package.

Access Package

• There are Three ways to access the package from outside the package.
o import package.*;
o import package.classname;
o fully qualified name

Using Packagename.*

19
• If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages (Package inside the package is called the
subpackage).
• The import keyword is used to make the classes and interface of another package
accessible to the current package.

Using packagename.classname

• If you import package.classname then only declared class of this package will be
accessible.

20
Using fully qualified name

• If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
• It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

21
Subpackage in java

• Package inside the package is called the subpackage. It should be created to


categorize the package further.

3.6. Multithread Programming

• A program can be divided into a number of small processes. Each small process can
be addressed as a single thread.
• Multithreaded programs contain two or more threads that can run concurrently and
each thread defines a separate path of execution. This means that a single program

22
can perform two or more tasks simultaneously. For example, one thread is writing
content on a file at the same time another thread is performing spelling check.
• In computer, multitasking is when multiple processes share common processing
resources such as a CPU, hard disk etc... Multi-threading extends the idea of
multitasking into applications where you can subdivide specific operations within a
single application into individual threads.
• Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
• A Thread is similar to a program that has a single flow of control, It has a beginning, a
body, and an end, and executes commands sequentially.
• Thread is a lightweight components and it is a flow of control. In other words a flow of
control is known as thread, Threads share the same address space.
• Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.

Advantages of Java Multithreading

• It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
• You can perform many operations together so it saves time.
• Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

3.7. Life cycle of thread

• State of a thread are Classified into five types they are


o New State
o Ready State
o Running State
o Waiting State
o Halted or dead State

23
• New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it completes
its task or otherwise terminates.

24
3.8. Creating Threads

• In java language multithreading can be achieve in two different ways.


o Using Extending Thread class
o Using Runnable interface

Using Extending Thread class

In java language Rules to be followed to creating multithreading program

• Create any user defined class and make that one as a derived class of thread class.

25
• Override run() method of Thread class (It contains the logic of perform any operation)
• Create an object for user-defined thread class and attached that object to predefined
thread class object.
• Object Creation for Thread Class_Name obj=new Class_Name Thread t=new
Thread(obj);
• Call start() method of thread class to execute run() method.
• Save the program with filename.java

Using Runnable interface

26
• The easiest way to create a thread is to create a class that implements the runnable
interface. After implementing runnable interface , the class needs to implement the
run() method,

Rules to create the thread using Runnable interface

• Create any user defined class and implements runnable interface within that
• Override run() method within the user defined class.
• all start() method to execute run() method of thread class

Stopping thread

• When ever we want to stop a thread from running further, we may do so by calling its
stop() method, ex. aThread.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 thread

• A thread can also be temporarily suspended or blocked from entering into the runnable
and subsequently running state by using either following thread methods.
• sleep() - block for a specified time
• suspend() - blocked until further order
• wait() - blocked until certain condition occurs

27
What is the difference between sleep() and suspend()

• Sleep() can be used to convert running state to waiting state and automatically thread
convert from waiting state to running state once the given time period is completed.
• Whereas suspend() can be used to convert running state thread to waiting state but it
will never return back to running state automatically.

3.9. Thread Priority

• Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread scheduler schedules the threads according to their priority
(known as preemptive scheduling).

Three types of Thread Priority

public static int MIN_PRIORITY


public static int NORM_PRIORITY
public static int MAX_PRIORITY

The following are the methods of thread class

• getPriority() - This method is used to get the current priority of thread.


• setPriority() - This method is used to set the current priority of thread.
• getName() - This method is used to get the current executing thread name.
• setName() - This method is used to set the user-defined name for the thread.
• run() - Which contains the main business logic that can be executed by multiple
threads simultaneously in every user defined thread class run method should be
overridden.
• start() - Used to convert ready state thread to running state.

28
• sleep() - Used to change running state thread to ready state based on time period it is
a static method should be called with class reference.
• suspend() - used to convert running state thread to waiting state, which will never
come back to running state automatically.
• resume() - Used to change the suspended thread state(waiting state) to ready state.
• stop() - This method is used to convert running state thread to dead state.
• getState() - This method is used to get the current state of thread.

29
Course Material

Subject: Java Programming Class: III B.Sc CS A

Semester: III

Unit – IV

Title Page No.


4.1. Errors 2
4.2. Exceptions 4

4.3. Handling Exceptions 6


4.4. Applet Programming 13

4.5. Running of Applet Programs 15


4.6. AWT (Abstract Window Toolkit) 17
4.7. Graphics Programming 24

1
4.1. Errors

• It is common to make mistake while developing as well as typing a program.


• A mistake might lead to an error causing to program to produce unexpected results.
• Errors are the wrongs that can make a program go wrong
• An Error may produce an incorrect output or may terminate the execution of the
program unexpectedly or even may cause the system to crash.

There are two types of error

o Compile time error


o Runtime error

Compile time error

• Syntax errors will be detected and displayed by the java compiler and therefore these
errors are known as compile time error.
• Whenever compiler displays an error, it will not create the .class file.
• It is necessary that we fix all the errors before we can successfully compile and run the
program.

Most common errors are

• Mission semicolons
• Missing brackets in classes and methods
• Misspelling of identifiers and keywords
• Missing double quotes in strings
• Use of undeclared variables
• Incompatible types in assignment/initialization
• Bad reference to objects
• Use of = in place of == operator

2
• In the above program semicolon is missing in the first statement

Runtime error

• Sometimes a program may compile successfully creating .class file but may not run
properly, such program may produce wrong results due to wrong logic.
• infinite loop
• divide by zero
• Array Index Out of Bounds
• Finding remainder and storing answer in a float or double.
• Dividing float/float and storing answer in integer
• Negative size of array
• Converting invalid string to a number

3
4.2. Exceptions

• The process of converting system error messages into user friendly error message is
known as Exception handling.
• The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
• An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and
the program/Application terminates abnormally, which is not recommended, therefore,
these exceptions are to be handled.

An exception can occur for many different reasons

• A user has entered an invalid data


• A file that needs to be opened cannot be found
• A network connection has been lost in the middle of communications or the JVM has
run out of memory

Type of Exception

o Checked Exception
o Un-Checked Exception

Checked Exception

• Checked Exception are the exception which checked at compile-time. These exception
are directly sub-class of java.lang.Exception class.
• Only for remember: Checked means checked by compiler so checked exception are
checked at compile-time.
o FileNotFoundException
o ClassNotFoundException
o IOException
o InterruptedException

4
Un-Checked Exception

• They are the exception both identifies or raised at run time. These exception are
directly sub-class of java.lang.RuntimeException class.
• Note: In real time application mostly we can handle un-checked exception.
• Only for remember: Un-checked means not checked by compiler so un-checked
exception are checked at run-time not compile time.
o ArithmeticException
o ArrayIndexOutOfBoundsException
o StringIndexOutOfBoundsException
o NumberFormateException
o NullPointerException
o NoSuchMethodException
o NoSuchFieldException

5
Difference between checked Exception and un-checked Exception

Difference between Error and Exception

4.3. Handling Exceptions

• Handling the exception is nothing but converting system error generated message into
user friendly error message in others word whenever an exception occurs in the java
application, JVM will create an object of appropriate exception of sub class and
generates system error message, these system generated messages are not
understandable by user so need to convert it into user-friendly error message.

6
• You can convert system error message into user-friendly error message by using
exception handling feature of java.

Use Five keywords for Handling the Exception

o try
o catch
o finally
o throw

General syntax for Syntax for handling the exception

Try block

• Inside try block we write the block of statements which causes executions at run time in
other words try block always contains problematic statements.

Important points about try block

• If any exception occurs in try block then CPU controls comes out to the try block and
executes appropriate catch block.
• After executing appropriate catch block, even through we use run time statement, CPU
control never goes to try block to execute the rest of the statements.

7
• Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.

• Each and every try block must contains at least one catch block. But it is highly
recommended to write multiple catch blocks for generating multiple user friendly error
messages.
• One try block can contains another try block that is nested or inner try block can be
possible.

Catch block

• Inside catch block we write the block of statements which will generates user friendly
error messages.

Catch block important points

• Catch block will execute exception occurs in try block.

8
• You can write multiple catch blocks for generating multiple user friendly error messages
to make your application strong. You can see below example.
• At a time only one catch block will execute out of multiple catch blocks.
• in catch block you declare an object of sub class and it will be internally referenced by
JVM.

Example without Exception Handling

• Abnormally terminate program and give a message like below, this error message is
not understandable by user so we convert this error message into user friendly error
message, like "denominator not be zero".

9
Example of Exception Handling using try and catch block

Multiple catch block

• You can write multiple catch blocks for generating multiple user friendly error messages
to make your application strong. You can see below example.

10
Finally Block

• Inside finally block we write the block of statements which can handle an exception that
is not caught by any of the previous catch statements.

11
Finally block important points

• Finally block will execute compulsory


• Writing finally block is optional.
• You can write finally block for the entire java program
• In some of the circumstances one can also write try and catch block in finally block.

Throw block

• Throw is a keyword in java language which is used to throw any user defined exception
to the same signature of method in which the exception is raised.
• Note: throw keyword always should exist within method body.

12
Throws

• Throws is a keyword in java language which is used to throw the exception

which is raised in the called method to it's calling method throws keyword

always followed by method signature.

4.4. Applet Programming

• Applets are small java programs that are primarily used in internet computing.
• Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
• An applet, like any application program, can do many things for us, it can perform
arithmetic operations, display graphics, play sounds, accept user input, create
animation and play interactive games.
• An applet developed locally and stored in a local system is known as local applet,
When a web page is trying to find a local applet, it does not need to use interne facility.
• A remote applet is that which is developed by someone else and stored on a remote
computer connected to the internet.

Advantage of Applet

o Applets are supported by most web browsers


o Applets works on client side so less response time
o Secured: No access to the local machine
o Easy to develop applet, just extends applet class

Life cycle of applet

13
o Initialization - init()
o start()
o paint()
o stop()
o destroy()

• init(): Which will be executed whenever an applet program start loading, it contains the
logic to initiate the applet properties.
• paint(): It displays the result of the applet code on the screen. The output may be text,
graphics, or sound.
• start(): It will be executed whenever the applet program starts running.
• stop(): Which will be executed whenever the applet window or browser is minimized.
• destroy(): It will be executed whenever the applet window or browser is going to be
closed (at the time of destroying the applet program permanently).

Building applet code

• Without these import statements, the Java compiler would not recognize the classes
Applet and Graphics, which the applet class refers to.
• import java.applet.*; Applet class which is contained this package provides lifecycle and
behavior to the applet through its methods init(), start() and point()
• import java.awt.*; contains graphics class, all output operations of an applet are
performed using the methods defined in the graphics class, The output may be text,
graphics, or sound.

14
4.5. Running of Applet Programs

• Applet program can run in two ways


o Using html (in the web browser)
o Using appletviewer tool (in applet window)

Running of applet using html

• In general no Java program can directly execute on the web browser except markup
language like html.
• Html support a predefined tag called <applet> to load the applet program on the
browser window.

15
Running of applet using appletviewer

• Some browser does not support <applet> tag so that Sun MicroSystem was introduced
a special tool called appletviewer to run the applet program.
• Applet tag is /*<Applet code=filename.class height=200 width=200></Applet>*/
• In this Scenario Java program should contain <applet> tag in the commented lines so
that appletviewer tools can run the current applet program.

The following are the commandds used to compile & run applet program

• To compile Applet program: javac filename.java


• To run applet program: appletviewer filename.java

16
4.6. AWT (Abstract Window Toolkit)

• AWT stand for abstract window toolkits. Any user interact with java program in two
different way;
o CUI (Command user Interface)
o GUI (Graphical user Interface)

17
• If any user interact with java program by passing same commands through command
prompt is known as CUI, if any user interact with java program through a graphical
window known as GUI.

• Container classes - These are the predefined classes in java.awt package which can
be used to display all non-container classes to the end user in the frame of window.
container classes are; frame, panel.
• Non-container classes - These are the predefined classes used to design the input
field so that end user can provide input value to communicate with java program, these
are also treated as GUI component. non-container classes are;
• Label - It can be any user defined name used to identify input field like textbox,
textarea etc.

• Button - This class can be used to create a push button.

18
• TextField - This class can be used to design textbox.

• TextArea - This class can be used to design a textarea, which will accept number of
characters in rows and columns format.

• CheckboxGroup - This class can be used to design radio button. Radio button is used
for single selection.

• Checkbox - This class can be used to design multi selection checkbox.

19
• Choice - This class can be used to design a drop down box with more options and
supports single selection.

• List - This class can be used to design a list box with multiple options and support multi
selection.

• Scrollbar - This class can be used to display a scroolbar on the window.

20
Display numeric value in applet

• In applets, we can display numerical values by first converting them into strings and
then using the drawstring() method of Graphics class we can do this easily by calling
the valueOf() Method of String class. Let us consider an example:

Getting Input from the User in Java Applet

• Applets work in graphical environment, therefore applets treat input as text strings.
• We can do this by using the TextField class of the applet package.
• For any kinds of computation on the input field, we must convert it to the right form and
the results again converted back to strings for display.

21
AWT Frame

• Frame - It is a predefined class used to create a container with the title bar and body
part.

22
• setTitle() - It is used to display user defined message on title bar.

• setBackground() - It is used to set background or image of frame.

• setForground() - It is used to set the foreground text color.

• setSize() - It is used to set the width and height for frame.

• setVisible() - It is used to make the frame as visible to end user.

• Note: You can write setVisible(true) or setVisible(false), if it is true then it visible


otherwise not visible.

23
• add() - It is used to add non-container components (Button, List) to the frame.

• Explanation: In above code we add button on frame using f.add(b), here b is the object
of Button class.

4.7. Graphics Programming

• Java graphics class includes methods for drawing many different types of shapes

from simple lines to polygons to text in a variety of fonts,

• To draw a shape on the screen, we may call one of the methods available in the

graphics class

The following are the drawing methods of the graphics class

• clearRect(int x, int y, int width, int height) - Clears the specified rectangle by filling it
with the background color of the current drawing surface.
• copyArea(int x, int y, int width, int height, int dx, int dy) - Copies an area of the
component by a distance specified by dx and dy.

24
• drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) - Draws the
outline of a circular or elliptical arc covering the specified rectangle
• drawLine(int x1, int y1, int x2, int y2) - Draws a line, using the current color, between
the points (x1, y1) and (x2, y2) in this graphics context's coordinate system
• drawOval(int x, int y, int width, int height) - Draws the outline of an oval
• drawPolygon(int[] xPoints, int[] yPoints, int nPoints) - Draws a closed polygon
defined by arrays of x and y coordinates.
• drawRect(int x, int y, int width, int height) - Draws the outline of the specified
rectangle
• drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) -
Draws an outlined round-cornered rectangle using this graphics context's current color
• drawString(String str, int x, int y) - Draws the text given by the specified string, using
this graphics context's current font and color
• fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) - Fills a circular
or elliptical arc covering the specified rectangle
• fillOval(int x, int y, int width, int height) - Fills an oval bounded by the specified
rectangle with the current color
• fillPolygon(int[] xPoints, int[] yPoints, int nPoints) - Fills a closed polygon defined
by arrays of x and y coordinates.

25
26
1

Unit V
Course Material

Subject: Core V : Java Programming Class: II B.Sc CS A

Semester: III

Syllabus
. Unit V: Managing Input / Output Files in Java : Concepts of Streams- Stream Classes –
Byte Stream classes – Character stream classes – Using streams – I/O Classes – File
Class – I/O exceptions – Creation of files – Reading / Writing characters, Byte-Handling
Primitive data Types – Random Access Files.

MANAGING INPUT / OUTPUT FILES IN JAVA: CONCEPTSOFSTREAMS


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.

Figure : Relationship of java program with I/O devices


A stream in Java is a path along which data flow. It has a source (of data) and a
destination (for that data). Both the source and the destination may be physical devices or
programs or other streams in the same program.

The concept of sending data from one stream to another (like one pipe feeding into
another pipe) has made streams in Java a powerful tool for file processing.
2

Input streams Reads


Source Program

a) Reading data into a program

Program Destination
Writes

Output streams

b) Writing data to a destination

Figure: Using input and output streams

Java streams are classified into two basic types, namely, input stream and output
stream. An input stream extracts (i.e. reads) data from the source (file) and sends it to the
program. Similarly, an output stream takes data from the program and sends (i.c. writes) it
to the destination (file).

STREAM CLASSES
The java.io package contains a large number of stream 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.
a) Byte stream classes that provide support for handling I/O operations on bytes.
b) Character stream classes that provide support for managing I/O operations on
characters.

Java Stream classes

Byte stream Character


classes stream classes

Write
Output Reader
Input Classes
Stream Classes
Stream

memory file pipe memory file pipe

Figure : Classification of java stream classes


3

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. Java provides two kinds
of byte stream classes: input stream classes and output stream classes.

Input stream classes


Input stream classes that are used to read 8-bit bytes include a super class known as
input stream and a number of subclasses for supporting various input-related functions.This
fig shows the class hierarchy of input stream classes.
The following are the methods provided by the InputStream class:

Method Description
1. read() reads a byte from the input stream
2. read (byte b[]) reads an array of bytes into b
3. read(byte b[],int n,int m) reads m bytes into b starting from nth byte
4. available() gives number of bytes available in the input
5. skip(n) skips over n bytes from the input stream
6. reset() goes back to the begining of the stream
7. close() close the input stream

Note that the class DatalnputStream extends FilterInputStream and implements the
interface Data Input. Therefore, the DatalnputStream class implements the methods
described in DataInput in addition to using the methods of InputStream class. The Datalnput
interface contains the following methods:
a) readShort() f) readDouble()
b) readLine() g) readUTF()
c) readChar() h) readLong()
d) readBoolean() i) readInt()
e) readFloat()
4

Output stream classes:


The several subclasses of the output stream can be used for performing the output
operations. The output stream includes methods are designed to perform the following
tasks:
• Writing bytes
• Closing streams
• Flushing streams

The following are the methods provided by the OutputStream class:

Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream

The DataOutputStream, a counterpart of DataInputStream, implements the interface


DataOutput and, therefore, implements the following methods contained in DataOutput
interface.
a) writeShort() f) writeDouble()
b) writeInt() g) writeBytes()
c) writeLong() h) writeChar()
d) writeFloat() i) writeBoolean()
e) writeUTF()

Hierarchy of output stream classes


5

CHARACTER STREAM CLASSES


Character streams can be used to read and write 16-bit Unicode characters. 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 the files. Reader class
is the base class for all other classes in this group. These classes are functionally very
similar to the input stream classes.

Figure: Hierarchy of reader stream classes

Writer Stream classes


Like output stream classes, the writer stream classes are designed to perform all
output operations on files. Only difference 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 other writer
stream classes
6

Hierarchy of writer stream classes

USING STREAMS
There are various types of input and output stream 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 writing operations only. Some perform operations such as
buffering, filtering, data conversion, counting and concatenation while carrying out I/O tasks.

Task character stream byte stream classes


classes
Performing input operations Reader Inputstream

Buffering input BufferedReader BufferedInputStream

Reading from an array CharArrayReader ByteArrayInputStream

Reading from files FileReader FileInputStream

Filtering the input FilterReader FilterInputStream

Pushing back characters/bytes PushBackReader PushbackInputStream

Reading from a string StringReader StringBufferInputStream

Reading primitive types (none) DataInputStream

Buffering output BufferedWriter BufferedOutputStream

Writing to an array CharArrayWriter ByteArrayOutputStream

Writing to a file FileWriter FileOutputStream


7

OTHER USEFUL I/O CLASSES


The java.io package supports many other classes for performing certain specialized
functions. They include among others:
• Random Access File
• Stream Tokenizer
The Random Access File enables us to read and write bytes, text and java data types
to any location in a file. This class extends object class and implements DataInput and
DataOutput interface as shown in below.
The class Stream Tokenizer, a subclass of object can be used for breaking up a
stream of text from an input text file into meaningful pieces called tokens. The behavior of
the Stream Tokenizer class is similar to that of the StringTokenizer class that breaks a string
into its component tokens. Object

DataInput DataOutput

RandomAccessFile

Figure : Implementation of the Random Access File

USING THE FILE CLASS


The java.io package includes a class known as the file class that provides that
support for creating files and directories. The class includes several constructors for
instantiating the File objects. This class also contains several methods for supporting the
operations such as
• Creating a file
• Opening a file
• Closing a file
• Deleting a file
• Getting the name of the file
• Getting the size of the file
• Checking the existence of a file
• Renaming a file
• Checking whether the file is writable
• Checking whether the file is readable
8

INPUT/OUTPUT EXCEPTIONS
When creating files and performing I/O operations on them, the system may generate
i/o related exceptions. The basic i/o related exception classes and their functions are given
below.

I/O exception class Function


EOFException signals that an end of the file or end of stream has bee
reached unexpectedly during
input.
FileNotFoundException informs that a file could not be found
InterrupetedIOException warns that an I/O operations has been interrupted
IOException signals that an I/O exception of some sort has occurred

Each I/O statement must have an exception handler around it as shown below:

try
{
.....................
. ........................ //I/O statements
.....................
}
catch (IOException e)
{
.................... // Message output statement
}

CREATION OF FILES
If we want to create and use a disk file, we need to decide the following about the file
and its intended purpose:
• Suitable name for the file
• Data type to be stored
• Purpose (reading, writing or updating)
• Method of creating the file
(i) A filename is a unique string of characters that helps identify a file on the disk. The length
of a filename and the characters allowed are dependent on the OS on which the java
program is executed. A file may consist of two parts, a primary name and an optional
period with extension.
9

Example:
Input.data Salary test.doc
student.txt
inventory rand.dat
(i) Data type is important to decide the type of file stream classes to be used for handling
the data. User should decide whether the data to be handled is in form of characters,
bytes or primitive type.
(i) The purpose of using a file must also be decided before using it. For example, user
should know whether the file is created for reading only, or writing only, or both the
operations.

The constructor, of stream classes may be used to assign the desired filenames to the file
stream objects.

Source or Characters Bytes


Destination Read Write Read Write
Memory CharArrayReade CharArrayWrite ByteArrayinputStream ByteArrayOutputStream
File FileReader FileWriter FilelnputStream FileOutputStream
Pipe PipedReader PipedWriter PipedinputStream PipedOutputStream

Figure: Common Stream Classes used for I/O Operations

There are two ways of initializing the file stream objects. All of the constructors
require that we provide the name of the file either directly, (as a literal string or variable), or
indirectly by giving a file object that has already been assigned a filename. The following
code segment illustrates the use of direct approach.

FileInputStream fis; // Declare a file Stream object


try
{
//Assign the filename to the file stream object
fis = new FileInputStream(“test.dat”);
……..
}
catch(IOException e)
…..
…..
The indirect approach uses a file object that has been initialized with the desired
filename.This is illustrated by the following code.
…………..
…………..
10

file inFile; //Declare a file object


InFile = new File(“test.dat”); //Assign the filename to
FileInputStream fis; // Declare a file Stream object
try
{
//Give the value of the file object
//to the file stream object
fis = new FileInputStream(inFile);
……..
}
catch (………)
……………
……………
The code above includes five tasks:
• Select a filename
• Declare a file object
• Give the selected name to the file object declared
• Declare a file stream object
• Connect the file to the file stream object

Both the approach are illustrated

Figure: Instantiating file stream objects

Example: Program to two file stream classes to copy the contents of a file named
“input.dat”into a file called “output.dat”.

//Copying character from one file into another


import java.io.*;
class Copy
11

{
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); //Opens inFile
outs=new FileWriter (outFile); //Opens outFile
//Read and write till the end
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally //Close files
{
try
{
ins.close();
outs.close ();
}
catch (IOException e)
{}
}
}
}
12

READING/WRITING CHARACTERS
The subclasses of Reader and Writer implement streams that can handle characters.
The two subclasses used for handling characters in files are FileReader and FileWriter.
The general form is
FileReader fileobject=new FileReader(filename);
FileWriter fileobject= new FileWriter(filename);

The following are the methods provided by the InputStream class:

Method Description
read() reads a byte from the input stream
read (byte b[]) reads an array of bytes into b
read(byte b[],int n,int m) reads m bytes into b starting from nth byte
available() gives number of bytes available in the input
skip(n) skips over n bytes from the input stream
reset() goes back to the beginning of the stream
close() close the input stream

The following are the methods provided by the OutputStream class:

Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream

Example: Program to two file stream classes to copy the contents of a file named
“input.dat”into a file called “output.dat”.

//Copying character from one file into another


import java.io.*;
class Copy
{
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
13

{
ins=new FileReader (inFile); //Opens inFile
outs=new FileWriter (outFile); //Opens outFile
//Read and write till the end
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally //Close files
{
try
{
ins.close();
outs.close ();
}
catch (IOException e)
{}
} } }

The character -1 indicates the end of the file and therefore the code
while ( (ch-ins.read( ) ) != -1)
causes the termination of the while loop when the end of the file is reached. The statements
ins.close();
outs.close ( );
enclosed in the finally clause close the files created for reading and writing. When the
program catches an I/0 exception, it prints a message and then exits from execution.
14

READING/WRITING BYTES
The FileReader and FileWriter classes is used to read and write 16-bits characters.
Two commonly used classes for handling bytes are FileInputStream and FileOutputStream
classes. This is used in place of FileReader and FileWriter.
The general form is
FileInputStream fileobject=new FileInputStream(filename);
FileOutputStream fileobject=new FileOutputStream(filename);

The following are the methods provided by the InputStream class:

Method Description
read() reads a byte from the input stream
read (byte b[]) reads an array of bytes into b
read(byte b[],int n,int m) reads m bytes into b starting from nth byte
available() gives number of bytes available in the input
skip(n) skips over n bytes from the input stream
reset() goes back to the beginning of the stream
close() close the input stream

The following are the methods provided by the OutputStream class:

Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream

The program demonstrates how FileOutputStream class is used for writing bytes to a
file. The writes to the names of some cities stored in a byte array to a new file named
"city.txt". User can verify the contents of the file by using the command
type city.txt

//Program1 for writing bytes to a file:


import java.io.*;
class WriteBytes
{
public static void main (string args[])
{
//Declare and initialize a byte array
byte cities[]= {„D‟,‟E‟,‟L‟,‟H‟,‟I‟,‟\n‟};
15

//create an output file stream


FileOutputStream outfile=null;
try
{
//Connect the outfile stream to “city.txt”
Outfile=new FileOutputStream(“city.txt”);
//Write data to the stream
Outfile.write(cities);
Outfile.close();
}
catch (IOException ioe)
{
System.Out.println(ioe);
System.exit(-1);
}}}

Explanation :

type city.txt
DELHI
MADRAS
LONDON

Program shows how FilelnputStream class is used for reading bytes from a file. The
program reads an existing file and displays its bytes on the screen. Remember, before we
run this program, we must first create a file for it to read. We may use this program to read
the file "city.txt" created in Program 1.

//Program2 for reading bytes from a file:

import java.io.*;
class ReadBytes
{
public static void main (string args[])
{
//Create an input file stream
FileInputStream infile=null;
int b;
try
{
//Connect infile stream to the required file
infile=new FileInputStream(args[0]);
16

//Read and display data


while((b=infile.read())!=-1)
{
System.out.println((char)b);
}
infile.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}}}
Note that the program requires the filename to be given as a command line argument.
Program2 displays the following when we supply the filename "city.txt".
Prompt>java ReadOytes city.txt
DELHI
MADRAS
LONDON

HANDLING PRIMITIVE DATA TYPES

The basic input and output streams provide read/write methods that can be used for
reading/writing bytes or characters. If we want to read/write the primitive data types such
as integers and doubles.
The two filter classes used for creating "data streams" for handling primitive types
are DataInputStream and DataOutputStream.
A data stream for input can be created as follows:
FileInputStream fis=new FileInputStream (infile);
DataInputStream dis=new DataInputStream (fis);
These statements first create the input file stream fis and then create the input data
stream dis. These statements basically wrap dis on fis and use it as a "filter". Similarly, the
following statements create the output data stream dos and wrap it over the output file
stream fos.
FileOutputStream fos=new FileOutputStream (outfile);
DataOutputStream dos=new DataOutputStream (fos);
The file objects infile and outfile must be initialized with appropriate file names before
they are used.
17

FileOutputStream fos = new FileOutputStream(outfile);


DataOutputStream dos = new DataOutputStream(fos);

Note that the file objects infile and outfile must be initialized with appropriate file names
before they are used. User may also use file names directly in place of files objects.

//Program for Reading and Writing primitive data:


import java.io.*;
class ReadWrite
{
public static void main (String args[]) throws IOException
{
file primitive=new File ("prim.dat");
FileOutputStream fos=new FileOutputStream (primitive);
DataOutputStream dos=new DataOutputStream (fos);
dos.writeInt(1999);
dos.writeDouble(375.85);
dos.writeBooloean(false);
dos.writeChar(„X‟);
dos.close();
fos.close();
FileInputStream fis=new FileInputStream (primitive);
DataInputStream dis=new DataInputStream (fis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
dis.close();
fis.close();
}
}

Output:
18

1999
375.85
false
X

RANDOM ACCESS FILES


The files that can be used either for "read only" or for "write only" operations. These
files are read or written only sequentially and, therefore, are known as sequential files.
The random access file class supported by the java.io package allows us to create files that
can be used for reading and writing data with random access. Such files are known as
random access files.
We can use one of the following two mode strings:
• "r" for reading only
• "rw" for both reading and writing
An existing file can be updated using the "rw" mode.
Random access files support a pointer known as file pointer that can be moved to
arbitrary positions in the file prior to reading or writing. The file pointer is moved using the
method seek () in the RandomAccessFile class. When the file is opened by the statement
file=new RandomAccessFile ("rand.dat", “rw”);
the file pointer is automatically positioned at the beginning of the file.

Example:
import java.io.*;
class randomIO
{
public static void main (string args[])
{
RandomAccessFile file=null;
try
{
file=new RandomAccessFile ("rand.dat",”rw”);
file.WriteChar(„X‟);
file.WriteInt(555);
file.Writedouble(3.1412);
file.seek(0);
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2);
19

System.out.println(file.readInt());
file.seek(file.length());
file.WriteBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(IOExceptiom e)
{
System.out.println(e);
}
}
}

The program opens a random access file and then performs the following operations.
1. Writes three items of data
X
555
3.1412
2. Brings the file pointer to the beginning.
3. Reads and displays all three items.
X
555
3.1412
4. Takes the pointer to the second item and then reads and displays the second item in the
file.
555
5. Places the pointer at the using the method length() and then add a Boolean item to the
file.
6. Finally, takes the pointer to the fourth item and displays it.
7. At the end, closes the file.

The output on the screen would appear as follows:

X
555
3.1412
555
false

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy