You are on page 1of 217

STUDENT REFERENCE

Internet Programming Using


Core Java – Part 1

globsyn technologies
XI - 11 & 12, Block - EP, Sector - V, Salt Lake Electronics Complex,
Calcutta - 700091, India

Globsyn
SR/JAVP1/301/1001/SC/3.0

All rights reserved. No part of this book shall be reproduced, stored in a retrieval
system, or transmitted by any means, electronic, mechanical, photocopying,
recording, or otherwise, without written permission from the publisher. No patent
liability is assumed with respect to the use of the information contained herein.

Globsyn
Internet Programming
Using Core Java – Part 1

Globsyn
Internet Programming Using Core Java – Part 1

Internet Programming Using Core Java

• Introduction to Java
• Java Class Concepts
• Packages and Interfaces
• Exception Handling in Java
• The Concept of Multithreading in Java
• Input/Output in Java

Module Objectives
Introduction To Java------------------------------------------------------------------------------------------ 4
History Of Java ------------------------------------------------------------------------------- 5
Java – The Programming Language ---------------------------------------------------------- 7
Features of Java ------------------------------------------------------------------------------- 9
Variables ------------------------------------------------------------------------------------- 15
Datatypes in Java ---------------------------------------------------------------------------- 17
Keywords ------------------------------------------------------------------------------------ 21
Literals and Comments ---------------------------------------------------------------------- 22
Operators------------------------------------------------------------------------------------- 24
Decision Constructs-------------------------------------------------------------------------- 28
Iteration or the Loop Construct -------------------------------------------------------------- 34
Arrays in Java -------------------------------------------------------------------------------- 42
Quiz ------------------------------------------------------------------------------------------ 48
Exercise -------------------------------------------------------------------------------------- 49
Summary------------------------------------------------------------------------------------- 51
Java Class Concepts ------------------------------------------------------------------------------------------52
Defining a Class ----------------------------------------------------------------------------- 53
Declaring Objects in Java -------------------------------------------------------------------- 56
Methods -------------------------------------------------------------------------------------- 60
Constructor ---------------------------------------------------------------------------------- 68
Method Overloading ------------------------------------------------------------------------- 72
Access Specifiers in Java -------------------------------------------------------------------- 76
Inheritance ----------------------------------------------------------------------------------- 78
Overriding ----------------------------------------------------------------------------------- 85
Static member and Final keyword ----------------------------------------------------------- 87
Abstract Class-------------------------------------------------------------------------------- 92
Quiz ------------------------------------------------------------------------------------------ 94

SR/JAVP1/301/1001/SC/3.0 1
Internet Programming Using Core Java – Part 1

Summary------------------------------------------------------------------------------------- 95
Packages and Interfaces-------------------------------------------------------------------------------------96
Packages ------------------------------------------------------------------------------------- 97
The CLASSPATH Variable ----------------------------------------------------------------103
Interfaces------------------------------------------------------------------------------------104
Packages in Java ----------------------------------------------------------------------------109
Quiz -----------------------------------------------------------------------------------------118
Summary------------------------------------------------------------------------------------119
Exception Handling in Java ------------------------------------------------------------------------------ 120
Exceptions in Java --------------------------------------------------------------------------121
Exception Handling Techniques ------------------------------------------------------------124
Unchecked Exception Classes --------------------------------------------------------------130
Checked Exception Classes-----------------------------------------------------------------131
User Defined Exceptions -------------------------------------------------------------------133
Quiz -----------------------------------------------------------------------------------------135
Exercise -------------------------------------------------------------------------------------136
Summary------------------------------------------------------------------------------------137
The concept of Multithreading in Java --------------------------------------------------------------- 138
Introduction to Threads ---------------------------------------------------------------------139
Concept of Multithreading------------------------------------------------------------------141
The thread Life Cycle-----------------------------------------------------------------------142
Thread States -------------------------------------------------------------------------------144
Other methods of the Thread class ---------------------------------------------------------146
Thread Creation-----------------------------------------------------------------------------150
Implementing the Runnable Interface ------------------------------------------------------153
Priority of Threads --------------------------------------------------------------------------156
Synchronization-----------------------------------------------------------------------------158
Interthread Communication-----------------------------------------------------------------168
Daemon Thread -----------------------------------------------------------------------------169
Quiz -----------------------------------------------------------------------------------------170
Exercise -------------------------------------------------------------------------------------171
Summary------------------------------------------------------------------------------------172
Input/Output in Java--------------------------------------------------------------------------------------- 173
Introduction---------------------------------------------------------------------------------174
File Class -----------------------------------------------------------------------------------175
Java Streams --------------------------------------------------------------------------------181
InputStream Class --------------------------------------------------------------------------183
OutputStream Class-------------------------------------------------------------------------190
Character Streams --------------------------------------------------------------------------197
Reader Class --------------------------------------------------------------------------------199
Writer Class ---------------------------------------------------------------------------------201
CharArrayReader ---------------------------------------------------------------------------202
CharArrayWriter ----------------------------------------------------------------------------204
Collection-----------------------------------------------------------------------------------206
Set Interface---------------------------------------------------------------------------------208

SR/JAVP1/301/1001/SC/3.0 2
Internet Programming Using Core Java – Part 1

List Interface --------------------------------------------------------------------------------209


Map Interface -------------------------------------------------------------------------------210
Quiz -----------------------------------------------------------------------------------------212
Summary------------------------------------------------------------------------------------214

SR/JAVP1/301/1001/SC/3.0 3
Internet Programming Using Core Java – Part 1

Introduction to Java
Objectives:
• Appreciate the evolution of Java as a
programming language
• Learn about the features of Java
• Develop, compile and run a simple Java program
• Recognize different datatypes
• Know about literals and keywords
• Implement decision-making and loop constructs in
a Java program
• Implement the concept of Arrays in a Java
program

Introduction To Java

At the end of this chapter, you will be able to:

Appreciate the evolution of Java as a programming language


Learn about the features of Java
Develop, compile and run a simple Java program
Understand the concept of variables
Recognize the different Datatypes
Know about literals and keywords
Implement decision-making & loop constructs in Java programs
Implement the concept of arrays in a Java program

SR/JAVP1/301/1001/SC/3.0 4
Internet Programming Using Core Java – Part 1

History of Java

• Developed by Patrick Naughton, James


Gosling and Mike Sheridian
• Emerged from OAK
• Gained popularity with the increased
importance of internet
• Enables the development of platform
independent languages

History Of Java
Let us begin our journey to the fascinating world of Java with a brief insight into its
history. This will enable us to appreciate the immense popularity that Java has gained
today.

In December 1990, Patrick Naughton, James Gosling and Mike Sheridan of Sun
Microsystems started to work on a project known as the Green Project. At that time the
programming languages that was ruling the software market was C and C++. However, C
and C++ have certain complexity and limitations as the programmers have to be
concerned about the platform which they are working on. This frustrated the project team
and they decided to create an object-oriented development environment based on C++,
but easier to learn and use. In April 1991, the team decided on embedded systems
software for smart consumer devices as the delivery platform for their project. James
Gosling wrote the original compiler called "Oak" and, with the other team members,
developed a runtime interpreter for what would become the Java language. In 1994 the
Green Project was aborted because of its restricted market. But from the “OAK emerged
a new language called JAVA.

However, a very obvious question that can rise in our minds at this stage is that what is
the necessity of developing a language that is platform independent or in other words that
can run on different operating systems without the need of recompiling. Let us try to find
out a convincing answer to this question.

The 1990s saw the emergence of Internet as the main medium of data exchange. Gone are
the days where networking involves joining a few machines in a particular department of
an organization or at most all the machines in the whole organization. Internet introduced
the concept of “network of networks” where innumerable computers (of different
hardware and software configurations) spanning the entire world are connected together
to facilitate exchange of information.

SR/JAVP1/301/1001/SC/3.0 5
Internet Programming Using Core Java – Part 1

This created the need for a language, which will execute on all Platforms (Software,
hardware, and OS). World Wide Web is made up of heterogeneous hardware and
software platforms of different types. So there must be some features, through which, a
universal program can run on any platform. This is where Java came into the picture.
With the help of Java one create platform independent programs.

SR/JAVP1/301/1001/SC/3.0 6
Internet Programming Using Core Java – Part 1

Java -The language

• Java is a high level,third generation


programming language
• Provides platform for distributed computing
and built-in support for world wide web
• Compiled with the help of Java compiler
(generates byte code) and interpreted by
Java interpreter.
• There are two types of Java programs
namely applications and applets
• Is a case sensitive language

Java – The Programming Language

Java si an Object Oriented programming language that can run on different platforms. A
Java program can also travel across a network and can be executed on another machine’s
browser. Java is a pure object oriented language i.e. everything has to be written within a
class.

The credit for making Java as a platform independent language goes to a very important
component of Java Runtime Environment called Java Virtual Machine (JVM as it is
more popularly known as).

When a Java program is compiled it is converted into a binary program called by the
Java Compiler. The binary format is called byte codes. Byte codes are actually machine
instructions that can be understood by the Java Virtual Machine . At the time of
execution of the program a Java interpreter that resides inside the Java Virtual
Machine executes the instructions that the byte codes specify. This interpreter is also
entrusted with the responsibility to the byte codes are safe to execute and has not been
tampered with. The interpreter also handles communication with the operating system of
the machine in which it is residing.

Since the Java program is compiled into byte codes instead of machine instructions (as in
the case of other programming languages like C, C++) it is completely encapsulated from
the hardware of the machine in which it is executing. Since, the Java interpreter handles
the execution of the byte codes, thus any computer that has Java Virtual Machine
installed in it can execute a Java program. This gives rise to a very important USP of Java
programming language namely “ Compile once and run anywhere”. The Java
interpreter located between the Java program that is being executed and the physical
hardware level of the machine and it prevent the program from performing any
unauthorized actions.

SR/JAVP1/301/1001/SC/3.0 7
Internet Programming Using Core Java – Part 1

The Java interpreter can either be stand-alone or it can be embedded in a Web Browser
such as Netscape Navigator or Microsoft Internet Explorer, which are automatically
used to run applets (explained below).

To write a Java program, we need a plain text editor such as Notepad, WordPad, MS-
DOS edit etc.) We can acquire the Java compiler and the JRE (Java Runtime
Environment) by downloading the Java Development Kit from the website http://
java.sun.com.

Java can be used to create two different types of programs, which are

1. Applications: - Standalone programs written in Java are known, as application. They


can run on the desktop with the help of the JVM.

2. Applets: - Applets are programs that are woven directly into Web pages. It requires a
web browser that has JVM to run on the desktop. They are pieces of executable Java
code that are embedded in an HTML document using the <APPLET> tag. To run an
applet without a browser we need Appletviewer (discussed in the later part of the
book). Applets have been discussed in detail in the later chapters of this book.

Java is a case-sensitive programming language.

SR/JAVP1/301/1001/SC/3.0 8
Internet Programming Using Core Java – Part 1

Features of JAVA

Different features of Java are :


• Simple
• Object oriented
• Distributed
• Interpreted and compiled
• Robust and secure
• Architectural neutral
• High performance
• Multi Threaded and Dynamic
• Java Vs C++

Features of Java

The following definition of Java by Sun Microsystems lists all the features of Java.

Java is a simple, Object Oriented, distributed, interpreted, robust, secure, architecture


neutral, portable, high performance, multithreaded and dynamic language.

Lets' look into the features individually.

Ø Simple

The fundamental concepts of Java technology can be are grasped quickly and hence
programmers can be productive from the very beginning. If you compare Java with
another commonly used object-oriented language C++, Java doesn’t support certain very
complex features such as multiple inheritance, direct memory manipulation via pointers
(pointer are variable in C and C++ that stores the address of another variable) and
operator overloading (It is a tool on C++ to implement polymorphism where different
operators are overloaded to do a different job that their normal job). That’s the reason we
can say Java is simple and easy to learn and use.

Ø Object Oriented

Java is purely object-oriented and supports the basic features of object orientation such as
abstraction, encapsulation, inheritance, and polymorphism. The syntax of Java is similar
to C++, another Object oriented language. But it differs from C++ in one concept i.e. it
does not support standalone functions. The most basic Java program is only made up of
classes. This you will discover while executing the first Java program discussed later in
this module.

SR/JAVP1/301/1001/SC/3.0 9
Internet Programming Using Core Java – Part 1

Ø Distributed

Java has been developed in such a way that it has the capability to share data and
resources across the network. Using Java, multiple programmers can work on a single
project from multiple remote locations. The Remote Method Invocation Mechanism of
Java helps establish communication between distributed objects. Similarly, newer
technologies like Beans and EJB are useful in achieving the component architecture
using Java.

Ø Interpreted and compiled

The Java compiler doesn't generate "machine code" in the sense of native hardware
instructions--rather, it generates byte-codes a high-level, machine-independent code for a
hypothetical machine called the Java Virtual Machine (JVM) that is implemented by
the Java interpreter and run-time system. When a program has to be executed, the code is
fetched into the memory and interpreted on the user machine.

Ø Robust

Java is intended for developing software that must be robust, highly reliable, and secure,
in a variety of ways.

In order to achieve the above, there is strong emphasis on early checking for possible
problems, as well as later dynamic (run-time) checking, to eliminate error-prone
situations. The Java compiler employs extensive and stringent compile-time checking so
that syntax-related errors can be detected early, before a program is deployed. One of the
advantages of a strongly typed language (like C++) is that it allows extensive compile-
time checking, so bugs can be found early. Unfortunately, C++ inherits a number of
loopholes in its compile-time checking from C. In this respect C++ and C are relatively
lax, most notably in the area of method or function declarations. Java imposes much more
stringent requirements on the developer: Java requires explicit declarations and does not
support C-style implicit declarations. Many of the stringent compile-time checks at the
Java compiler level are carried over to the run time, both to check consistency at run
time, and to provide greater flexibility. The linker understands the type system and
repeats many of the type checks done by the compiler, to guard against version mismatch
problems.

Ø Secure

We are already aware that the prominence and popularity of Java can mainly be attributed
to the growing use of Internet. Security should be a very important characteristic for any
program that runs on the Internet. In order to meet this requirement, a Java implements
multiple levels of security.

SR/JAVP1/301/1001/SC/3.0 10
Internet Programming Using Core Java – Part 1

Memory allocation and reference model impose the First level of security in Java. The
memory layout decision is not made during the compilation time but during the runtime
depending upon the Hardware and software platform where it is executed. The Second
line of defense is the class loader. Whenever a Java system is executing it may in turn
load class or classes from network, which is verified and tested by the byte code loader.
Java programs cannot read or write outside the program environment. So there is less
probability for the existing resources in the memory to be infected by virus.

A class loader is a part of Java Virtual Machine that finds and


loads a .class file. We will learn about .class files a little later in
this chapter.

Ø Architecture neutral

The Java programs are not transformed into machine dependent executable code during
compilation. Instead the Java compiler converts the source code into a binary format
called Byte code . The Java Interpreter that resides inside the Java Virtual Machine then
executes this Byte code within the Java Virtual Machine . Thus, any computer in which
the Java Virtual Machine is installed can run the Java program that we develop.
Moreover, say we have compiled a Java programmer on a computer running Windows
NT operating system. The same program can then be executed on a workstation which is
running Linux without again recompiling the program. This will avoid any need to
perform any special porting work for that program.

JVM is different for different platform. JVM for UNIX will be


different from JVM in WINDOWS.

Ø Portable

Since Java programs take an approach of byte code therefore it is portable to any system
on which the Java interpreter and run-time systems have been implemented.

Ø High performance

Java gives better performance than any Interpreter based language since the interpreter
can run at full speed without checking the runtime environment. The automatic garbage
collector running as a background thread ensures that memory is available when required
leading to high performance.

SR/JAVP1/301/1001/SC/3.0 11
Internet Programming Using Core Java – Part 1

Ø Multi-threaded

In Java programs, multiple tasks can be carried simultaneously by different thread


executing concurrently. In language level, also Java supports extremely better
synchronization of threads.

The multi threading property of Java means that they do not have to wait for the program
to finish a task before beginning another task. This makes Java very responsive to user
input. It also helps to contribute to Java’s robustness.

Ø Dynamic

Java is capable of dynamically linking new class libraries, methods and objects to the
programs that we have developed. Classes are linked only as needed. New code modules
can be linked in on demand from a variety of sources, even from sources across a
network.

Java source code is divided into .java files, usually one for each class that we define in
our program. The java .class file tends to be small, a few kilobytes at the most. It is not
necessary to link in large runtime libraries to produce an executable file. Instead, the
necessary classes are loaded from the user’s CLASSPATH.

Comparison between Java and C++

Difference between Java and C++ are listed below:

Java C++
Java does not support operator overloading. C++ supports operator overloading.
Java does not support multiple inheritance C++ supports multiple inheritance
It does not use pointer. It uses pointer.
De-allocation of memory is done
Requires explicit de-allocation of the
automatically with the help of the Garbage
memory by the user.
collection technique.

Writing our first Java program

As discussed earlier, the java program can be written in editors like the Notepad, DOS
editor etc. The java program has two main parts a class definition that encloses the entire
program and a method called main that contains the body. The java source code is stored
in files with .java extension. Usually the file name is the same as the class name that
contains the main() method.

SR/JAVP1/301/1001/SC/3.0 12
Internet Programming Using Core Java – Part 1

We will now write our first Java program. The program that we write below will display
the line “My first Java Program”.

class myClass
{
public static void main(String args[])
{
System.out.println("My first Java program");
}
}

Let us analyze the above program. We have already learnt that Java is a pure object-
oriented programming language. Therefore, all properties and methods of Java must be
placed inside the class definition.

So, the first line of our program defines the class within which our code should reside. To
define a class, the class keyword is used. Every class will have a name. In our program,
myClass is the name of the class.

The above program that we wrote has to execute from a specified point. The function
from which a Java program starts execution is the main () method.

The main () method is declared public. This is done in order to ensure that the
functionality of the main () method is not confined only within myClass. Thus the main
() method of myClass can even be called from outside myClass.

The keyword static is used after the keyword main (). We are all aware from our
knowledge of other object-oriented languages that a method defined within a class can
only be invoked with the help of an object belonging to that class. Java being a pure
object-oriented language is no exception. However, there are certain cases, where we
have to call a method defined within a class prior to the creation of any object belonging
to that class. An apt example in this regard is the main () method. The main () method is
the point from where the execution of a program begins. Therefore, it has to be called
before the creation of any object of the class within which main () has been declared.

In order to deal with such situations, Java provides a kind modifier called static which
enable a class variable or method to be called before the creation of any object of that
class. Thus, the main () method is declared static so that it can be called before creating
any object of the class within which it is declared.

The keyword void in the declaration of the main () method signifies that this method
does not return any value.

SR/JAVP1/301/1001/SC/3.0 13
Internet Programming Using Core Java – Part 1

System.out.println is used inside the program to print a message or value of a variable


on the standard output device (monitor).

We have to save after giving it a name, which should match with the class name. So the
name of our program should be myClass.java.

Compiling the program: As with other programming language the next step after
writing a Java program is to compile the program. We are already aware of the fact that
compilation of a java program results in the source code being converted to byte codes.
In order to achieve this we use the type in the following command in the command
prompt:

javac myClass.java

In the above command, javac is the name of the Java compiler and the myClass.java is
the name of the program source file. If our program does not contain any error, the Java
compiler generates the resulting byte code which is stored in a file that has the same
name as the source but with an extension of .class.

Java executable files are always stored with a .class extension.

Running the program: In order to execute the program that we have written, we have to
take the help of the java interpreter. To do so, the following command is required:

java myClass

In the above command, the file extension is not specified. This is because, in the instant
case, myClass is not a name of a file but it is the name of a Java class.

The output of the program is:

My first Java program

SR/JAVP1/301/1001/SC/3.0 14
Internet Programming Using Core Java – Part 1

Variables
• A named reserved portion in the memory which
is utilized to store the inputs to a program.
• In Java, variable is declared in the following
manner:
– datatype variable_name;
• Storing a value to a variable is called variable
initialization
• A variable should begin with a letter, dollar sign
or underscore and followed by letter, dollar sign
underscore or digits
• Should not be a key word or reserved word

Variables

Program is sequence of commands, which takes certain inputs, process it and gives an
output. The data, which are entered, as inputs to the program should be stored
somewhere. These inputs are only required during the execution of the program and not
permanently hence they are stored in the memory. For the purpose of storing these inputs
a certain portion of the memory is reserved, assigning a specific name to it. These named
memory spaces are referred to as variables.

Variable declaration is very similar to representing value in equation using x and y in


algebra. Variable declaration is performed in the following manner:

Datatype <varaible_name>

In the above code snippet variable_name is the name of the variable and datatype
represents the type of data that can be stored in the variable. Datatype of a variable
determines whether the variable can store numeric or character data.

In the code snippet below, we are declaring a variable named num in which we are
storing the value 10.

int num;

num = 10;

SR/JAVP1/301/1001/SC/3.0 15
Internet Programming Using Core Java – Part 1

In the above example, first we are declaring a variable called num whose datatype is
integer. Integer datatype ensures that num can store only numeric values (we will learn
more about datatypes in the subsequent topic). In the next line we are storing the value 10
to num. This step is called variable initialization.

Variable declaration and initialization can be performed in a single line as shown below:

int num = 10;

Each variable that is used in a program must be declared. That


is to say, the program must contain a statement specifying
precisely the name of the variable and what kind of data (data
type) the variable will contain. This applies to every variable in
the program, irrespective of the type .

Rules for naming variables

In Java, the name that we give to a method, variable or a class is called an identifier.
There are certain rules that must be followed with regard to an identifier. These rules are
as follows:

Ø An identifier can be of any length


Ø It must begin with a letter or an underscore (_) or a dollar sign ($). However, the
subsequent characters can include letters, digits, dollar sign or under score.
Ø An identifier should not be same as a keyword. Thus, we cannot have identifiers like
class, static and so on as these are keywords.
Ø Identifiers are case sensitive. So if a variable num is erroneously written as NUM
then the Java compiler will treat num and NUM as two different variables.
Ø An identifier should not be a Boolean literal or a constant value. A Boolean Literal
can only be true or false. Thus we cannot have variables having names like 7, true
and so on.

Thus in a nutshell, the name of a variable should be meaningful, short, and without any
embedded space or symbol like - ? ! @ # ^ % & ( ) [ ] { } . , ; : “ ‘ / and \. However,
underscore can be used wherever a space is required; for example, employee_Name

Conventions for naming Variable

Variable names begin with a lowercase letter, and class names begin with an uppercase
letter. If a variable name consists of more than one word, the words are joined together,
and each word after the first begins with an uppercase letter, like this: isVisible.

SR/JAVP1/301/1001/SC/3.0 16
Internet Programming Using Core Java – Part 1

Datatypes in Java

Java provides 2 different types of Datatypes,


which are:
• Primitive or Standard datatypes
• Abstract or Derived datatypes.

Datatypes in Java

The data that is stored in variable can be of many types. For example, basic_salary of an
employee is stored as numeric value and the address of the employee is stored as
alphanumeric characters. Data types are a way to define what type of data those variables
will store and the operations possible on them and the storage method.

Datatypes in Java can be differentiated into the following two categories:

Primitive – Primitive data types, also known as standard data types, are the data types
that are built into the Java language Compiler. The compiler contains extensive
instructions on the operations supported by the datatype. There are eight primitive data
types in Java. They are as follows:

Ø Boolean
Ø Char
Ø Byte
Ø Short
Ø Int
Ø Long
Ø Float
Ø Double

SR/JAVP1/301/1001/SC/3.0 17
Internet Programming Using Core Java – Part 1

Abstract or Derived Datatypes– Abstract data types are based on primitive data types
and have more functionality than primitive data types.

Let us bring about an analogy. All of us know unit of measurement in Physics. There are
two types of unit- Fundamental and Derived Unit. Examples of Fundamental units are
meter, Kilogram, Second and so on. Apart from this there are certain units, which are
made out of these fundamental units and are known as Derived units like meter/second
for measuring speed, meter/second2 for measuring acceleration. The same holds true for
Primitive and abstract data type. Abstract data types are made of primitive data type with
certain added functionality. There are different abstract data types in Java like String,
Float, and Integer. For example, String is an abstract data type that can store letters,
digits, and other characters. There is a predefined class called String. Since this is a class
there are different methods available to manipulate the String that the class contains.

Let us now examine the primitive datatypes of Java in detail.

Ø Boolean
A variable whose datatype is Boolean can contain either true or false. Boolean variables
cannot contain any other values. The values true or false that a Boolean variable can
contain are called Boolean Literals. A Boolean is declared in the following manner:

boolean b1 = true;

Ø Char
A variable whose datatype is char can store a single character (A-Z, a-z). A variable of
datatype char takes up 16 bytes (I.e. 2 bytes) of memory space. A character variable is
declared and initialized in the following manner :

char ch = ‘m’;

Java uses Unicode to represent characters. Unicode defines a fully international character
set that can represent all human languages. The range of char is from 0 to 65,535 ( i.e.
from 0 to 216 – 1). Thus , in the above code snippet the variable ch gets initialized with
the Unicode representation of the letter ‘m’.

The standard set of character sets, such as ASCII still ranges from 0 to 127. Since Java is
designed to allow applets to be written for worldwide use, it makes sense that it would
use Unicode to represent characters.

SR/JAVP1/301/1001/SC/3.0 18
Internet Programming Using Core Java – Part 1

The value of a character variable should always be enclosed with


a single quote.

Ø Integer

There are four kinds of integer datatypes in Java namely, byte, short, int, and long. Each
of these can hold different range of values and be used to store both positive and negative
values. The following table gives the details of range of values that each category of
Integer datatype can hold.

Datatype Size Minimum value Maximum value


Byte 8 bits -128 127
Short 16bits -32,768 32,767
Int 32bits -2,147,483,648 2,147,483,647
Long 64bits -9223372036854775808 9223372036854775807

Variable on Integer datatype is declared in the following manner:

byte b1= 23;


short s1 = 140;
int i1= 400;
long l1= 27786;

The range of values that can be stored in each of the four Integer
datatypes is the same irrespective of the type of computer that is
being used. This is an advancement that Java has introduced
over other datatypes.

Ø Float and double

Variables of datatype float specify a value that uses 32-bits of storage. Values of float
datatype can range from –3.4E38 (-3.4x1038 ) to +3.4E38 (+3.4x1038 ). The float type is
used to store number with decimal part and for storing fractional components. Float
values are represented with approximately 7 digits of accuracy. It is declared by using the
float keyword.

SR/JAVP1/301/1001/SC/3.0 19
Internet Programming Using Core Java – Part 1

The double type uses 64-bits for storage. Variable of datatype double can have values
ranging from –1.7E308 (-1.7x10308 ) to +1.7E308 (+1.7x10308 ). This type is returned by
functions like sin(), cos(), sqrt(), etc. It is declared by using the double keyword.

Operations involving Float and Double datatype complies with


IEEE754 standard. Like Integer datatypes, the range of values
that can be stored in Float and Double datatype also remains the
same irrespective of the hardware configuration of the computer
that we are using.

SR/JAVP1/301/1001/SC/3.0 20
Internet Programming Using Core Java – Part 1

Keywords

• Building blocks of Java programs


• Cannot be used to name identifiers

Keywords

In the previous module you have understood the features of Java. After that I am sure you
will agree that Java is a language. Like any other language Java has certain words and a
set of rules to arrange and use them. These words are called keywords and the grammar
of arranging them is called the syntax of the language.

For writing a program we have to arrange these keywords adhering to the syntax of the
language. Apart from using keywords we might have to use operators, data types for
writing a Java program. All these keywords, syntax, data types, operators are defined in
the compiler of the java i.e. javac.exe.

Key Words are the building blocks of a Java Program. They are special words, which are
of significance to the Java compiler. Another fact about the Java Keywords is that they
cannot be used to name classes, variables or methods. The following table displays the
complete list of keywords in Java:

abstract Const implements import synchronized while


boolean false final instanceof private this
break continue finally int protected throw
byte default float interface public throws
case do for long return true
catch double goto native transient try
char else if short static void
class extends volatile short null super

The words goto and const are reserved. Even though they are
not keywords the programmers cannot use them.s

SR/JAVP1/301/1001/SC/3.0 21
Internet Programming Using Core Java – Part 1

Literals and constants

• Literals are values that may be assigned to a


primitive or string type variables
• The following are the various types of literals:
– Integer: stores numeric values
– Boolean: can be either true or false
– String: enclosed in double quotes e.g. “Java”
– Character: Can store a single character. Enclosed
in single quotes. For example ‘m’
– Floating-point: Stores numbers that have adecimal
fraction
• Comments describe the functionality of the
various methods included in the program.
Can be single line or double line.

Literals and Comments


The variables in Java can be assigned constant values. The values assigned must match
the data type of the variables. Literals are the values that may be assigned to primitive or
String type variables.

Ø The integer literals are numeric data. They can be represented as octal (representing
a number with 0 prefixed) or hexadecimal (representing a number 0x prefixed).
Ø The Boolean literals are either true or false. It cannot be represented by any other
values.
Ø String literals are enclosed in double quotes. For example ”Java”.
Ø Character literals are enclosed in single quotes. It can store a single character For
example ‘m’
Ø Floating- point literals are numbers that have a decimal fraction. The datatype of
floating point literals can be either float or double.

Assigning values to a variable or constant can be done during declaring the variable ( int
age =28) or anywhere else in the program.

<variable>=<value>

Examples

y=true ; //Boolean literals


y=1; //integer literals
y=2.3f //float literals

SR/JAVP1/301/1001/SC/3.0 22
Internet Programming Using Core Java – Part 1

y=’a’ //character literals


y = ”Java” //string literals.

Comments in Java

Like C or C++, we can use comments in a Java program. Actually, it is a healthy practice
to use comments in a Java program. With the help of comments we can describe the
functionality of the various methods that we include in our program. If a line is confined
within comments, the Java compiler simply ignores that particular line.

Comments that are inserted in a Java program can be of two types:

Ø //: Used for inserting a single line as a comment.


Ø /: Employed when the comment that we insert can span multiple lines.

SR/JAVP1/301/1001/SC/3.0 23
Internet Programming Using Core Java – Part 1

Operators

• Operators are of the following types:


– Arithmetic Operators: Performs arithmetic
operations
– Comparison Operators: Compares two data
values
– Assignment Operators: Assigns values to
variables
– Logical operators: Combines several expressions
and return a Boolean value.

Operators
We all know how to add two numbers. How do we achieve that? Obviously with the help
of PLUS (+) operator. Operators are used to compute values, and test multiple conditions.
In Java, operators are divided into the following categories:

Ø Arithmetic operators
Ø Logical operators
Ø Assignment operators
Ø Comparison operators

Arithmetic operator

Arithmetic operators are used for performing arithmetic operations like addition,
subtraction, multiplication and division. The following list is given below:

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

Modulus operator returns the remainder when we divide one integer with another.

SR/JAVP1/301/1001/SC/3.0 24
Internet Programming Using Core Java – Part 1

Comparison operators

Comparison operators are used for comparing two data values. The data values that are
being compared can either be variables, constants or expressions that are derived from the
following primitive datatypes defined in Java:

Ø Char
Ø Byte
Ø Short
Ø Int
Ø Long
Ø Float
Ø Double
The result of a comparison operator should always be either True or False. The
Comparison operators are primarily used for the purpose of decision making.

The table below lists the six Comparison operators provided by Java.

Operator Meaning
== Equal
!= Not Equal
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to

Assignment operators

Assignment operators are used for the purpose of assigning values to variables.
Assignment operators can be divided into unary and binary operators. As the name
suggests unary operators operate on one operand and the binary operators operate on two
operands. The unary assignment operators used in java are:

Operator Expression Meaning


+= A+=B A=A+B
-= A-=B A=A-B
*= A*=B A=A*B

SR/JAVP1/301/1001/SC/3.0 25
Internet Programming Using Core Java – Part 1

Operator Expression Meaning


/= A/=B A=A/B
= A=B A=B

There are two special assignment operators in Java called:

Ø Increment
Ø Decrement
The increment operator can be used in two ways:

1. As a prefix, in which the operator precedes the variable:

++iVar;

2. As postfix, in which the operator follows the variable:

IVar ++;

The following code segment will differentiate the two notations:

ivar1 = 5;
iVar2 = ++iVar1;

The same code could have been written in this format:

ivar1=5;
ivar1 = iVar1 + 1;
iVar2 = iVar1;

In this way both iVar1 and iVar2 are set to 6.

ivar1 = 5;
ivar2 = iVar1++;

The same code could have been written in this format:

SR/JAVP1/301/1001/SC/3.0 26
Internet Programming Using Core Java – Part 1

iVar1 = 5;
iVar2 = iVar1;
ivar1=iVar1 + 1;

In this way iVar1 will be set to 6 and iVar2 will be set to 5.

In the same way decrement operator can be used as both prefix and postfix operator.

Logical operators

Logical operators are used to combine several expressions that return a Boolean value
(i.e. either True or False). Since Logical operators operate on Boolean values, they are
also called Boolean operators . The table below lists the Logical operators provided in
Java.

Operator Represented as Explanation


It returns true if both the both the expressions being
AND &&
evaluated return true
It returns true if any of the expression being evaluated
OR ||
return true
NOT ! The value of NOT is negation of the expression

SR/JAVP1/301/1001/SC/3.0 27
Internet Programming Using Core Java – Part 1

Decision Constructs

• Determines the execution sequence of a program

• Enables conditional branching of a program.


• Decision -making in Java is performed with the help
of the following constructs:
– if..else
– switch..case

Decision Constructs

Any program is not made up of sequence only. It also involves some Decision making as
well. This also holds true even in our day to day life. For example if we are making a
plan for an outing, perhaps we will make it in this manner. If the weather is sunny then
only we will go for outing or we may arrange for some indoor games. If we are planning
to go for a movie, we make decision as to what movie we will watch.

Decision-making also exists in computer programs as well. Decision making in


programming determines the execution sequence of a program. We can go for conditional
branching of a program with the help of decision constructs. Decision construct will
allow us to selectively execute a part of the program depending upon a condition. For
example while opening a bank account we may provide two different forms for resident
and non-residents. Depending upon the nationality of the customer we will take a
decision regarding which is to be displayed.

Decision making in Java is facilitated by the following programming constructs:

Ø The if else construct


Ø The switch case Statement

SR/JAVP1/301/1001/SC/3.0 28
Internet Programming Using Core Java – Part 1

The if else Statement


• The syntax for if and else construct is as follows:
if(Boolean expression)
{
statements;
}
Or
if(Boolean statement)
{
statements;
}
else
{
statements }

The if else construct

The if … else construct executes a series of statements based on a condition that returns a
Boolean value. The general syntax of the if..else construct is as follows:

if (condition)
{
statements;
}
else
{
statements;
}

If the condition that is specified in the if statement evaluates to True then the statements
or the series of statement following the if clause will be executed. Otherwise, the
statements or the series of statements following the else clause will be executed. Let us
now try out the program given below:

class condition1
{
public static void main(String args[ ])
{
int x = 12;
if (x > 10)
System.out.println(“Number is greater than 10”);
else
System.out.println(“Number is less than 10”);
}
}

SR/JAVP1/301/1001/SC/3.0 29
Internet Programming Using Core Java – Part 1

In the above program we are trying to find out whether a particular number is less than or
greater than 10. For this purpose, we are declaring a variable x to which we are assigning
a value of 12. Next, the condition that is specified in the if statement is checking whether
the x is greater or less than 10. If this condition evaluates to True, then we are displaying
the message “Number is greater then 10”. Otherwise, the message “Number is less than
10 is displayed”.

In this case, since the value of x is 12, thus the message “Number is greater than 10 will
be displayed”.

There is another form of if…else construct that is enumerated below:

if (condition)
{
statements;
}
else if (condition)
{
statements;
}
else
{
statements;
}

In this case, if the condition specified in the if clause is not satisfied then the condition
stated in the else if clause is evaluated. If it evaluates to True then the program statement
or statement following the else if is executed. Otherwise, the statements enclosed by the
else will be executed.

The else clause is optional. If there are multiple statements that


are to be executed after the if, else if and the else clause, then
such statements should be enclosed within curly braces {}. In
case of a single statement, the curly braces are not required.

SR/JAVP1/301/1001/SC/3.0 30
Internet Programming Using Core Java – Part 1

The switch case Statement

The switch statements are shorthand for certain kind of if-else


statements. Usage is as follows:
switch(variable)
{
case value1:
statements;
break;
case value2:
statements;
break;
…………………..
default:
statements;
}

Switch case statement

Another decision construct that we can use in Java is the switch ... case. It is generally
used when there can be multiple conditions for the same parameter are available. For
example, the commissions given to the sales person depend upon the amount of sale they
have made. Thus, there is a single parameter that is the amount of sales made by the sales
staff and this parameter can contain multiple values. Say, if the Sale made per annum is
less than 50,000 no commission will be given. If the sale value is between 50,000 and
1,00,000 then the commission will be 3% of the total Sale value per annum, if the sale
value is between 1,00,000 and 1,50,000 then commission rate will be 5% of the total sale.
The switch statement successively tests the value of an expression against a list of ni teger
or character constants. When a match is found, the statements associated with the case
constant are executed.

The syntax of the switch..case construct is as follows:

Syntax:

Switch ( variable_name )
{
case expression1:
statements;
break;
case expression2:
statements;
break;
default:
statements;
}

SR/JAVP1/301/1001/SC/3.0 31
Internet Programming Using Core Java – Part 1

The keyword switch is followed by the variable in parenthesis.

switch ( iday );

Each case keyword is followed by a case constant which are actually the possible values
that the variable can contain:

case 1:

The data type of the case constant should match with switch variable. Before entering the
switch construct, a value should be assigned to the switch variable. Let us now attempt to
develop a program which will enable us to understand the usage of switch...case
construct more clearly.

The break statement causes the program flow to exit from the body of the switch
construct.

class SwitchConstruct {

public static void main (String args[]) {

int iDay = 2;

switch ( iDay )
{
case 1:
System.out.println ( “Monday” );
break;

case 2:
System.out.println ( “Tuesday” );
break;

case 3:
System.out.println ( “Wednesday” );
break;

case 4:
System.out.println ( “Thursday” );
break;

case 5:
System.out.println ( “Friday” );
break;

SR/JAVP1/301/1001/SC/3.0 32
Internet Programming Using Core Java – Part 1

case 6:
System.out.println ( “Saturday” );
break;

case 7:
System.out.println ( “Sunday” );
break;

default:
System.out.println ( “Invalid value” );
}
}
}

The above program will print the day depending upon the value contained in the variable
iValue.

Since, iValue contain a value 2 thus the above program will print “Tuesday”.

The break statement

The break statement causes the program flow to exit from the body of the switch
construct. Control goes to the first statement just following after the switch construct. If
the break statement is not used the control passes to the next case statement and the
remaining statements in the switch construct are executed. For example in the previous
example if we don’t give the break statement and the variable iValue contains a value 2
then it will print “Tuesday”, “Wednesday”, “Thursday”, ”Friday”, “Saturday” and
“Sunday”, “Invalid Value”.

The default Keyword

The statements associated with default are executed if value of the switch variable does
not match any case constants. In the above example if the variable iValue contains any
value other than 1 to 7 the program will print “Invalid value”.

The case expression expressions can be either numeric or


character data type.

SR/JAVP1/301/1001/SC/3.0 33
Internet Programming Using Core Java – Part 1

Iteration or Loop constructs

• Causes a section of a particular program to


be repeated for a certain number of times.
• Following loop constructs are supported in
Java:
– while loop
– do..while loop
– for loop

Iteration or the Loop Construct


We have already learnt conditional execution. A program has another attribute –
Iteration. Lets now discover this feature of Java program.

If a particular portion of the code has to be executed repeatedly, then instead of writing
the code that many times, we use a loop construct. A loop cause a section of a particular
program to be repeated certain number of times. The repetition continues while the
condition set for it remains true. When the condition becomes false, the loop ends and the
control is passed to the statement following the loop.

Java supports the following Loop constructs:

Ø The while loop


Ø The do..while loop
Ø The for loop

We will learn about each of the Loop constructs in detail in the subsequent three topics.

SR/JAVP1/301/1001/SC/3.0 34
Internet Programming Using Core Java – Part 1

The while loop

The statements given in the while loop executes as long as the


Boolean expression is true. The syntax is:

while(Boolean expression)
{
statements;
}

The loop executes only if the expression is true from the very
first time.

The while loop

Among many looping constructs available in Java, while loop is one of them. The while
loop continues until condition specified with the while loop becomes false. The condition
specified in while loop has to be a logical expression and must return a true or false value.
The variable that is checked in the Boolean expression is called the loop control variable.

while (boolean_expression)
{
statements;
}

Whatever statements we will write within the two braces of the while construct will
continue to be executed until the Boolean expression becomes false.

The example given below illustrates the usage of the while loop:

class whileLoop
{
public static void main (String args[])
{
int n=10;
while (n>0)
{
System.out.println(“Value of n is: ”+n);
n = n – 1;
}
System.out.println(“Outside the while loop”);

SR/JAVP1/301/1001/SC/3.0 35
Internet Programming Using Core Java – Part 1

}
}

In the above program, the condition tested by the while loop is evaluating whether the
value of 10 is greater than 0 or not. As long as this condition evaluates to true, the
statements enclosed by this loop will continue to be executed. The moment the value of
variable n becomes equal to 0 the condition by the while loop will evaluate to false. As a
result the program control will come out of the loop and the statement immediately
following it will be executed.

The output of the above program is:

Value of n is: 10
Value of n is: 9
Value of n is: 8
Value of n is: 7
Value of n is: 6
Value of n is: 5
Value of n is: 4
Value of n is: 3
Value of n is: 2
Value of n is: 1
Outside the while loop

SR/JAVP1/301/1001/SC/3.0 36
Internet Programming Using Core Java – Part 1

The do - while loop

• The syntax for the do-while loop is:


do
{
statements;
}while(Boolean expression);
• The difference between the while loop and the
do-while loop is that the statement of the do-
while loop always executes at least once, even
if the expression evaluates to false.

The do-while loop


In some cases, it is desirable to execute the body of a loop at least once, even if the
Boolean expression returns false the very first time. In such cases, we make use of the
do..while loop. In a do-while loop the condition is tested at the end of the loop rather
than the beginning.

The general syntax of the do while loop is as follows:

do
{
statements;
} while(condition);

The following is an example of the do while statement:

class condition3 {
public static void main(String args[ ])
{
int n=10;
do
{
System.out.println (“Value of n is:” + n);
} while (--n > 0);
System.out.println(“Outside the do..while loop”);
}
}

The output of the above program is same as the one shown for the while loop.

SR/JAVP1/301/1001/SC/3.0 37
Internet Programming Using Core Java – Part 1

The for loop

• The for loop structure consists of 3 different


steps which are:
for(initialization ; body expression : re-
initialization)

The for loop

The for loop executes a set of statements for certain number of times until the condition is
matched. The general syntax for the for loop:

for (initialization ; condition ; expression)


{
statements;
}

The for loop contains three parts and the use is:

initialization: to initialize a variable


condition: to test a condition, it returns a Boolean value
expression: is used for increment or decrement the value of variable

The following is an example of the for loop:

class generateNum {
public static void main(String args[]) {
for ( int x = 1;x<=15;x++)
{
for(int y=1;y<=x;y++)
{
System.out.print(y);
}
System.out.print("\n");
}
}
}

SR/JAVP1/301/1001/SC/3.0 38
Internet Programming Using Core Java – Part 1

The output of the code is

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Example:

The following example illustrates the how to give label in a program and the use of
continue key word.

class conlabel{
public static void main(String args[]){
outer: for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if( j > i){
System.out.println();
continue outer;
}
System.out.print(" " + (i*j));
}
}
System.out.println();
}
}

In the above example the first for loop has a label outer and it is called from the inner
loop using the continue key word.

The output of the above program is:

SR/JAVP1/301/1001/SC/3.0 39
Internet Programming Using Core Java – Part 1

Example:-

The following is a simple example of nested for loop:

class factorial {
public static void main (String args[]) {
long ctr = 15;
long factorial = 1;
for (int i = 1; i <= ctr; i++)
{
factorial = 1;
for (int factor = 2; factor <= i; factor++)
factorial = factorial * factor;
System.out.println (“"Factorial of " + i + " is " +
factorial);
}
}
}

In the above program, we are trying to find out the factorial of numbers upto 15. We are
declaring two long variable ctr and factorial and initializing them with values 15 and 1
respectively. Next, the statement enclosed within the outer for loop will continue to be
executed until its value remains less than or equal to 15. Within this outer for loop we are
reinitializing the value of variable, factorial to 1. Thereafter, we are executing the inner
for loop, which ascertains the factorial of the current value of i using the variable factor
as the counter, which spans from 2 to the current value of i.

The output of the above program is as follows:

SR/JAVP1/301/1001/SC/3.0 40
Internet Programming Using Core Java – Part 1

SR/JAVP1/301/1001/SC/3.0 41
Internet Programming Using Core Java – Part 1

Arrays in Java

• An Array is a group of like-type


variables that are referred by a common
name.It is a means of storing data in an
indexed manner.

Arrays in Java
We have learnt that if we have to store values that are to be used in a program, we have to
use store such values in variables. However, the primitive datatypes in Java has the
capability to store a single value. This sometimes can cause problems while creating
programs in Java with the help of primitive datatypes.

Say, there is a necessity to store the marks obtained by 50 students in a class. In order to
do so, we can declare 50 integer variables. This is a Herculean task by any standard.

Hence, it helps us if there is some mechanism to accept all the 100 names in just one
variable.

Arrays are the answer to our wish. They play a very important role in developing
programs when large numbers of variables are involved.

An array is a collection of elements having the same data type with the same name,
occupying contiguous spaces in memory. The values that are stored in an array are
known as array elements. An array element can be uniquely identified by its relative
position from the beginning of the array, which is known as index. In programming
parlance, an index is an integer value of type int. The index of the first element of an
array is 0. Let us consider an array named num where we shall store 6 numbers.

15 16 17 18 19 20

ß------------------- num -------------------------à

Thus, in the num array the array element at index 0 is 15, at index 1 is 16, index 2 is 17
and so on.

SR/JAVP1/301/1001/SC/3.0 42
Internet Programming Using Core Java – Part 1

Declaration and Memory allocation of a Single dimensional Array

To create an array, the type has to be specified. The syntax of declaring a one-
dimensional array is:

type var-name[];or type[] var-name;

Ø Type denotes the dataype of the array


Ø var_name is the name assigned to the array
Ø Brackets are required to be specified after the array name to indicate the existence
of an array.

Memory allocation for an array is done with the help of the new operator. We will in
details about the new operator in the subsequent chapter when we will learn about classes
and objects. However, for now we will have to remember that the new operator is used
for the purpose of allocation of memory during runtime. Memory allocation for an array
is performed in the following manner:

var-name[ ] = new type[size];

In the syntax illustrated above, type signifies the datatype of the elements that will be
stored in the array. Size signifies the number of elements that will be stored in the array.

In the example illustrated below, we will declare an array called num_array that will
store six integer values of datatype int.

int num_array[];
num_array = new int [6];

Array declaration and memory allocation can be performed in one single step as shown
below:

int num_array[] = new int [6];

Once you have allocated an array, we can access or assign values to the specific elements
of the array by using the array name combined with the index of the particular array
element.. For example, to display the 4th element of the num_array we use the following
command:

SR/JAVP1/301/1001/SC/3.0 43
Internet Programming Using Core Java – Part 1

System.out.print(num_array [3]);

Initialization of Single-dimension Arrays

Initialization of an array can also be done when they are declared. An array initializer is
a list of comma-separated expressions surrounded by curly braces. The commas separate
the values of the array elements. In this case, the new keyword is not required. For
example:

int num_array [] = {10,20,30,40,50,60}

char c[]={‘a’,’b’,’c’,’d’}

Values can also be assigned to each element of a single dimensional array as shown
below:

num_array [0] = 10;


num_array [1] = 20;
num_array [2] = 30;
num_array [3] = 40;
num_array [4] = 50;
num_array [5] = 60;

Let us now develop which will enable us to get a better grasp on single-dimensional
array.

class SingleArray {
public static void main (String args[]) {
int number_array [] = {10,30,50,70,90,110};
int result = 0;
for (int ctr = 0; ctr < 6; ctr++)
result = result + number_array [ctr];
System.out.println ("Sum of the array elements is : " +
result);
}
}

In the above program, we are trying to ascertain the sum of the elements that are stored in
the array number_array. The output generated will be as follows:

Sum of the array elements is: 360

SR/JAVP1/301/1001/SC/3.0 44
Internet Programming Using Core Java – Part 1

Multidimensional Arrays

In Java, multidimensional arrays are actually array of arrays. To declare a


multidimensional array, we have to specify an additional index using another set of
square brackets. For example:

int num[][] = new int[4][5];

In this case the array num will have 4 rows and each row will contain 5 columns. The
index on the left-hand side indicates the rows of the num array whereas the index on the
right-hand side indicates the number of columns that each row will contain. The figure
given below will illustrate to us how the array num will look like.

(0,0) (0,1) (0,2) (0,3) (0,4)


(01) (1,1) (1,2) (1,3) (1,4)
(0,2) (2,1) (2,2) (2,3) (2,4)
(0,3) (3,1) (3,2) (3,3) (3,4)

While allocating memory for a multidimensional array, we have to specify only the
memory for the first dimension ed. The remaining dimensions can be allocated
separately.

For example:

int num[][] = new [4][ ];


num[0]=new int[5];
num[1]=new int[5];
num[2]=new int[5];
num[3]=new int[5];

The dimensions can be different for each row.

For example, if you want to store one element in the first row, two elements in the second
row, three elements in the third row and four elements in the fourth row, then you can
declare the array like this:

num[0]=new int[1];
num[1]=new int[2];
num[2]=new int[3];
num[3]=new int[4];

SR/JAVP1/301/1001/SC/3.0 45
Internet Programming Using Core Java – Part 1

The example given in the following page illustrates the usage of two-dimensional array.
In this program we are initializing and displaying the elements of a two-dimensional
array called twoarray that contains four rows of five columns each. The initialization and
the display part is performed within a for loop.

class MultiArray {
public static void main (String args[]) {
int twoarray [][] = new int [4][5];
int x, y, z;
z = 0;
for (x = 0; x < 4; x++)
{
for (y = 0; y < 5; y++)
{
twoarray [x][y] = z;
z++;
}
}

for (x = 0; x < 4; x++)


{
for (y = 0; y < 5; y++)
System.out.print (twoarray [x][y] + " ");
System.out.println();
}
}
}

The output of the above program is:

0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

Let us try out another program on two-dimensional arrays. In the program that is
illustrated below, we have declared a two-dimensional array of varying length named td.
This array has got four rows, but the number of its columns varies. The first row can hold
one element, the second row can hold two elements, the third row can hold three
elements and the fourth row can hold four elements. The functionality of this program is
the same as the previous one.

class twoD {
public static void main(String args[])
{
int td[][] = new int[4][];
td[0] = new int[1];
td[1] = new int[2];

SR/JAVP1/301/1001/SC/3.0 46
Internet Programming Using Core Java – Part 1

td[2] = new int[3];


td[3] = new int[4];

int i,j,k = 0;

for( i=0;i<4;i++)
for (j=0;j<i+1;j++)
{
td[i][j] = i*j*k
k++;
}// end of for loop

for (i=0;i<4;i++)
{
for(j=0;j<i+1;j++)
System.out.print(td[i][j] + " ");
System.out.println();
}//end of for loop
}//end of main
}// end of class

The output of the program is as follows:

0
0 2
0 8 20
0 21 48 81

SR/JAVP1/301/1001/SC/3.0 47
Internet Programming Using Core Java – Part 1

Quiz

• Write a Java program that will display the first


100 numbers (I.e.from 1 to 100).
• Write a Java program to display the first 100
odd numbers
• What is the difference between Java and
C++.
• When do we use the do..while loop

Quiz

SR/JAVP1/301/1001/SC/3.0 48
Internet Programming Using Core Java – Part 1

Exercise

Q1) State whether the following are true or false:

A. The default case is required in the switch selection structure.


B. The break statement is required in the default case of a switch selection structure.
C. The expression (x > y && a < b) is true if either x > y is true or a < b is true.
D. An expression containing the || operator is true if either or both of its operands is
true.
E. An array can store many different types of values.
F. An array subscript should normally be of data type float.
G. An array declaration reserves space for the array.

Q2) Find the errors in each of the following code segments and explain how to correct
it.

x = 1;

while (x <= 10);


x++;
}

for (y = .1; y != 1.0; y += .1 )


System.out.println ( y );

The following code should output the even integers from 2 to 100:

Counter = 2;
do {
System.out.println ( counter ) ;
counter += 2;
} While ( counter < 100 );

The following code should print whether integer value is odd or even:

switch ( value % 2 ) {

case 0:
System.out.println ( “Even integer” ) ;

case 1:
System.out.println ( “Odd integer” );
)

SR/JAVP1/301/1001/SC/3.0 49
Internet Programming Using Core Java – Part 1

Q3) Fill in the blanks in each of the following:

A. A _______ is a special method used to initialize the instance variables of a class.


B. The keyword ________ introduces a class definition.
C. The _______ type modifier implies that the subclasses will no longer be allowed
to override your variables or methods.
D. To initialize the static variables, a _______________ can be declared.
E. The ______________ keyword is used to signify that the class is a subclass of the
superclass superclassname.
F. The _______________ package contains the Object class.
G. The ______________ operators allow manipulation of individual bits.
H. The JVM interprets the ___________ into native codes.
I. A method declared static cannot access ________ class members.
J. The keyword ________ specifies that an object or variable is not modifiable after
it is initialized.

SR/JAVP1/301/1001/SC/3.0 50
Internet Programming Using Core Java – Part 1

Summary
• Appreciate the evolution of Java as a
programming language
• Learn about the features of Java
• Develop, compile and run a simple Java
program
• Recognize different datatypes
• Know about literals and keywords
• Implement decision-making and loop
constructs in a Java program
• Implement the concept of Arrays in a Java
program

Summary

At the end of this chapter, you are now able to:

Appreciate the evolution of Java as a programming language


Learn about the features of Java
Develop, compile and run a simple Java program
Understand the concept of variables
Recognize the different Datatypes
Know about literals and keywords
Implement decision-making & loop constructs in Java program
Implement the concept of arrays in a Java program

SR/JAVP1/301/1001/SC/3.0 51
Internet Programming Using Core Java – Part 1

Java Class Concepts


Objectives:
• Define and declare a class
• Define and declare methods within a class.
• Learn how to define and declare different
types of constructors in a class
• Appreciate method overloading and method
overriding and understand the difference
between the two
• Develop Java programs that implement the
concept of Inheritance
• Learn about abstract and final members of a
class

Java Class Concepts

At the end of this chapter, you will be able to

Define and declare a class


Define and declare the members of a class
Learn how to declare and define different types of constructors in
a class
Appreciate method overloading and method overriding and
understand the difference between the two
Develop Java programs that implement the concept of
Inheritance
Learn about abstract and final members of a class.

SR/JAVP1/301/1001/SC/3.0 52
Internet Programming Using Core Java – Part 1

Defining a class

• A class is a template for an object. It defines


the attributes and behavior of an object.
• An object is defined as an instance of a class.
• During defining a class we have to define its:
– Fields
– Methods

Defining a Class

Java is a purely object oriented language. We have already seen that in a Java program
every single piece of code is written inside a class definition. So much so that we even
write the main () method in Java within a class definition. This is a unique feature in
java. In C++, the other popular object-oriented language, the main () method is written
outside the class definition. Besides, some of the important features of OOPS (such as
Inheritance, Polymorphism and Abstraction) are also implemented in Java Programs.

The class is the core of Java. It is the logical construct upon which the entire Java
language is built because it defines the shape and the nature of an object. Any concept
that we wish to implement in a Java program must be encapsulated within a class.

In the real world, we often have seen many objects of the same kind. For example, that an
Television that an individual owns is just one of many televisions in the world. Using
object-oriented terminology, we say that a particular television set is an instance of the
class of objects known as Television. All televisions have some characteristics (screen
size, model no, weight, no_of_speakers) and behavior (change color, change contrast,
channel scan) that are in common. However, each television's state is independent of and
can be differentiated from another television.

Manufacturers take advantage of the fact that televisions share the same characteristics.
When manufacturing televisions, manufacturers design a blueprint and manufacture
many televisions from the same blueprint--it would be very inefficient to produce a new
blueprint for every individual television they manufacture.

Therefore a class is a template or blueprint for an object and an object is the instance of
a class. Because an object is an instance of a class so the two words objects and classes
are used interchangeably.

SR/JAVP1/301/1001/SC/3.0 53
Internet Programming Using Core Java – Part 1

Declaring a Class in Java

Now from the above description we can define a class. A class is a template of objects
having common attributes (characteristics) and behavior. To define a class in Java the
syntax is:

class <class_name>
{
// Statements
}

We can see from the above syntax that each class will have a name. When we are naming
a class it is mandatory for us to follow certain rules and conventions. The following are
such rules:

A class name:

Ø Must not be a keyword in Java.


Ø Can begin with a letter, an underscore '_' or a '$' symbol.
Ø Must not contain embedded spaces or period ('.') .
Ø Can contain characters from different alphabets like Japanese, Greek, Cyrillic and
Hebrew

Apart from the above rules it is a good programming practice to ensure that the first letter
of the class should be in upper case.

Data Members

The data, or variables, defined within a class are called Data Members or Instance
Variable. The coding of the class is contained within methods. The methods and the
variables that are defined are collectively called class members . In most classes, the
instance variables are acted upon and accessed by the methods defined for that class.

When we try to describe a television we speak about its physical attributes such as color,
dimension, screen size, no. of speakers etc. All these attributes are the data members of
class Television. They are defined within the class as variables and are also called
instance variable.

The syntax for declaring a data member is:

<Datatype > < variablename >;

SR/JAVP1/301/1001/SC/3.0 54
Internet Programming Using Core Java – Part 1

While declaring data members for a particular class, the following must be ensured:

Ø The < datatype > is mandatory and can be any Java data type, depending upon the
kind of data to be stored.
Ø The < variablename > is mandatory. The variable name must adhere to the variable
naming rules discussed in the last chapter.

The following code demonstrates how to declare a class.

class Cube{

int length;

int breadth;

int height;

In the above code snippet, we have declared a class called Cube, which has three
instance variables called length, breadth and height. The datatype of all the three
instance variables of Cube class is int, which is a primitive datatype in Java.

SR/JAVP1/301/1001/SC/3.0 55
Internet Programming Using Core Java – Part 1

Declaring Objects in Java


• An object is an instance of a class
• Creation of an object is a two step process:
– Creating a variable of the class type
– Creation of a physical copy of the object using the
new operator.
• The syntax for creating an object is:
Object object_name;
object_name = new object ();
or
Object object_name = new Object ()
• The variable and methods of an object are
members .
• The members of an object are accessed with
the help of a dot (.) operator as shown below:
object_name.member

Declaring Objects in Java

When we create a class, we are actually creating a new data type (an abstract datatype
about which we have already learnt in the first chapter). We can utilize this abstract
datatype to declare objects belonging to that type. So, after we have created the Cube
class, we must instantiate (i.e. instantiate is the process of creating an object of that
class) it before it can be used. When you create an instance of a class, you create an
object of the abstract datatype that the class defines and the system allocates memory for
the instance variables declared by the class.

Obtaining objects of a class is a two-step process. First, we need to declare a variable of


the class type. However, at this stage the variable yet does not define any object.
Declaring a class type variable only implies that this variable has the capability to refer to
an object of that class. The next step is the creation of the physical copy of the object.
This is done using the new operator. The new operator dynamically (during runtime)
allocates memory for an object and returns the address of the memory allocated for that
object (known as reference), which is then assigned to the variable of class type. This
reference is the address of the memory allocated for the object.

The following syntax demonstrates how to declare an object of a class

Cube myCube;
myCube = new Cube();

The first line of the above syntax declares a variable called myCube whose type is Cube.
At this point of time, myCube does not define an object of class Cube. This is done in
the second line of the syntax. At this line, a physical copy of an object of Cube class is

SR/JAVP1/301/1001/SC/3.0 56
Internet Programming Using Core Java – Part 1

created and the address of the memory allocated for it by the new operator is assigned to
myCube.

The above two lines of code can be combined in one line as illustrated below:

Cube myCube = new Cube ();

Let us now develop a program where we will implement the concept of objects and
classes.

class Cube {
int length;
int breadth;
int height;
}

class CubeVolume {
public static void main (String args []) {
Cube myCube = new Cube ();
myCube.length = 20;
myCube.breadth = 20;
myCube.height = 20;
int volume = myCube.length * myCube.breadth *
myCube.height;
System.out.println ("The volume of the cube is : " +
volume);
}
}

In the above program, we are declaring a class called Cube about which we have already
discussed in the previous topic. Within the main () method, we are constructing an object
of class Cube and storing its reference in the variable myCube of type Cube.

Let us particularly on the following three lines of code:

myCube.length = 20;
myCube.breadth = 20;
myCube.height = 20;

In the above code segment, we are initializing the instance variables of class Cube. In
order to access the instance variables of a class from outside that class we have to take
the help of the dot (.) operator. The dot operator links the instance variable of a class
with the object reference type variable (the variable that contains the reference of an

SR/JAVP1/301/1001/SC/3.0 57
Internet Programming Using Core Java – Part 1

object belonging to the class). Thus, in order to initialize the instance variable length we
have used the following line of code

myCube.length = 20;

When the Java compiler encounters the above statement, it assigns the value 20 to the
copy of the instance variable length, which exists within the object referred to by
myCube.

The dot (.) operator is used to access both the instance variables
and the methods of the object.

The source file that contains the program we have just developed should be called
CubeVilume.java because the main () method is contained within the class
CubeVolume. When the CubeVolume.java file is compiled then it will result in the
creation of the following two .class namely:

Ø Cube.class
Ø CubeVolume.class

It is also possible to create two source files called Cube.java and CubeVolume.java.

The output of the above program is :

The volume of the cube is : 8000

The instance variables that are declared within a class are copied into each object that is
declared for that class. Thus if we declare another object of the Cube class then it will
have its own copy of the instance variables length, breadth and height. Thus, if we
make changes to the instance variables of one object of Cube class, it will not have any
effect on another object of the same class. The program given below illustrates this.

SR/JAVP1/301/1001/SC/3.0 58
Internet Programming Using Core Java – Part 1

class Cube {
int length;
int breadth;
int height;
}

class CubeVolume {
public static void main (String args []) {
Cube myCube1 = new Cube ();
Cube myCube2 = new Cube ();
myCube1.length = 10;
myCube.breadth = 10;
myCube.height = 10;
int volume = 0;
volume = myCube1.length * myCube1.breadth *
myCube1.height;
System.out.println ("The volume of the second cube is
: " + volume);
myCube2.length = 20;
myCube2.breadth = 20;
myCube2.height = 20;
volume = myCube2.length * myCube2.breadth *
myCube2.height;
System.out.println ("The volume of the second cube is
: " + volume);
}
}

The output of the above program is :

The volume of the first cube is : 1000


The volume of the second cube is : 8000

SR/JAVP1/301/1001/SC/3.0 59
Internet Programming Using Core Java – Part 1

Methods

• Methods are the functionality exhibited by an


object
• Declared inside a class
• Syntax for declaring a method is:
<returntype> < method_name > (parameter_list )
{
// Statements
}
• The name of a method should not match with
a keyword in Java’
• Can begin with a letter, underscore or a dollar
sign and should not contain embedded
spaces or period

Methods

Methods are the functionality exhibited by the object. These methods are described in the
class, the designing template of object.

When we are describing a television set we would also like to list the functionality it
provides like brightness, contrast, volume, on/off and channel_select. The brightness and
contrast methods increase or decrease the brightness or contrast of the picture whereas
the channel_select method allows us to select a channel of our choice and returns the
channel number.

The syntax for declaring a method is:

<returntype> < method_name > (parameter_list )


{
// Statements
}

In the above syntax, method_name is the name of the method, returntype is the datatype
of the value that is being returned by the method and parameter_list is the list of
parameters that are passed as arguments to the method. We will discuss about return type
and parameters of a method a little later.

The following rules must be complied with while declaring a method:

Ø Must not be a keyword in Java.


Ø Can begin with a letter, an underscore '_' or a '$' symbol.

SR/JAVP1/301/1001/SC/3.0 60
Internet Programming Using Core Java – Part 1

Ø Must not contain embedded spaces or period '.' .


Ø Can contain characters from different alphabets like Japanese, Greek, Cyrillic and
Hebrew

The following are conventions that should be followed while naming methods:

Ø Method names should start with verbs followed by nouns. For example,
dispalayColor().
Ø If a method name consists of two or more words then join the words. The first word
should start with lower case, but the subsequent words should start in upper case. (e.g.
acceptEmployeeDetails( ), displaySalary( ).
Ø A method name must be meaningful.

In the Cube class that we have developed earlier, there are three instance variables
(length, breadth and height) and no methods. Though this is perfectly legal, it is not a
good programming practice. In most cases, methods provide the interface to the data that
are declared within a class. This enables the programmer to hide or encapsulate the
internal data structure of the class behind the methods so that they are not illegally
tampered with. Also, if a class does not contain any methods then any change in the data
structure of the class will require changing the program (outside that class), which access
those data structures. But if the access to the instance variables is controlled through
methods then any change in the instance variables will only warrant modifications to be
made to the methods. There will be no need to modify the programs that access those
methods.

In the CubeVolume.java file we have set the values of the instance variables of the
Cube class from the main method (i.e. from outside the Cube class). However, we have
just learnt that it is a unhealthy practice. Again the volume of the cube represented by the
Cube class is being calculated within the main () method. Again, this is cumbersome
program. Suppose, another class wants to obtain the volume of the cube, in such a
situation it has to again recalculate the volume. This will result in writing the same line of
code multiple times, which in turn will result in wastage of time and effort.

Now that we have understood the necessity and importance of methods in a class, let us
discuss about the two other important aspects of methods, namely :

Ø Passing arguments to a method


Ø Returning values from a method

SR/JAVP1/301/1001/SC/3.0 61
Internet Programming Using Core Java – Part 1

Passing arguments to methods

Methods within a class that accept arguments accomplish the assigned tasks on the basis
of those arguments. Take the example of Bookshop. The bookshop owner can only sell to
the customer after the customer specifies his choice in this regard. So, in order to
successfully complete the transaction of selling a book the shopkeeper requires an
information in the form of the name of the book from the customer. Therefore, if we
consider the act of selling a book as a method then the information that is passed in the
form of name of a book by the customer is called as an argument to the method.

An argument can be defined as a value or a variable that is


passed to a called method when it is invoked from the caller
method. On the other hand, a parameter signifies the variable
defined by the called method, which receives the argument when
the called method is invoked.

In the parlance of object-oriented programming, we can consider a bookshop as a class.


In this case, the act of selling a book represents a method and we will name this method
as sellBook (). The following code snippet illustrates this in a programmatic form:

class BookShop
{
void sellBook(String bkname)
{
System.out.println("The book name is" + bkname);
}
}

In the above code snippet, the method is declared void because it does not return any
value. We will learn about the methods that can return values in the next topic. The
parameter (String bkname) to the sellBook () method has been declared to be of datatype
String. String is an abstract datatype that Java provides. We will learn about String in
the latter part of this chapter.

We have already learnt the problems associated with developing classes without any
methods in them. So we will now modify the Cube class and to it a method that will set
the values of its instance variables (namely length, breadth and height). The modified
program is shown in the following page:

SR/JAVP1/301/1001/SC/3.0 62
Internet Programming Using Core Java – Part 1

class Cube {
int length;
int breadth;
int height;

void setCube (int l, int b, int h) {


length = l;
breadth = b;
height = h;
}
}

class CubeVolume {
public static void main (String args []) {
Cube myCube1 = new Cube ();
Cube myCube2 = new Cube ();
myCube1.setCube (10, 10, 10);
myCube2.setCube (20, 20, 20);
int volume = 0;
volume = myCube1.length * myCube1.breadth *
myCube1.height;
System.out.println ("The volume of the first cube is :
" + volume);
volume = myCube2.length * myCube2.breadth *
myCube2.height;
System.out.println ("The volume of the second cube is
: " + volume);
}
}

Like instance variables, in order to access a method defined within a class from another
class, we have to specify the name of the object belonging to the class and the name of
the method separated by the dot (.) operator. Thus in order to access the setCube ()
method from the CubeDemo class we have to use the following statement:

myCube1.setCube (10, 10, 10);

When the above statement is executed, the control of the program is transferred to the
setCube () method of the Cube class, which is then executed. The arguments specified in
the above statement is copied into the parameters defined by the setCube () method (l, b
and h). These parameters are then used to initialize the instance variables of the Cube
class.

There are two ways of passing arguments to a method:

SR/JAVP1/301/1001/SC/3.0 63
Internet Programming Using Core Java – Part 1

Ø Call by Value
Ø Call by Reference

Call By Value

In Java, all arguments that are of primitive data types (byte, short, int, long etc.) are
passed by value. The called method gets a copy of the argument passed by the caller. So
any change made to the variable/object of the called method is not reflected in the caller.

void caller()
{
int send=10;
called(send);
System.out.println(send); // prints 10 on the
screen
}
void called(int receive)
{
receive=20;
}

In the above example a copy of the argument's value (i.e., the value of the variable send)
is passed to the parameter of the called () method, which is maintained in a separate
memory location (variable receive). So when the called () method changes the value of
the argument (variable receive) and stores a value of 20, the change is not reflected in the
caller () method. The variable send still contains the value 10 because they are in
different memory location.

The following is a complete program that illustrates passing of arguments by value:

class DemoClass {
int inum1;
int inum2;

void setValue(int a, int b) {


int inum1 = a * 2;
int inum2 = b * 2;
}
}

class CallByValueTest {
public static void main (String args []) {
DemoClass dm = new DemoClass ();
int x =10;

SR/JAVP1/301/1001/SC/3.0 64
Internet Programming Using Core Java – Part 1

int y = 20;
System.out.println ("The value of x and y before
invoking setValue () : " + x + " " + y);
dm.setValue (x, y);
System.out.println ("The value of x and y after
invoking setValue () : " + x + " " + y);
}
}

The output of the above program is :

The value of x and y before invoking setValue () : 10 20

The value of x and y after invoking setValue () : 10 20

In the above program, we can see that the values of the variable x and y that is passed as
arguments to the setValue () remain unaffected irrespective of the modification that is
taking place inside the setValue () method.

Call By Reference

Arguments, which are objects of classes, when passed as arguments, are passed by
reference to the called method. This means any change made to the object in the called
method is reflected in the caller also. When passing objects as arguments to methods, we
actually pass the variable that stores the object reference. Thus, the parameter that
receives this object reference will also refer to the same object.

Thus changes made to the instance variable inside the called method will be affect the
accordingly affect the object that is passed as an argument.

class Employee
{
String empName;

void called(Employee receive)


{
receive.empName="Ellis";
}
}

class TestCallByRef {
public static void main (String args []) {

Employee send=new Employee();


send.empName="John";
System.out.println (send.empName);

SR/JAVP1/301/1001/SC/3.0 65
Internet Programming Using Core Java – Part 1

send.called(send);
System.out.println(send.empName); // prints "Ellis" on the
screen
}
}

Let us understand the above code. Employee class contains a data member of String data
type named empName. An object of the said class is created in the another class named
TestCallByRef. In the TestCallByRef class the object (send) is created and its instance
variable empName is initialized with the value “John”. This object is then passed to the
called () method of the Employee class. Since its an object, the address (reference) of the
argument's variable is passed to the called() method. Here both the objects (send and
receive) are referring to the same address space. Therefore when the called () method
changes the value of the argument, the change is reflected in the caller () method also.

Returning values from methods

We have already seen that a method's return type is specified in the method declaration.
Within the body of the method, we use the return operator to return a value from a
method. Any method that is not declared void must contain a return statement. The data
type of the return value must match the method's return type i.e. we cannot return an
Object type from a method declared to return an integer.

In the Cube class that we have created, we are calculating the volume of the cube outside
the Cube class. We have already established the fact that this is not a good programming
practice. So let us add a method called calcVolume () that will perform this job.

class Cube {
int length;
int breadth;
int height;

void setCube (int l, int b, int h) {


length = l;
breadth = b;
height = h;
}

int calcVolume () {
return length * breadth * height;
}
}

class CubeVolume {
public static void main (String args []) {
Cube myCube1 = new Cube ();
Cube myCube2 = new Cube ();

SR/JAVP1/301/1001/SC/3.0 66
Internet Programming Using Core Java – Part 1

myCube1.setCube (10, 10, 10);


myCube2.setCube (20, 20, 20);
int volume = 0;
volume = myCube1.calcVolume ();
System.out.println ("The volume of the first cube is :
" + volume);
volume = myCube2.calcVolume ();
System.out.println ("The volume of the second cube is
: " + volume);
}
}

We can see that the calcVolume () method of the Cube class is returning the volume of
the cube. In order to invoke this method, we are declaring a int variable called volume.
This variable is plced on the right hand side of the following assignment statement and
the invocation of the calcVolume () method is placed on the right hand side.

volume = myCube1.calcVolume ();

When the above program statement is executed, the calcVolume () method will be
invoked and the volume will be calculated and stored in the variable volume.

The datatype of the variable, which receives the value returned


by a method, should be compatible with the return type of the
method.

SR/JAVP1/301/1001/SC/3.0 67
Internet Programming Using Core Java – Part 1

Constructor
• Constructor is a method, which initializes
automatically when an object is created. It
has the same name as the class name.
• Constructors do not possess a return type.
• There are two types of constructors:
– Default
– Parameterized: Has the capacity to accept
arguments
• If the user has not defined a constructor then
Java defines a default constructor with no
parameter and an empty body

Constructor
When we create objects, each object contains a set of all the data members defined in the
class. So it becomes necessary to initialize the values of certain data members when an
object is created. To do so we can write a method inside the class, as we have done in the
Cube class (setCube ()) and call this method after creating the object. In such a situation,
we have got to ensure that the above-mentioned method is always called after creating the
object. Java solves the problem by providing a special method - the constructor.

So what is a constructor and what extra advantage do we get from it. A constructor is a
method defined inside the class having the same name that of the class. The constructor
should not have a return type. The constructor contains the code for initializing the data
members of the class. It is executed automatically when an object of the class is created.
Therefore, no matter who creates the object of a class the constructor is invoked and the
data members are initialized. Normally when we create an object for a class we use the
following statement:

class object_variable = new class ();

In the above statement, the name of the class followed by parenthesis signifies the
constructor of the class.

At the time of defining a constructor, we have to comply the following two rules:

Ø A constructor is a method defined inside the class having the same name as that of the
class.
Ø The constructor should not have a return type. As it is called automatically, you
cannot return any value.

SR/JAVP1/301/1001/SC/3.0 68
Internet Programming Using Core Java – Part 1

Constructors can be divided into two broad categories, namely:

Ø Default Constructors
Ø Parameterized Constructors

Default constructors

Every class has at least one constructor. Even if no user-defined constructor is provided,
Java provides a default constructor with no argument and an empty body. The default
constructor helps to create an object with the new operator. In the Cube class that we
have created earlier we have not explicitly defined any constructor and hence, in such
cases, default constructors have been utilized.

If a user-defined constructor is specified for the class, then the default constructor is no
longer available. In case the default constructor is still required, it has to be created
explicitly as shown in the program below:

class defaultConst{
String ecode;
String name;
defaultConst ()//default constructor
{
ecode = "90";
name = "Susan";
}

void display()
{
System.out.println("the code of the employee is" +
ecode);
System.out.println("the name of the employee is" +
name);
}
}

class dConst{
public static void main(String args[]) {
defaultConst c1=new defaultConst ();
c1.display();
}
}

The output is:

SR/JAVP1/301/1001/SC/3.0 69
Internet Programming Using Core Java – Part 1

In the above program the variables declared are automatically initialized in the
constructor when the object of the defaultConst class is created. Thereafter, the values of
the instance variables: ecode and name are then displayed by calling the display ()
method.

Parameterized Constructors

In the previous example, we have made use of a default constructor to initialize the
instance variables of the defaultConst class. However this method of programming has
some limitations. This is because the instance variables of all the objects of defaultConst
that we create will have the value 90 and Susan. So, in order to create multiple objects of
defautConst class that will have different values of ecode and name, we take the help of
Parameterized Constructors .

In the program below we modify the defaultConst class to introduce the parameterized
constructors. We will rename this class to parameterConst.

class parameterConst{
String ecode;
String name;

parmeterConst(String x,String y)
{
ecode=x;
name=y;
}

void disp()
{
System.out.println("the code of the employee is"+ecode);
System.out.println("the name of the employee is"+name);
}
}

class argumentConst{
public static void main(String args[]) {
parameterConst c1=new parameterConst ("9","David");
parameterConst c2 = new parameterConst (“10”, “John”);
c1.disp();
c2.disp ();
}
}

SR/JAVP1/301/1001/SC/3.0 70
Internet Programming Using Core Java – Part 1

When an object is no longer referred to by any variables, Java


automatically reclaims the memory used by that object. This is
known as garbage collection. Thus, there are no destructor
methods in Java as in C/C++.

The Finalize () method

Sometimes there may be a necessity for an object to perform certain functions before it
goes out of scope or in other words before that object is reclaimed by the garbage
collector. Java have the garbage collection mechanism which automatically free up the
memory allocated by the object when that particular object goes out of scope. However,
garbage collector has a limitation in the sense that it is unable to de-allocate the memory
occupied by the non-Java objects such as file descriptors or window system fonts. In
order to free up this space we should use the finalize () method that is defined in java.
Before an object is reclaimed by the garbage collector the finalize () defined for that
object will be invoked.

The following is the syntax for declaring finalize () method is as follows:

protected void finalize () {


{
//statements that make up the code for the finalize ()
method
}

We should always remember that the finalize() method is called


just before an object is reclaimed by the garbage collector. So, we
cannot be sure when this particular method will be invoked.
Therefore, we should not depend on the finalize() method for
deallocating memory occupied by non-Java objects.

SR/JAVP1/301/1001/SC/3.0 71
Internet Programming Using Core Java – Part 1

Method Overloading

• If two or methods have the same name but


have different number, sequence or datatype
of parameters in its argument list then such
methods are called overloaded.
• Constructors can also be overloaded. It
means multiple constructors in the class
definition but with different signatures.

Method Overloading
If we write more than one method with the same name but with different method
signatures, then this phenomenon is known as Method Overloading.

There can be a situation when you want to create several methods that perform closely
related tasks. Since these methods perform the same essential tasks, name of these
methods can be same. But when we define two or more methods having same name their
signature should be different. The signature of a method consists of:

Ø The name of the method.


Ø The number of arguments it takes.
Ø The data type of the arguments.
Ø The order/sequence of the arguments.

Thus, we can say two or methods are overloaded when they differ in the number of
arguments, datatype of the argument or the sequence of the arguments that the method
can accept. The program implements the concept of method overloading.

SR/JAVP1/301/1001/SC/3.0 72
Internet Programming Using Core Java – Part 1

class Calculator
{
int add(int x,int y)
{
return (x + y);
}
float add(float x,int y)
{
return (x + y);
}
float add(float x,float y)
{
return (x + y);
}
float add(float y,float x, float z)
{
return (x + y +z);
}
}

class overloadDemo {
public static void main(String args[])
{
int i;
float j, k;
Calculator calcobj = new Calculator();
i = calcobj.add (2,2);
System.out.println (i);
j = calcobj.add (2.1f,3.1f);
System.out.println (j);
k = calcobj.add (5, 5.5f);
System.out.println (k);
k = calcobj.add (6.6f, 7.7f ,8.8f);
System.out.println (k);
}
}

In the above program, the add () method inside the Calculator class has been overloaded
four times. The first add () method takes two integer parameters, the second add ()
method takes one float and one integer parameter. The third and the fourth form of add ()
method accepts two and three float parameters respectively. Whenever we attempt to
invoke an overloaded method Java tries to find a correlation between the arguments to the
overloaded method and the overloaded method’s parameters. Whenever it locates a match
between the arguments to the overloaded method and overloaded method’s parameters
then that particular method will be called.

SR/JAVP1/301/1001/SC/3.0 73
Internet Programming Using Core Java – Part 1

However, we should always remember that method overloading is possible only when the
signature of two or methods is different. The datatype of the value returned by a method
does not constitute a method signature. Thus, if two methods differ only in the datatype
of the values returned by them then those methods cannot be considered as overloaded.
Any attempt to treat them as overloaded methods will result in the generation of a
compilation error.

Overloading Constructors

Like overloaded methods, we can also have overloaded constructors. It means more than
one constructor within a class definition having different signature. The program given
below illustrates the usage of overloaded constructors .

class Addition
{
int x;
int y;

Addition () // Default constructor which doesn't


take any argument
{
x=0;
y=0;
}

Addition (int a) // One argument constructor


{
x=a;
y=0;
}

Addition (int a, int b) // Two argument constructor


{
x=a;
y=b;
}

void display ()
{
System.out.println ("Values of x and y are : " +
x + " " + y);
}
}

class overloadedConstructorDemo {
public static void main(String args[])
{
Addition obj1=new Addition (); // Default constructor
called obj1.display ();

SR/JAVP1/301/1001/SC/3.0 74
Internet Programming Using Core Java – Part 1

Addition obj2=new Addition (10); // One argument


constructor called obj2.display ();
Addition obj3=new Addition (10,20); // Two argument
constructor called obj3.display ();
}
}

In the above code three objects of Addition class are created. The first object contains
two data members x and y with 0 value each. The second object contains two data
members x and y with values 10 and 0 respectively. The third object contains two data
members x and y with values 10 and 20 respectively.

The output of the above program is as follows:

Values of x and y are: 0 0


Values of x and y are: 10 0
Values of x and y are: 10 20

SR/JAVP1/301/1001/SC/3.0 75
Internet Programming Using Core Java – Part 1

Access Specifiers

• Mechanism to restrict access to the various


members of a class.
• Three types of access specifiers are
supported by java:
– Public: Can be accessed from anywhere outside
the class.
– Private : Can only from within the class in which
they are defined
– Protected: Can be accessed from within the class
and also from the sub class
• There is also a default access specifier which
is applicable to any member for access
specifier is not explicitly specified. They can
only be accessed from within the package

Access Specifiers in Java

We are already aware that Encapsulation is an important feature of object-oriented


programming. Encapsulation means hiding of non-essential details of a class. So,
through encapsulation we can control what parts of a program can access the members of
a class. By allowing access to data members only through a set of predefined methods we
can prevent misuse of data members. Implementation of encapsulation will allow us to
create a “Black Box” to determine which members of a class are accessible from outside
the class boundary. The mechanism by which you can control the access to the various
members of a class is called Access Specifiers .

Java has a rich set of Access Specifiers , namely, public, private and protected. Java
also defines a default access level. In cases when inheritance is involved, the protected
access specifier is used. A protected member of a class can be accessed by all the classes
within the same package and also by classes, which are subclasses (we will learn about
subclasses when we do inheritance) of that particular class irrespective of the fact
whether such subclasses reside in a different package or not. When any member is
declared as private then ONLY members of that class can access them. When a member
of a class is declared as public, then it can be accessed by any other code of your
program. The main () is always preceded with the public specifier because it is called by
the code outside the program – that is the Java run time system. When no access specifier
is used then all the members are by default public within the package (a package is a
collection of classes.) but cannot be accessed outside the package. We will learn about
packages in the following chapter. This default access specification is also referred to as
friendly

The following program demonstrates the use of default, private and public access
specifier.

SR/JAVP1/301/1001/SC/3.0 76
Internet Programming Using Core Java – Part 1

class Access
{
int var1; // default access
private int var2; // private access
public int var3; // public access

// method to access and set value to private member


var2
public void storeValue( int a)
{
var2=a;
}

// method to access and retrieve value from private


member var2
public int retrieveValue()
{
return var2;
}
}

class TryAccess
{
public static void main( String args[ ] )
{
Access obj = new Access( );

obj.var1=1;
//obj.var2=2; ERROR !! var2 is private and hence commented
out
obj.var3=3;

// var2 can only be accessed through its methods

obj.storeValue(2);
System.out.println( obj.var1+" "+obj.retrieveValue( ) +"
"+obj.var3);
}
}

In the above example var1 has default access, and thus it is accessible to all the classes
inside the package, and var3 is explicitly specified as public. The variable var2 is
private which means to access it outside the class boundary; it must be accessed through
its public methods inside the class.

The output of the above program is as follows:

1 2 3

SR/JAVP1/301/1001/SC/3.0 77
Internet Programming Using Core Java – Part 1

Inheritance

• Inheritance is the mechanism by which child


classes are inherit from parent class.
• To inherit a class,the definition of one class is
incorporated into the other using the extends
keyword.
• The private member of the base class cannot
be accessed from the derived class.
• The keyword super is used to refer to the
immediate super class.
• When a class hierarchy is created the
constructors are called in the order of
derivation.

Inheritance

Generally, objects are defined in terms of classes. We will know a lot about an object by
knowing its class. If we consider an automobile, we would know that an automobile has
wheels, steering, and engine.

Object-oriented systems take this a step further and allow classes to be defined in terms
of other classes. For example, truck, bus, car and airplane are all different kinds of
automobiles. In object-oriented terminology, truck, bus, car and airplane are all
subclasses of the automobile class. Similarly, the automobile class is the superclass of
truck, bus, car and airplane.

To inherit a class we simply incorporate the definition of one class into another using
extends keyword.

class Base {
int inum1;
int inum2;
int inum3;

void setBase (int x, int y, int z) {


inum1 = x;
inum2 = y;
inum3 = z;
}
}

class Derived extends Base {

void display ()

SR/JAVP1/301/1001/SC/3.0 78
Internet Programming Using Core Java – Part 1

{
System.out.println ("The instance variables of
base class are : " + inum1 + " " + inum2);
}
int sum ()
{
return inum1 + inum2 + inum3;
}
}

class InheritenceDemo {
public static void main (String args []) {
Derived subObj = new Derived ();
subObj.setBase (30,40,50);
subObj.display ();
int total = subObj.sum ();
System.out.println ("The sum of the instance variables
of the Derived class is : " + total);
}
}

The example shown above illustrates the concept of Inheritance. In this program we are
defining a subclass called Derived which extends the superclass called Base. Since
Derived class is the subclass of Base, thus Derived can also access all the instance
variables and methods of the Base class. Thus, we can invoke the setBase () method of
the Base class with the help of a reference variable of type Derived.

However, if any of the members of the Base class is declared private then it cannot be
accessed from the Derived class. A class member that has been declared as private is not
accessible by any code outside the class, including subclasses. So if any any attempt is
made by a subclass to access a private member of the superclass, then it will result in a
compilation error.

The keyword super

If a subclass needs to refer to its immediate superclass, it can do so by use of the


keyword super. This keyword can be used for two purposes; to call the superclass
constructor and methods and also to access a member of the superclass that has been
overridden by a member of a subclass.

The following program illustrates how super can be used to call the constructor and the
methods of the immediate superclass.

class Furniture
{
private String furn_type;
private String furn_color;

SR/JAVP1/301/1001/SC/3.0 79
Internet Programming Using Core Java – Part 1

Furniture( ) // default constructor


{
furn_type = "Wooden";
furn_color= " white";
}

Furniture( String typ, String col) // 2 argument


constructor
{
furn_type = typ;
furn_color= col;
}
public void display( )
{
System.out.println( " The type of the furniture
is :" + furn_type);
System.out.println( " The color of the furniture
is :" + furn_color);
}
}

class Table extends Furniture


{
private int no_of_legs;
private float price;
Table( )
{
super( ); // calls base class default constructor
no_of_legs = 4;
price= 2000;
}
Table( String typ, String col, int lgs, float prc)
{
super( typ,col); //calls base class 2 argument
constructor
no_of_legs = lgs;
price = prc;
}
public void display( )
{
super.display( );
System.out.println( " The no of legs of the table
are :" + no_of_legs);
System.out.println( " The price of the table is
:" + price);
}
}

class superDemo
{
public static void main( String args[ ])

SR/JAVP1/301/1001/SC/3.0 80
Internet Programming Using Core Java – Part 1

{
Table table1 = new Table( );
Table table2 = new Table("Glass","Black",3,500);

table1.display( );
table2.display( );
}
}

In the above, we are creating an object of Table class. In order to do so, we have to pass
four values for a table viz. types, color, no_of_legs and price. In the above code, when
the first object, table1, is created with no values, then the Table class can initialize the
variables that are unique to it (private int no_of_legs; private float price;). Here is a slight
problem, how can it initialize the variables of its base class that are declared private? To
avoid such a problem to arise, the base class constructor needs to be called from the
Table class-using super ().

Similarly, the second object table2 is created with 4 values. As we know constructors can
be overloaded so the constructor of the Table class that takes all four values will be
called. Here, Table () (the parameterixed constructor of the Table class) calls super ()
with parameters typ and col. This results in the Furniture class constructor to be called
which initializes the furn_type and furn_color using super(typ,col).

Another use of super is to call a member of a superclass. In the above code when we are
calling the display () method of Table class to display the value of the data members that
are present inside the class. But to display the private members of the Furniture class we
need to refer them through a public method of that class only. The display () method
prints the values of Furniture class. So to print the values of the members of the Furniture
class the base class display () method is called using super.display () from inside the
display () method of the Table class.

The output pf the above program is :

The type of the furniture is: Wooden


The color of the furniture is: white
The nos of legs of the table are: 4
The price of the table is: 2000
The type of the furniture is: Glass
The color of the furniture is: Black
The nos of legs of the table are: 3
The price of the table is: 5000

The program given below illustrates the usage of super to access an instance variable of
the superclass that has been overridden by a member of the subclass.

SR/JAVP1/301/1001/SC/3.0 81
Internet Programming Using Core Java – Part 1

class Base
{
int num;
}

class Child extends Base


{
int num;

Child (int x, int y)


{
super.num = x; //num of Base class
num = y;//num of Child class
}

void display ()
{
System.out.println ("Value of num in class Base is :
" +super.num);
System.out.println ("Value of num in class Child is :
" + num);
}
}

class testSuper {
public static void main (String args []) {
Child sub = new Child (10,70);
sub.display ();
}
}

In the above program, both the class Base and Child have an instance variable of the
same name (num). In such cases, num in class Child hides the instance variable num in
class Base. So, super is used to access the access the variable num in class Base

In a subclass, super () must be the first statement. If super () is


not used, then the default or parameter less constructor of each
base class will be executed.

When a class hierarchy is created, the constructors are called in the order of derivation,
from super class to sub class. However, we should always keep in mind that constructors
are never inherited, they have to be invoked explicitly.

SR/JAVP1/301/1001/SC/3.0 82
Internet Programming Using Core Java – Part 1

class GrandParent
{
GrandParent( )
{
System.out.println (" Inside GrandParent's
constructor ");
}
}
class Parent extends GrandParent
{
Parent( )
{
System.out.println (" Inside Parent's constructor
");
}
}
class Child extends Parent
{
Child( )
{
System.out.println (" Inside Child's constructor
");
}
}

class Test
{
public static void main (String args [])
{
Child c = new Child( );
}
}

The output of the above program is as follows:

Inside GrandParent’s constructor


Inside Parent’s constructor
Inside Child’s constructor

In the above the class Child is a subclass of class Parent which in turn is deroved from
the class GrandParent. Thus, whenever, we create an object of the Child class then the
constructors of all the three classes are invoked in the order of their derivation. Therefore,
first the constructor of the GrandParent class is invoked then the constructor of the
Parent class is invoked and lastly the constructor of the Child class is called.

SR/JAVP1/301/1001/SC/3.0 83
Internet Programming Using Core Java – Part 1

The orders of invocation of the constructors are the same


whether or not the keyword super is used.

SR/JAVP1/301/1001/SC/3.0 84
Internet Programming Using Core Java – Part 1

Overriding

• It is a mechanism to create methods in the


sub class which has the same name and the
signature as the methods in the parent class.
• The data type of the date returned by the
overridden method and the method that it
overrides should be the same.

Overriding
Overriding is a mechanism of creation of methods in the subclasses with the same name
and signature at that of the parent or the super class. The datatype of the value returned
by both the overriding and the overridden methods must be the same. This is a significant
difference between method overriding and method overloading. In the latter case the
overloaded methods can differ in their return type. The new method declared in the sub-
class hides the method of super class. This is shown in the example below:

class Furniture
{
void display( )
{
System.out.println (" This is a furniture");
}
}
class Chair extends Furniture
{
void display( )
{
System.out.println (" This is a Chair");
}
}
class overrideDemo
{
public static void main (String args [])
{
Chair c = new Chair( );
c.display( ); // the display( ) method of class Chair
is called
}
}

SR/JAVP1/301/1001/SC/3.0 85
Internet Programming Using Core Java – Part 1

In the above example an object of Chair class is created. It will call the version of
display () method present in the Chair class because the version of display ( ) inside
Chair class overrides the display () method defined inside the Furniture class.

Thus, the output of the above program will be :

This is a Chair

In order to access the display () method of the Furniture class the keyword super should
be used as illustrated below:

class Furniture
{
void display( )
{
System.out.println (" This is a furniture");
}
}
class Chair extends Furniture
{
void display( )
{
super.display ();
System.out.println (" This is a Chair");
}
}
class overrideDemo
{
public static void main (String args [])
{
Chair c = new Chair( );
c.display( ); // the display( ) method of class Chair
is called
}
}

The output of the above program is as follows:

This is a furniture
This is a Chair

SR/JAVP1/301/1001/SC/3.0 86
Internet Programming Using Core Java – Part 1

Static member and Final keyword

• The static members of a class can be


accessed before an object of that class is
created. Such members can be accessed
with the help of the class name.
• A static method can only access other static
methods and variables and cannot use super
• A static variable is initialized only once when
the class is first loaded.
• The final keyword is used to signifies that the
variables behave as constants.
• A final class cannot be subclassed, a final
variable cannot be modified and a finla
method cannot be overridden.

Static member and Final keyword


Normally, a member of a class is accessed with the help of an object belonging to that
class. However, there may arise a situation where a member of a class is to be accessed
prior to the creation of any object of that class. An example in this regard can be the
main () method which is invoked prior to the creation of any object of the class in which
the main () method has been defined.

So, how do we create such class members?

The answer is to use the keyword static. When a class member has been declared as
static it can be accessed before the creation of any object belonging to that class. The
static keyword can be applied to variables, methods and a special kind of block called the
static block. A static member of a class can be accessed in the following manner from
outside the class:

Classname.i

In the above syntax, i signify a member of a class (instance variable or method)

A method declared as static must comply with the following restrictions:

Ø A static method can only access other static methods.


Ø A static method can only access static instance variables.
Ø A static method cannot refer to the keyword super.

The program given below illustrates the usage of static methods:

SR/JAVP1/301/1001/SC/3.0 87
Internet Programming Using Core Java – Part 1

class staticClass
{
static int ivar1 = 2;
static int ivar2 = 2 * 4;

static void display (int x)


{
ivar1 = ivar1 * x;
ivar2 = ivar1 + x;
System.out.println ("The values of ivar1 and ivar2 are :
" + ivar1 + " " + ivar2);
}
}

class staticDemo
{
public static void main (String args [])
{
staticClass.display (10);
}
}

In the above program, the method display () in the staticClass has been declared as
static. Thus, we have used the name of the class (staticClass) to invoke the method
display () without creating an instance of staticClass.

The output of the above program is :

The values of ivar1 and ivar2 are : 20 30

The instance variables that have been declared as static are initialized only once when the
class is first loaded. Thus exactly one copy of static variables exist irrespective of the
number of objects of that class existing. All the objects of the class share the same copy
of a static instance variable. The program given below corroborates this fact:

class statex
{
static int ivar1;

statex ()
{
ivar1 = 0;
}
}

SR/JAVP1/301/1001/SC/3.0 88
Internet Programming Using Core Java – Part 1

class statIllustration
{
public static void main (String args [])
{
statex st1 = new statex ();
statex st2 = new statex ();
st1.ivar1 = 100;
st2.ivar1 = 200;
int testvar = st1.ivar1;
System.out.println (testvar);
}
}

The output of the above program is:

The value of testvar is : 200

Normally, we would expect that since two objects of statex class exists, each object of
this class (st1 and st2) will have its own copy of the variable ivar1. Thus when we assign
the value of st1.ivar1 to the variable testvar, its value should be 100. But this is not the
case because ivar1 is static. Thus, only one copy of ivar1 will exist no matter how many
objects of statex class have been instantiated. Both st1 and st2 refer to the same static
variable ivar1. This is precisely the reason why the value of testvar should be 200 and
not 100.

The static block, like static instance variables and methods are executed only once i.e., at
the time when the class is first loaded. A static block is generally used to initialize static
instance variables by performing some computations.

Let us modify the staticClass that we have created earlier. In the staticClass, we are
initializing the variable ivar2 by multiplying 4 with ivar1. We can put this computation
inside the static block as shown in the program given in the next page:

SR/JAVP1/301/1001/SC/3.0 89
Internet Programming Using Core Java – Part 1

class staticClass
{
static int ivar1 = 2;
static int ivar2;

static void display (int x)


{
ivar1 = ivar1 * x;
ivar2 = ivar1 + x;
System.out.println ("The values of ivar1 and ivar2 are :
" + ivar1 + " " + ivar2);
}

static
{
System.out.println ("Inside the static block");
ivar2 = ivar1 * 4;
}
}

class staticDemo
{
public static void main (String args [])
{
staticClass.display (10);
}
}

When the staticClass is loaded, all the static statements are executed. Thus, the static
instance variable ivar1 is first initialized to 2. Thereafter the static block is executed
wich displays a message “Inside the static block” and thereafter initializes the value of
ivar2 to ivar1 * 4 or 8. The output of the above program is :

Inside the static block


The values of ivar1 and ivar2 are : 20 and 30

A static method cannot be overridden to be non-static. If an attempt is made to do so a


compilation error will be generated.

If a static method has to access non-static members of a class,


then it has to specify which object of that class

SR/JAVP1/301/1001/SC/3.0 90
Internet Programming Using Core Java – Part 1

The final keyword

The final keyword can be applied to classes, variables and methods.

Final Classes

The classes are declared final in Java to ensure security. Once a class is declared final, we
cannot create a subclass of that class. There are many pre-defined classes in Java such as
String, Boolean, which are declared as final (we will learn about these classes at a later
chapter). Thus, we cannot create subclasses of these classes. If an attempt is made to
subclass a final class, the following compilation error will be generated:

Can’t subclass final classes

When a class is declared is final the method defined within the


class are implicitly declared as final.

Final variable

When a variable has been declared as final, it cannot be modified. A final variable is
similar to a const in C++. An object reference variable declared as final cannot be
changed. However, the data defined in the object that is referred to by the final object
reference variable can be altered.

Final methods

Methods declared final cannot be overridden in a subclass. When a final method is


called, the Java compiler copies the byte code for the subroutine directly to the compiled
code of the calling method, thus eliminating a costly method call. For non-final classes,
Java determines method calls dynamically during runtime. This is known as late binding.
However, calls to final methods are determined at the time of compilation, as a final
method cannot be overridden. This is called early binding.

SR/JAVP1/301/1001/SC/3.0 91
Internet Programming Using Core Java – Part 1

Abstract class

• They are created by using the abstract


keyword.
• A class is declared as abstract if it contains
one or more abstract methods.
• An abstract method has only method
declaration and no method body.
• An abstract class cannot be instantiated.
• The abstract must be overridden by the
derived class or otherwise the derived must
also be declared as abstract.

Abstract Class
Abstract classes are created using abstract keyword. A class is declared as abstract if it
contains one or more abstract methods. Abstract methods are those methods, which
have only method declaration but no method body. The syntax for declaring an abstract
method is as follows:

abstract return_type method_name (parameter_list);

The class inherited from the abstract class should implement the abstract methods in it,
otherwise they should also be declared as abstract. Abstract classes cannot be
instantiated.

It is mandatory for a class to be declared as abstract in the following circumstances:

Ø The class contains one or more abstract methods.


Ø The class inherits one or more abstract methods (from its base class) for which it
does not provide implementation.
Ø The class implements an interface (we will discus interface in the subsequent
chapter) but does not provide implementation to all the methods declared in that
interface.

The program given in the subsequent page illustrates the usage of an abstract class.

SR/JAVP1/301/1001/SC/3.0 92
Internet Programming Using Core Java – Part 1

abstract class abs1


{
abstract public void add(int x, int y);
abstract public void sub(int a, int b);
public void disp()
{
System.out.println("This is te Abstract calss");
}

class abs2 extends abs1


{
int x;
int y;

public void add(int x, int y)


{
this.x=x;
this.y=y;
System.out.println(x+y);
}
public void sub(int a, int b)
{
x=a;
y=b;
System.out.println(x-y);
}
public static void main(String[] args)
{

abs2 ab=new abs2();


ab.add(10,20);
ab.sub(40,2);
ab.disp();
System.out.println("Hello World!");
}
}

The output of the above program is as follows:

30
38
This is the Abstract class

A class cannot be declared both abstract and final.

SR/JAVP1/301/1001/SC/3.0 93
Internet Programming Using Core Java – Part 1

Quiz
• Define Class
• Define Object
• What are the different types of constructor?
Name them.
• Define method overloading
• Define static member and final?
• What is the use of having finalize () method?

Quiz

SR/JAVP1/301/1001/SC/3.0 94
Internet Programming Using Core Java – Part 1

Summary

• Define and declare a class


• Define and declare methods within a class.
• Learn how to define and declare different
types of constructors in a class
• Appreciate method overloading and method
overriding and understand the difference
between the two
• Develop Java programs that implement the
concept of Inheritance
• Learn about abstract and final members of a
class

Summary

After this chapter, you are now able to:

Define and declare a class


Define and declare the members of a class
Learn how to declare and define different types of constructors in
a class
Appreciate method overloading and method overriding and
understand the difference between the two
Develop Java programs that implement the concept of
Inheritance
Learn about abstract and final members of a class.

SR/JAVP1/301/1001/SC/3.0 95
Internet Programming Using Core Java – Part 1

Packages and Interfaces

Objectives:
• Understand and implement the concept of
packages in a Java program
• Learn about the CLASSPATH environmental
variable.
• Understand of Interfaces
• Know about the standard Java packages
• Develop Java programs using the String and
the StringBuffer class

Packages and Interfaces

At the end of the chapter, you will be able to:

Understand and implement the concept of packages in a Java


program
Learn about the CLASSPATH environmental variable
Understand the concept of Interfaces
Know about the standard Java packages
Develop Java programs using the String and the StringBuffer
class

SR/JAVP1/301/1001/SC/3.0 96
Internet Programming Using Core Java – Part 1

Packages

• Containers for groups of related classes.


• Avoids naming conflicts
• Syntax for creating a package:
package package_name;
• The classes that make up a package should
be stored in a directory with the same name
as that of the package.
• In order to utilize the classes inside a
package from outside that package the
following syntax is required:
import package_name.*;

Packages

Packages are containers for groups of related classes and interfaces. Packages provide a
convenient mechanism for managing a large group of classes and interfaces and help in
avoiding naming conflicts. They are stored in a hierarchical manner and are explicitly
imported into new class definitions.

The Java API itself is implemented as a group of packages. The java.lang, which is a
standard package provided by the Java API is implicitly imported into the new class
definitions.

Packages can be named using the standard Java naming conventions.

Creating user defined packages

User defined packages can be created by using the package keyword to specify the
package statement. The package statement specifies the name of the package and this
should be the first line in the program. The package statement is given as:

package <packagename>;

In the above statement, packagename stands for the name given to the package.

Thus, in order to create a package called pack we have to use the following statement:

package pack;

SR/JAVP1/301/1001/SC/3.0 97
Internet Programming Using Core Java – Part 1

Java stores packages in file system directories. After the classes are created for the
package, they have to be stored in the directory with the name as the package name.
Thus, the package pack should be stored in the directory called pack.

We have to ensure that the directory name must be an exact


match of the package name including the case. So the package
pack must be stored in the directory called pack and not Pack.

If the package statement is omitted, then the classes and interfaces declared within the
package are placed in the default package, which is unnamed.

Multiple class files can belong to the same package. All files belonging to a package must
stay in the directory indicated by its name. This directory must be a searchable directory
specified in the CLASSPATH.

It is possible to create a hierarchy of packages. We can achieve this by simply specifying


each package name separated by periods. Thus, in order to create a package subpack
under pack, we have to use the following statement:

package pack.subpack;

However, the classes that we create in the package subpack must be stored in the
directory structure pack\subpack.

Using the created package

The classes that are placed inside a package can be utilized from outside the package by
using the import keyword. The import statement must be specified immediately after the
package and before any class definition.

The syntax for the import statement is as follows:

import package_name.class_name;

In the above program statement, package_name is the name of the package and
class_name is the name of the class inside that package. However, in order to import all
the classes that are placed inside a package the following syntax is required:

import package_name.*;

SR/JAVP1/301/1001/SC/3.0 98
Internet Programming Using Core Java – Part 1

In the above program statement, the wildcard character * indicates all the classes that are
stored inside that package.

Thus to use all the classes that we have created under the package pack, the following
program statement is required:

import pack.*;

In order to access the classes that are placed inside the package subpack, the following
syntax is required:

import pack.subpack.*;

The wildcard character * in the import statement imports all


the classes that are stored in a particular package. However, *
will not import the packages that have been created under
that package. In order to import the sub packages we have to
specify the package hierarchy separated by periods.

Whenever the Java compiler encounters the import statement, it is interpreted in the
following manner:

Ø It checks the CLASSPATH (we will discuss about it in the next topic) environment
variable for the package path.
Ø Then the interpreter takes the package name and replaces each dot with a slash to
generate a path to get the class or classes imported

Name Collisions

Name Collision occurs when two packages are imported, both containing a class with the
same name. The compiler does not complain until any of the classes are utilized.
Whenever an attempt is made to utilize any of such classes, then a compilation error will
be generated. In case of such an error, the programmer has to explicitly name the package
along with the class required. Whenever the class is used, it has to include its fully
qualified name, which includes its full package hierarchy.

SR/JAVP1/301/1001/SC/3.0 99
Internet Programming Using Core Java – Part 1

Such a name collision can occur in a program, if it has the following import statements:

import abc.class1;
import xyz.class1;

In the above case the class class1 exists in both the packages abc and xyz. The collision
occurs when we try to create an object of class1. In such cases the compiler forces us to
be explicit. Thus, the following program statement is required:

abc.class1 c1 = new abc.class1();

Java automatically compiles a .java file in the package directory the moment an object of
the imported class is created.

The first time an object of an imported class is created, the compiler hunts for the .class
file with the same name in the appropriate directory. If it does not find it, it searches for
the .java file with the same name and creates the .class file automatically.

In case it finds both the .class file and the .java file with the name then, the compiler
compares the date stamp on the two files. If the .java file is found to be more recent, it
automatically recompiles it to generate an up-to-date .class file.

We will now create programs where the concept of packages will be implemented. For
this purpose we will create a package named pack where we will store two classes called
empInfo and deptInfo

The program below shows the creation of empInfo class

package pack;

public class empInfo


{
private String ename;
private double sal;

public empInfo (String s, double vsal)


{
ename = s;
sal = vsal;
}
public void display ()
{

SR/JAVP1/301/1001/SC/3.0 100
Internet Programming Using Core Java – Part 1

System.out.println (ename + ":" + " " + sal);


}
}

The steps that we must follow for compiling these classes are as follows:

Create a directory called pack (since the name of our package is pack)
Name the above source file as empInfo.java.
Store the file in the directory pack.
Compile the above file using the following command:

javac empInfo.java

The program given in the next page illustrates the creation of the deptInfo class.

package pack;

public class deptInfo


{
private String name;
private String location;

public deptInfo (String x, String y)


{
name = x;
location = y;
}

public void display ()


{
System.out.println ("Name and location of department :
" + name + " " + location);
}
}

The above should be named deptInfo.java and should also be stored in the pack
directory. This file should be compiled by using the same javac command.

Next, we will return to our current directory and create another source file called
packDemo.java in which we will import the classes stored in the pack directory.

SR/JAVP1/301/1001/SC/3.0 101
Internet Programming Using Core Java – Part 1

import pack.*;

class packDemo
{
public static void main (String args [])
{
empInfo e1 = new empInfo ("John Doe", 3456.22);
deptInfo d1 = new deptInfo ("Accounts", "London");
e1.display ();
d1.display ();
}
}

The moment we import the pack package in the packDemo.java file, all the public
methods and constructors of the empInfo and the deptInfo classes will be available to
the class packDemo.

The output of the above program is as follows:

John Doe : 3456.22


Name and location of department : Accounts London

We have declared the methods and the constructors of the empInfo and deptInfo class to
be public in order to facilitate the packDemo class to access them. Since packDemo
class is outside pack, it can only access the public members of the classes palced inside
pack.

SR/JAVP1/301/1001/SC/3.0 102
Internet Programming Using Core Java – Part 1

CLASSPATH Variable

• It is an environmental variable
• Searched by the compiler for specified class
when the import statement is encountered.
• New paths can be added to it by using the set
command.

The CLASSPATH Variable

It is an environmental variable containing a number of search paths. New paths can be


added to it using the set command.

When the compiler encounters the import statement, it begins searching in the directories
specified by the CLASSPATH for the specified class files.

SR/JAVP1/301/1001/SC/3.0 103
Internet Programming Using Core Java – Part 1

Interfaces

• Resembles an abstract class


• All the methods of the interface are abstract.
• Provides a means to define the protocol of a
class without devoting any attention to
implementation details.
• A class can implement an interface by
overriding all the methods that have been
defined in the interface.
• An interface can be implemented by a class
with the help of the implements keyword.
• A class can implement multiple interfaces.

Interfaces
An interface is like an abstract class whose all methods are abstract. However,
interfaces do not contain instance variables and all the methods declared in the interface
do not have method body. It provides a means to define the protocols for a class without
worrying about the implementation details. This simple benefit makes large projects
much easier to manage.

In order to implement an interface, a class should be defined which must override all the
methods that have been defined in the interface. After we define an interface one or
more classes can implement that interface. Again a single class can implement multiple
interfaces.

Unlike C++, Java does not allow multiple inheritance. Multiple inheritance takes place
when a particular is extended from two or more classes. Since a class can implement
multiple interfaces, we can say that with interfaces we can perform some of the
functionality that can be performed using multiple inheritances.

Creating interfaces

An interface is defined much like a class, but without declaring any constructors or
providing code for the methods.

The general form of declaration of an interface is as follows:

SR/JAVP1/301/1001/SC/3.0 104
Internet Programming Using Core Java – Part 1

acess Interface interface_name


{
final datatype varname = value;
return_type methodname1(parameter_list);
}

In the above syntax, access denotes access specifier and interface_name is the name of
the interface. Access specifier for an interface can be either public or not specified. If
the access specifier is not specified then the methods declared within that interface is
available to the classes present in the same package. If the access specifier is public, then
that interface can be accessed by all classes both inside and outside the package.

All methods of an interface are public by default. Variables can be declared inside the
interface declaration, but they are implicitly final, i.e. the implementing class cannot
change their values. These variables must be initialized with a constant value .

If an interface, then all methods and variables in that interface


will be implicitly public

In the code snippet below we are creating an interface called area. The interface area
consists of a final, static variable called pi, which has been initialized with the value of
pi and a method called calcArea, which accepts and return a double value.

interface area
{
final static double pi = 3.14;
double calcArea(double x);

Implementing an interface

The interface is implemented by using the implements keyword. The class implementing
the interface must override all the methods in the interface. The type and the signature of
the method that overrides an interface method must be exactly the same as the type
signature of the method defined in the interface.

Let us now create a class that implements the area interface that we have created earlier.

SR/JAVP1/301/1001/SC/3.0 105
Internet Programming Using Core Java – Part 1

interface area
{
final static double pi = 3.14;
double calcArea (double x);

class circle implements area


{
public double calcArea (double x)
{
return (pi*x*x);
}

public static void main(String args[])


{
circle cr=new circle();
area ar;
ar=cr;
System.out.println("area of circle is" + ar.calcArea
(2));
}
}

In the above program, we are creating a class called circle, which is implementing the
interface area. Inside the class circle we are overriding the method area () which is
declared in the interface area.

Another interesting aspect in the circle class is that here we are declaring an object
reference variable of type area. This is because it is legal to declare variables as object
references to the interface. These variables use an interface as the type rather than a
class. Any instance of any class, which implements the declared interface, may be stored
in such a variable. If a method is called using these variables, the corresponding
implementation will be called based on the actual instance.

Thus in our program we are declaring an object reference variable of type area called ar.
To this variable we are storing the reference to the object (cr) of class circle. When the
method area () is invoked using ar the area () method of the object (whose reference is
stored in cr) of class circle will be invoked.

The output of the above program is as follows:

Area of circle is : 12.56

SR/JAVP1/301/1001/SC/3.0 106
Internet Programming Using Core Java – Part 1

Inheriting Interfaces

Like classes, one interface can inherit another by using the keyword extends . The syntax
is the same as for inheriting classes. When a class implements an interface that inherits
another interface, it must provide implementations for all methods defined within the
interface inheritance chain.

The example given below illustrates the inheritance of interface

//one interface extending another interface

interface ABC {
void method1();
void method2();
}

//XYZ interface extends ABC interface

interface XYZ {
void method3();
}

//class Myclass implements XYZ interface

class Myclass implements XYZ {


public void method1()
{
System.out.println("This is method 1 ");
}

public void method2()


{
System.out.println("This is method 2 ");
}

public void method3()


{
System.out.println("This is method 3 ");
}

SR/JAVP1/301/1001/SC/3.0 107
Internet Programming Using Core Java – Part 1

class Mtest {
public static void main(String arg[])
{
Myclass obj = new Myclass();
obj.method1();
obj.method2();
obj.method3();
}
}

The output of the program is as follows:

This is method1
This is method2
This is method3

SR/JAVP1/301/1001/SC/3.0 108
Internet Programming Using Core Java – Part 1

Packages in Java

• Java provides with a number of pre-defined


packages that contains classes which
facilitates the performance of specialized
tasks.
• The package java.lang.* is implicitly imported
in all the Java programs that we develop.
• Two important classes of java.lang.* are:
• String
• StringBuffer
• The String class represents an immutable
string.
• The StringBuffer class encapsulates a string
that can be modified

Packages in Java

Java provides a number of pre-defined classes for the user that performs a variety of
functions. Now these classes are stored in packages to facilitate their easy reference by
the user. To use Java classes in program its required to import it. This is done by writing
import java.<package_name> at the begning of the program. The default package
imported when a program is written is java.lang package.

The following table lists some of the important pre-defined packages in Java:

Package Name Purpose


java.lang Encompasses classes that are
fundamental to the Java program.
Implicitly imported in every Java
program that is developed.
java.util Its classes deal with collection of data,
manipulating time and date
information and analyzing strings
java.io Supports input and output operations
java.awt Supports Graphical User Interface
(GUI) programming
java.awt.event Facilitates event handling
java.applet Enables the creation of applets
java.sql Supports database access

SR/JAVP1/301/1001/SC/3.0 109
Internet Programming Using Core Java – Part 1

In this topic, we are going to learn about two very important classes of java.lang package
namely String and StringBuffer.

String Calss

The String class is used to describe an immutable string. Once an object of the String
class is created, the string that it represents cannot be changed. Thus, whenever any
modification is performed on such string a new String object that reflects the
modifications. The original string remains unchanged.

The String class has number of constructors. The list enumerates some of them:

Ø String();
Ø String(char c[]);
Ø Stringchar c[], int start_index, int numer_chars)

String();

This will create an instance String with no character in it.

String (String obj)

The above constructor will create a String object that will contain a string that has
been created by another String object denoted by obj. The program below illustrates
this:

class StringDemo
{
public static void main (String args [])
{
String str1 = new String (“HELLO”);
String str2 = new String (str1);
System.out.println (str1);
System.out.println (str2);
}
}

The output of the above program is:

HELLO
HELLO

SR/JAVP1/301/1001/SC/3.0 110
Internet Programming Using Core Java – Part 1

String(char c[]);

This constructor will create a string that will be initialized with a character array
denoted by c[]. The example below illustrates the creation of a string with the help of
this constructor.

class stringEx1
{
public static void main(String arg[])
{
char c[]={'a','b','c','d'};
String s=new String(c);
System.out.println(s);
}

The output of this program is as follows:

abcd

String (char c[], int start_index, int number_chars)

The constructor above can be used to create a string that will contain a sub array of a
character array. In the syntax given above char c[] represents the character array,
start_index specifies the point from where the sub array will start and
number_chars specifies the number of characters that the sub array will contain. The
program below illustrates this:

class stringEx2
{
public static void main(String arg[])
{
char c[]={'a','b','c','d','e','f','g'};
String s=new String(c,2,2);
System.out.println(s);
}

SR/JAVP1/301/1001/SC/3.0 111
Internet Programming Using Core Java – Part 1

Output of the program is

cd

Methods of String class

Some of the important methods of the String class are illustrated below:

Methods Use
length() Find number of characters in a string
charAt(int) Find a character at a location in a string
passed as its argument
substring(int) Returns a String object containing a
specified character set of a String from the
position specified by the integer argument
passed to it.
concat(String) Returns a new String object containing the
original String’s characters followed by the
string specified in the argument
Replace(char,char) Replaces all occurrence of a particular
character in the string with the specified
character
toCharArray() Converts a String to character array
getChars(int, int, char [], int) Extracts the specified range of characters
from a string and stores them in a character
array. The starting and ending point of
extraction in the string as well as the name
of the character array and the starting point
in the character array where the sub string
will be stored can be specified as the
argument to this method.
getBytes() Copy characters from a String to a byte
array
equals(object) Checks if two Strings are equal or not
equalsIgnoreCase(object) Checks if two Strings are equal or not
ignoring the case.
trim() Trims the blank spaces and returns a new
String
valueOf(object) Returns a String representation of the
object argument. It is a static method.
indexOf() Returns the index of a character in a String
lastIndexOf() Returns the index of a character in a String
but starts searching from the last
toLowerCase () Converts the object of the String class
which calls this method to lower case.

SR/JAVP1/301/1001/SC/3.0 112
Internet Programming Using Core Java – Part 1

toUpperCase() Converts the object of the String class,


which calls this method to lower case.

The program given in the next page illustrates some of the above methods of the String
class.

SR/JAVP1/301/1001/SC/3.0 113
Internet Programming Using Core Java – Part 1

class stringEx3
{
public static void main(String[] args)
{
String s="Globsyn Technologies Limited";
String s1="hello";
String s2="HELLO";
System.out.println(s);
System.out.println (“The location of the first character in
string S is : “ + s.charAt(1));
System.out.println("The s1 and s2 strings compaired gives
the result of "+s1.equals(s2));

System.out.println("The s1 and s2 strings compaired gives


the result of "+s1.equalsIgnoreCase(s2));
System.out.println("Lndex of n in the string is
"+s.indexOf('n'));
System.out.println("Last Index of n in teh string is
"+s.lastIndexOf('n'));
System.out.println(" Concat " +s2.concat("World"));
System.out.println("Replace n with m "+s.replace('n','m'));
System.out.println("change to uppercase +s1.toUpperCase());
System.out.println(" Change to lowercase
"+s2.toLowerCase());

}
}

The output of the program is:

SR/JAVP1/301/1001/SC/3.0 114
Internet Programming Using Core Java – Part 1

StringBuffer class

StringBuffer class provides much of the common use functionality of strings. The
difference is String represents fixed-length character series that cannot be modified but
the StringBuffer class represents a varied length character series that can be modified
according to our requirements. Characters and substrings can be inserted in the middle or
appended at the end of a string encapsulated by the StringBuffer class.

The following are the constructors of the StringBuffer class:

Ø StringBuffer (): This constructor results in the creation of a string that can
accommodate 16 characters without reallocation.
Ø StringBuffer (int): Results in the creation of a string whose initial size is
categorically specified by an integer variable that is passed as an argument to this
constructor.
Ø StringBuffer (String): This argument results in the creation of a StringBuffer that
is initialized by the by a string that is passed to it as anargument.

Some Methods of StringBuffer

Methods Use
length() Returns the length of the StrinBuffer
append(String) Adds a string at the end
insert(int,String) Used to insert string in the middle of the
StringBuffer
charAt(int) Returns the character at the location
specified by the integer argument.
setCharAt(int,char) Places the character denoted by a character
argument at the location specified by the
integer argument.
capacity() Returns the total allocated capacity of the
invoking StringBuffer .
reverse() Reverses the string
getChars(int,int,cahr[],int) Extracts a substring from the string buffer
into a specified character array.
delete (int, int) Deletes a sequence of characters from the
invoking StringBuffer. The range of
deletion is specified by the two integer
variables that are passed to this method as
an argument.
deleteCharAt (int) This method deletes a particular character
from the StringBuffer form a specified
position.

SR/JAVP1/301/1001/SC/3.0 115
Internet Programming Using Core Java – Part 1

class stringEx4
{
public static void main(String[] args)
{
String s="Globsyn Technologies Limited";
StringBuffer sb=new StringBuffer(s);
StringBuffer sb1=new StringBuffer("Hello");
System.out.println(sb);
System.out.println(sb1);
System.out.println ("Length of StringBuffer sb: "
+ sb.length ());
System.out.println ("Capacity of StringBuffer sb1
: " + sb1.capacity ());
sb1.setCharAt (2, 'y');
System.out.println ("charAt (2) of sb1 is : " +
sb1.charAt (2));
sb.reverse ();
System.out.println (sb);
sb.reverse ();
System.out.println (sb1.append("World"));
sb.delete (22, 28);
System.out.println ("sb after deletion : " + sb);
sb1.deleteCharAt (2);
System.out.println ("sb1 after deletion : " +
sb1);
}
}

The output of the program is:

SR/JAVP1/301/1001/SC/3.0 116
Internet Programming Using Core Java – Part 1

SR/JAVP1/301/1001/SC/3.0 117
Internet Programming Using Core Java – Part 1

Quiz

• How do you think that interfaces help in


implementing multiple inheritances.
• The classes inside a package must be stored
in a directory whose must be different than
the name of the package. State true or false.
• Define CLASSPATH environmental variable.

Quiz

SR/JAVP1/301/1001/SC/3.0 118
Internet Programming Using Core Java – Part 1

Summary

• Understand and implement the concept of


packages in a Java program
• Learn about the CLASSPATH environmental
variable.
• Understand of Interfaces
• Know about the standard Java packages
• Develop Java programs using the String and
the StringBuffer class

Summary

At the end of this chapter, you are now able to:

Understand and implement the concept of packages in a Java


program
Learn about the CLASSPATH environmental variable
Know about the standard Java packages
Understand the concept of Interfaces
Develop Java programs using the String and the StringBuffer
class

SR/JAVP1/301/1001/SC/3.0 119
Internet Programming Using Core Java – Part 1

Exception & Threads


Objectives
• Appreciate the exception handling mechanism in Java
• Learn about the Unchecked Exception classes
• Get acquainted with the Checked Exception classes
• Create User-defined exceptions

Exception Handling in Java

At the end of the chapter, you will be able to:

Appreciate the exception handling mechanism in Java


Learn about Unchecked Exception classes
Get acquainted with the Checked Exception classes
Create User Defined Exceptions

SR/JAVP1/301/1001/SC/3.0 120
Internet Programming Using Core Java – Part 1

Exceptions in Java

• Exceptions are errors that interrupt the normal flow of


execution and results in abnormal termination of the
program
• Exception handling mechanism in Java facilitates
exception handling in an ordered manner and prevents
abnormal termination
• Exceptions are handled in java with the help of the
following three classes:
• Throwable
• Exception
• Error
• The above classes are defined in the package java.lang

Exceptions in Java
Exception is an abnormal condition (such as errors) that occurs in a Java program.
Whenever, an error is encountered in a program, it’s execution abnormally terminates.

Java provides certain exception handling mechanism in order to fix the errors that can
occur during the execution of a Java program and also to avoid abrupt termination of a
program.

As JAVA is a true Object-Oriented language, it does everything through class and objects
and so even the exception handling mechanism in JAVA is object-based. It means when
an abnormal condition arises in the code at run time, an exception object is created
representing that condition and thrown in the method that caused the error. Now the
programmer may choose to handle the exception. If he doesn't, the default exception
handler of the run-time-environment will handle it.

Let us now explore the class that Java has defined to facilitate exception handling.

All exceptions are subclasses of Throwable class. It is the subclass of Object class and
the top of the exception hierarchy. Just below Throwable, are two classes named
Exception and Error. These classes are present in java.lang package.

The branch headed by Error is used for the situations, which cannot be handled by the
program itself.

The Error class has been designed to handle the following kinds of abnormalities:

Ø Running out of memory


Ø Inability to find files

SR/JAVP1/301/1001/SC/3.0 121
Internet Programming Using Core Java – Part 1

Ø Problems in network connectivity


Ø Resource allocation errors

The hierarchy of exception class is:

Object

Throwable

Error Exception

RuntimeException

The Exception class has been defined to deal with exceptions that the user programs are
expected to handle. Such exceptions can be an attempt to perform a division by 0 or
accessing array elements beyond the length defined. As shown in the above diagram the
main subclass of Exception class is RuntimeException. Further RuntimeException
class has subclasses to handle specific exceptions.

Some of the exception classes under Exception class are:

Ø ClassNotFoundException
Ø IllegalAccessException
Ø InterruptedException

Some of the exception classes under RuntimeException class are:

Ø ArithmeticException
Ø ArrayStoreException
Ø IllegalArgumentException
Ø IllegalMonitorStateException
Ø ArrayIndexOutOfBoundsException

SR/JAVP1/301/1001/SC/3.0 122
Internet Programming Using Core Java – Part 1

The exceptions defined above are system-defined exceptions.


User defined exception can be created in Java.

SR/JAVP1/301/1001/SC/3.0 123
Internet Programming Using Core Java – Part 1

Exception handling technique


• Few keywords are used for the purpose exception
handling, they are:
– try : Encloses the block of code that can give rise
to an exception
– catch: The block that performs the actual error
handling functions.
– throw: Used for explicitly throwing an exception
– finally : Specified after the try/catch block and
executed whether or not the try block throws an
exception

Exception Handling Techniques


Java handles exceptions using five keywords try, catch, finally and throw. Let us study
each of them in details.

try: - If any part of code is expected to give rise to an exception, it is put inside a try
block The statements that comprise the try block should be enclosed within curly braces.
A try block cannot comprise of a single statement. It is possible to develop nested try
blocks that is one try block can be placed inside another try block.

The syntax for try block is as follows:

try
{
Statement which may cause exception
}

catch: The catch block comes after the try block and performs the actual error handling
functions. One try block may be associated with one or more catch blocks. All the
corresponding catch blocks for a try block should come after the try block. The scope of
a catch block is limited to the statements specified to the statements in the immediately
preceding try block. A catch block cannot catch exceptions thrown by another try block
except in the case of nested try blocks, which we will discuss a little later. The catch
block contains an argument, which is of type Exception, or a subclass of Exception. This
argument tells that this catch block will handle the exceptions of its (argument’s) type
and any exception of its subclass. Once the exception is caught, the catch block executes.
Its usage is:

SR/JAVP1/301/1001/SC/3.0 124
Internet Programming Using Core Java – Part 1

try
{
Java statements which may occur exception
}
catch (SomeThrowableObject variableName)
{
Java statements which may occur exception
}

The example below illustrates exception handling with the help of a try/catch block.

class ExceptionDemo
{
public static void main (String args [])
{
try
{
int nums [] = {10,12,13};
for (int i = 0; i < 5; i++)
System.out.println (nums[i]);
}
catch (ArrayIndexOutOfBoundsException a)
{
System.out.println ("The array length is only 3.");
}
}
}

In the above program we have created an integer array called nums and storing three
elements in it. Thereafter, we are trying to display the contents of the array with the help
of a for loop. After displaying the three elements hat are stored in the array, the for loop
array attempts to access the fourth element of the array. Since the length of the nums
array is only 3, it will give rise to an exception, which in Java parlance is called
ArrayIndexOutOfBoundsException (we will discuss about it a little later).

This exception is thrown from the try block and is intercepted in the catch block. For this
purpose, the catch block is supplied with an argument of type
ArrayIndexOutOfBoundsException. Within the catch block we are informing the user
that the length of the array is 3.

The output of the above program is as follows:

10
12
13

SR/JAVP1/301/1001/SC/3.0 125
Internet Programming Using Core Java – Part 1

The array length is only 3

The class Throwable overrides the toString () method defined by Object (which sits at
the top of the class hierarchy). The toString () method returns a String that contains a
description of an exception. This exception can then be displayed using the
System.out.println () statement. So, let us now modify our program to display the
description of the exception thrown by the program.

class ExceptionDemo
{
public static void main (String args [])
{
try
{
int nums [] = {10,12,13};
for (int i = 0; i < 5; i++)
System.out.println (nums[i]);
}
catch (ArrayIndexOutOfBoundsException a)
{
System.out.println ("Exception: " + a);
}
}
}

The output of the program is as follows:

10
12
13
Exception: java.lang.ArrayIndexOutOfBoundsException

In case of nested try block the, if the inner try block does not have a corresponding catch
block then the catch block of the outer try statement is checked to see whether it can
handle the exception raised by the nested try block.

throw:- The throw statement can be used to explicitly throw an exception. Its syntax is

throw Throwable_Instance

SR/JAVP1/301/1001/SC/3.0 126
Internet Programming Using Core Java – Part 1

In the above statement, Throwable_Instance have to an object of the Throwable class or


any of its subclass. After the throw statement the executions of programs stop. The
program starts searching the catch block, which matches the particular type of execution.
If it is found the control of the program passes to that catch block. If not, then the catch
block of the enclosing try block (if any) is examined. If no match is found, then the
control is transferred to the default exception handler and the execution of the program is
abruptly terminated.

The program below illustrates the explicit throwing of an exception by creating a new
object.

class ThrowYourException
{
static void display() {
try {
throw new NullPointerException (“demo”);
}catch (NullPointerException e){
System.out.println (“Exception caught”);
throw e;
}//end of catch
}//end of display function
public static void main(String args[]){
try {
display ( );
} catch (NullPointerException e) {
System.out.println (“Recaught “ + e);
}//end of catch
}//end of main
} //end of class

In the above program, the main () method calls the demoproc () method inside the try
block. In the demoproc () method an instance of the NullPointerException (which is a
subclass of Runtime Exception class) is created with the help of the new operator and is
explicitly thrown using the throw keyword. This exception is caught twice. Once inside
the catch block in the demproc method from where it is again rethrown and is handled
by the catch block defined inside the main () method.

The output of the above program is:

SR/JAVP1/301/1001/SC/3.0 127
Internet Programming Using Core Java – Part 1

finally: This comes after the try and catch block. finally block is optional but if defined,
it will execute regardless of whether or not an exception is throw or not. If a catch is
defined after the try block then the finally block will be executed after the execution of
the catch block. If no catch block is defined after the try block then the finally block
will be executed after the try block. Many a time, a program can use certain system
resources like file handle. In such a case, if some exception occurs in the program then it
will not be possible for it to return those system resources. So to avoid the program from
exiting before an important job is done, we have to use the finally block.

The following example illustrates the ArithmeticException and the finally

class exp
{
public static void main(String args[])
{
try
{
int a=10;
int b=10;
a= a/(a-b);
// the exception occurs here on the above line so
//the control jumps to the catch block and does not
//come to or after these comment lines.
}
catch(ArithmeticException e)
{
System.out.println("dividing by ZERO is an "+ "Error");
}
finally
{
System.out.println("The finally block is executed") ;
}
}
}

The output of the above program is as follows:

SR/JAVP1/301/1001/SC/3.0 128
Internet Programming Using Core Java – Part 1

A try block must be accompanied by either a catch block


or by a finally block.

SR/JAVP1/301/1001/SC/3.0 129
Internet Programming Using Core Java – Part 1

UnChecked Exception Class


• The compiler does not have to ensure whether a method
throw or handles these exceptions.
• These are mainly subclasses of Error or
RuntimeException.

Unchecked Exception Classes


The exception that can arise in a Java program can be categorized into:

Ø Checked Exceptions
Ø Unchecked Exceptions

Mostly the exceptions that are derived from the RuntimeException classes are called
unchecked exceptions . They are so called because the compiler does not ensure whether
the method handles or throws these exceptions.

The following table illustrates some of the important unchecked exceptions :

Exception Description
ArithmeticException Arithmetic error e.g. division by 0.
ArrayIndexOutOfBoundExecptions An attempt is made to access an array element
that is beyond the number of elements that the
array can store
ArrayStoreException An element is assigned to an array which of an
incompatible type.
ClassCastExecption An attempt is made to perform an illegal cast.
NegetiveArraySizeException An array is created with a negative size.
NullPointerException Invalid use of a null reference
StringIndexOutOfBounds An attempt is made to index outside the
bounds of a string.

SR/JAVP1/301/1001/SC/3.0 130
Internet Programming Using Core Java – Part 1

Checked Exception Class


• The exceptions which are checked during compile time by
the compiler are called as checked exception.
• Must be specified in a particular method’s throw list.
• The throws clause is used when a method is capable of
handling an exception which it cannot handle.

Checked Exception Classes

Checked Exceptions are checked during compile time by the compiler. They must be
included in a method’s throws list if that method is capable of throwing that exception
but does not handle such exception by itself. Some of the important checked exceptions
are listed in the following table.

Exceptions Description
ClassNotFoundException A particular class is not found.
IllegalAccessException An access to a particular class is denied.
NoSuchFieldException A request is made for a field that does not exist
NoSuchMethodException A request is made for a method that does not
exist.

When a method is capable of throwing an exception that it does not handle by itself it
must declare so with the help of the throws clause. This is necessary so the callers of this
method can create appropriate catch blocks to handle such exceptions. Otherwise, an
abrupt termination of the program will take place. This is required for all exceptions other
than exceptions of the type Error or RuntimeException or any of their subclasses.

The syntax of the method declaration with the throws clause is as follows:

type method_name (parameter list) throws exception -list


{
//method body
}

SR/JAVP1/301/1001/SC/3.0 131
Internet Programming Using Core Java – Part 1

The exception list includes exceptions other than those exceptions, which are type Error
or RuntimeException or any of their subclasses.
The following program illustrates the usage of the throws statement.

class throwsDemo
{

static void display() throws NoSuchMethodException


{
System.out.println ("Inside the dispaly method");
throw new NoSuchMethodException ("demo");
}
public static void main(String args[])
{
try
{
display();
}
catch (NoSuchMethodException n)
{
System.out.println ("Caught " + n);
}
}
}

In the above program, the display () method throws an exception of type


NoSuchMethodException which it does not handle itself and hence the exception type
is declared with the help of throws at the time of method declaration. The exception is
handled in the catch block of the main () method.

The output of the above program is as follows:

Inside the display method


Caught java.lang.NoSuchMethodException: demo

SR/JAVP1/301/1001/SC/3.0 132
Internet Programming Using Core Java – Part 1

User Defined Exceptions


• A user-defined exception can be created by
developing a subclass of the Exception class.

User Defined Exceptions

Till now we have seen the use of exceptions that have been previously defined in the
package java.lang. But in Java it is possible to create user-defined exceptions. For this
purpose, we have to define a subclass of Exception.

The program given below creates a subclass of Exception and then utilizes this sub-class
to create user-defined exceptions.

class NewException extends Exception{


private int x;
NewException (int a){
x=a;
}

public String toString(){


return “NewException[“ + “]”;
}
}

class Demo{
public static void main(String args[]){
try{

for(int a=0;a<20;a++){
if (a==10)
throw new NewException(a);
System.out.println (“success”);
}
}catch(NewException e){
System.out.println( “catching exception :” +e);

SR/JAVP1/301/1001/SC/3.0 133
Internet Programming Using Core Java – Part 1

}
}
}

In the above program we are creating a subclass of Exception called NewException. The
NewException defines a constructor and also overrides the toString () method to display
the description of the exception. Inside the Demo class, the main method () is throwing
an instance of NewException when the value of a becomes equal to 10.In the catch
block a description of the exception is displayed with the help of the System.out.println
statement.

The output is:

SR/JAVP1/301/1001/SC/3.0 134
Internet Programming Using Core Java – Part 1

Quiz

• Define the hierarchy that are defined in Java for the


purpose of Exception handling
• What is the purpose of the throws clause.
• The try block should be accompanied either by
catch block or by a finally block. State true or false
• How are the exceptions handled in a nested try
block.

Quiz

SR/JAVP1/301/1001/SC/3.0 135
Internet Programming Using Core Java – Part 1

Exercise

Q1) Fill in the blanks:

a) If no exceptions are thrown in try block, when try block completes execution, control
proceeds to _______________.

b) The ___________ exception arises if the programmer tries to divide an integer value
by zero.

c) The IOException exception is checked for at the ___________ time.

d) A user-defined exception can be thrown by using this _________keyword.

e) IOException is a checked exception.

Q2) What happens if an exception occurs and an appropriate exception handler cannot be
found?

Q3) What is the key reason for using finally block?

Q4) State true or false?

a) A catch block may or may not have code inside it.

b) Checked exceptions are checked at the run time.

c) Exception class is the parent class of all types of program-generated exceptions.

d) The catch block comes before the try block.

e) One try block may be associated with one or more catch blocks.

SR/JAVP1/301/1001/SC/3.0 136
Internet Programming Using Core Java – Part 1

Summary

• Appreciate the exception handling mechanism in Java


• Learn about the Unchecked Exception classes
• Get acquainted with the Checked Exception classes
• Create User-defined exceptions

Summary

At the end of this, you are now able to:

Appreciate the exception handling mechanism in Java


Learn about Unchecked Exception classes
Get acquainted with the Checked Exception classes
Create User Defined Exceptions

SR/JAVP1/301/1001/SC/3.0 137
Internet Programming Using Core Java – Part 1

The concept of Multithreading in Java

Objectives:
• Define a thread
• Appreciate the concept of Multithreading
• Learn about the Thread lifecycle
• Learn about the Thread states
• Understand the priority of a thread
• Get acquainted with the methods of the Thread class
• Create a thread
• Learn about Thread Synchronization
• Appreciate Interthread communication and the concept of
Daemon threads

The concept of Multithreading in Java

At the end of this chapter, you will be able to

Define a Thread.
Appreciate the Concept of Multithreading.
Learn about the Thread Lifecycle.
Learn about the different Thread states.
Learn about Priority of a Thread.
Learn the methods of the Thread class.
Create a Thread.
Learn about Thread Synchronization.
Learn about Interthread Communication and the concept of
Daemon thread.

SR/JAVP1/301/1001/SC/3.0 138
Internet Programming Using Core Java – Part 1

Introduction to Threads

• Piece of code present in a single program that can


run concurrently with other pieces.
• Defines a separate path of Execution.
• Shares the same address space.
• Thread is a path of execution within a program that
executes separately.
• Inter-thread communication and context-
switching between threads is less expensive
than that between processes.

Introduction to Threads

A single process can have multiple concurrently executing units. Objects provide a way
to divide a program into multiple independent solutions. Also, we need to turn a program
into separate, independently running subtasks. This is made possible with the help of the
concept of multithreading.

Each of these independent subtasks is called a thread and our program will be executed
in such a manner that it will appear as if each thread is running by itself and has the CPU
by itself. Some underlying mechanism is actually dividing up the CPU time for us, but in
general, we do not have to think about it, which makes programming with multiple
threads a much easier task. A multitasking operating system is capable of running more
than one process at a time, while making it look like each one is chugging alone by
periodically providing CPU cycles to each process. A thread is a single sequential flow of
control within a process.

What Is a Thread?

A thread is said to be a single path of execution within a program. It is a part of a


program. So it can be said that if a program is having more than one parts that can run
independently of each other, the program is having multiple threads. Just like two
programs execute independently of each other, two threads also execute independently.
So if there are two threads in the program, both of them are executed differently from
each other. That is both of them are two separate paths of execution and each path is
independent of another. So in essence we can say that we are dividing a program into
more than one part through threads.

SR/JAVP1/301/1001/SC/3.0 139
Internet Programming Using Core Java – Part 1

Whenever a program starts running it is allocated a separate address space. Every


information related to the program is stored within that address space only. Now the
thread is also a part of the program, so it is not allocated a different address space. It runs
in the same address space of the program of which it is a part.

So all the threads within a program will execute within the address space of the program.
For this reason, communication and context switching between threads is less expensive
as compared to communication and context switching between processes.

SR/JAVP1/301/1001/SC/3.0 140
Internet Programming Using Core Java – Part 1

The concept of Multithreading

• The concept of multithreading facilitates developing efficient


programs that results in the optimum utilization of the CPU.
• A multithreaded program contains two or more parts that
can run concurrently.
• Each part of such a program is a separate thread that
defines a separate path of execution.
• This enables a single program performing two or more
tasks simultaneously

Concept of Multithreading
Java provides built-in support for multithreaded programming.

The concept of multithreading enables us to write very efficient programs that make
maximum use of the CPU, because idle time can be kept to a minimum.

A multithreaded program contains two or more parts that can run concurrently.

Each part of such a program is a separate thread that defines a separate path of execution.
Thus a single program can perform can perform two or more tasks simultaneously. For
example, a text editor can format text at the same time that it is printing, as long as these
two actions are being performed by two separate threads. This is depicted in the figure
below:

SR/JAVP1/301/1001/SC/3.0 141
Internet Programming Using Core Java – Part 1

The thread Lifecycle


• The start() method
– starts a thread.
• The run() method
– defines the code that constitutes the new thread.
• The isAlive() method
– provides information whether the thread has finished
execution or not
• The stop() method
– Used for explicit termination of a thread.

The thread Life Cycle

In Java, the concept of multithreading is implemented with the help of the Thread class,
the methods that are defined under it and an interface called Runnable. The methods
defined in the Thread class helps in the management of the thread. The lifecycle of a
thread can be described with the help of the following four methods of the Thread class:

Ø The start() method: Starts a thread.


Ø The run() method: Defines the code that constitutes the new thread.
Ø The isAlive() method: Provides information about the thread during its lifecycle.
Ø The stop() method: Used to stop a Thread.

Let us make a detailed examination of each of the above methods.

The Start () method :

The start () method puts a particular thread into the ready state or makes the thread
eligible to run. So if there is no other threads that is running or the current thread is a
higher priority thread, then this thread will be executed. But if it is not so, the current
thread may have to wait for some period of time before it actually starts running. So
calling the start method on a thread doesn’t mean that the thread will start running. It
depends on the scheduling algorithm that the thread scheduler follows. The start ()
method invokes the run () method that we are going to discuss next. The signature of the
start () method is:

void start ()

SR/JAVP1/301/1001/SC/3.0 142
Internet Programming Using Core Java – Part 1

The run () Method:

This defines the code that constitutes the new thread. This method can call other methods,
use other classes and declare variables, just like the main thread can. The only difference
is that run () establishes the entry point for another concurrent thread of execution within
your program. The new thread ends when the run () returns. The signature of the run ()
method is:

public void run ()

The isAlive () Method:

The method isAlive () when called on a thread determines whether the thread has finished
its execution or not. If the thread on which it was called has finished, this method returns
false. Otherwise it returns true. Signature of the isAlive () method is:

final boolean isAlive()

The stop () method:

This method is used to terminate the thread explicitly. Once terminated, the thread cannot
be resumed once again.

SR/JAVP1/301/1001/SC/3.0 143
Internet Programming Using Core Java – Part 1

Thread States
• Running State

• Waiting State
– Suspended State
– Sleeping State

• Ready State

• Dead State

Thread States

When a thread is created in a program, it is possible for the programmer to control it.
Thus, as a programmer we can suspend the execution of a thread for a particular period of
time (this phenomenon is technically known as sleeping) so that some other thread may
continue. This is possible because the threads are having different states in their lifetime.
The following are the different thread states:

Running state:
A thread is said to be in the running state when the CPU is executing it. It means that the
code attached with the thread is being executed.

Waiting state:

A thread is said to be in the waiting state if it was given a chance of execution but it did
not complete its execution. It may choose to go into sleep. The other possibility may be
that some other thread suspends the thread. Suspending the execution of a thread is now
deprecated in the new version.

Ready state:

When the thread is waiting for the CPU to execute it.

Dead state:

When the thread has finished its execution.

SR/JAVP1/301/1001/SC/3.0 144
Internet Programming Using Core Java – Part 1

The diagram below depicts the various states of a thread.

SR/JAVP1/301/1001/SC/3.0 145
Internet Programming Using Core Java – Part 1

other methods of the Thread class

• The methods that are frequently used in the


implementation of Multithreaded programs are as
follows:
– public static void sleep(long ms) throws InterruptedException
– public final void setName(String newname)
– public final String getName()
– public final void join() throws InterruptedException
– public static Thread currentThread ()

Other methods of the Thread class

We have already discussed about the Thread class and some of its methods at the time of
discussion about the life cycle of a thread. In this topic we ar going to discuss about a few
other important methods of the Thread class.

The sleep () method

The signature of this method of this method is

static void sleep(long ms) throws InterruptedException

The sleep () puts the currently active thread to sleep for the specified number of
milliseconds that is passed to it as an argument. This method is static and may be
accessed through the Thread class name.

When the CPU comes encounters the sleep () method it will suspend the thread for a
period of time that is specified as its argument. So if there are other threads waiting for
their turn to run, they will start running according to their priority. When the specified
period of time expires the thread that had gone for sleeping will become ready to run. We
have to remember that the thread doesn’t just start running after the sleeping time is over.
It simply becomes eligible to run.

Now when the scheduler finds the CPU time it will put this thread to run. So the time
after which the thread actually starts running may be higher than the time specified with
the sleep method.

SR/JAVP1/301/1001/SC/3.0 146
Internet Programming Using Core Java – Part 1

So when we give an instruction like t.sleep (1000) (where t is an object of the Thread
class) the thread goes to sleep for a period of 1 second. After 1 second it will become
ready to run.

The setName () method

Sets the name of the thread to that specified by newname. The signature of this method
is:

final void setName(String newname)

The getName () method

Returns a string that specifies the thread name. The signature of this method is:

final String getName()

The join () method

This method is used more frequently than the isAlive () method to wait for a thread. It
provides more functionality than the isAlive () method. This method waits for the called
thread to terminate. So the calling thread has to wait till the called thread finishes and
joins the calling thread. The name of the method comes from this concept that the called
thread joins the calling thread and till this happens the calling thread has to wait for the
called thread. Signature of the method is:

final void join() throws InterruptedException

The currentThread () method

This method returns a reference to the thread on which it is called. The main thread of a
Java program is created as soon as the execution of the program is started. However, in
order to control this thread with the help of the Thread object, we have to acquire a
reference to it. This can be achieved with the currentThread () method. This method
returns a reference to the thread on which it is called. Once a reference to the main thread
is obtained with the help of the said method, it can be controlled like any other thread.
The signature of the currentThread () method is:

public static Thread currentThread ()

SR/JAVP1/301/1001/SC/3.0 147
Internet Programming Using Core Java – Part 1

Let us now write our first thread program in java utilizing some of the above methods.

class MyThread
{
public static void main (String args [])
{
Thread th = Thread.currentThread ();
System.out.println ("Description of current thread : "
+ th);
th.setName ("New Thread");
String str = th.getName ();
System.out.println ("Thread name after change : " +
str);
try
{
for (int i = 1; i <=5; i++)
{
System.out.println (i);
Thread.sleep (500);
}
}
catch (InterruptedException e)
{
System.out.println ("Thread Interrupted");
}
finally
{
System.out.println ("Main thread exiting");
}
}
}

In the above program, we are obtaining a reference to the main thread by calling the
currentThread () method. Then, we are displaying the description of the current thread.
Thereafter, we are changing the name of the current thread to New Thread by calling the
setName () method and displaying the changed name of the thread with the help of
getName (). Next, we are defining a loop, which counts from 1 to 5 stopping half a
second between each line. This is achieved by calling the sleep () method to which the
period of stoppage is passed as a parameter. The loop is placed within a try/catch block
as the sleep () method can throw an InterruptedExcepion error.

The output of the program is as follows:

Description of current thread: Thread [main,5,main]


Thread name after change: New Thread
1
2

SR/JAVP1/301/1001/SC/3.0 148
Internet Programming Using Core Java – Part 1

3
4
5
Main thread exiting

Let us spend time on the description of the current thread when the th is used as an
argument to println. This displays the following information:

Ø The name of the thread


Ø The priority of the thread
Ø Name of the thread group
The default name of the main thread is main. Its default priority is 5 and main is also the
name of the thread group to which it belongs. The thread group is a data structure that
manages the state of a thread collection as a whole.

SR/JAVP1/301/1001/SC/3.0 149
Internet Programming Using Core Java – Part 1

Thread Creation

• To create a thread, create a new class that extends


Thread class.
• The extending class should call the run() method.
• It should also call start() to begin execution of the
new thread.

Thread Creation
There are two methods of creating a thread. Either they can extend from the Thread class
or implement the Runnable interface. Both the Thread class and the Runnable interface
are available in the package java.lang.

If we are creating a thread by extending from the Thread class we cannot extend from
some other class if we need to, due to restriction placed on multiple inheritance. But if we
create a thread by implementing the Runnable interface then we can extend from some
other class. Actually this is the design concern. It doesn't affect the way a thread will
behave.

Extending the Thread Class:

To create a thread, we have to create a new class that extends the Thread class. The
extending class must call the run () method. It must also call start () to begin execution
of the new thread.

The program given below illustrates the creation of a new thread by extending the
Thread class.

SR/JAVP1/301/1001/SC/3.0 150
Internet Programming Using Core Java – Part 1

class Nthread extends Thread


{
Nthread()
{
super("New thread");
System.out.println("Child thread: "+this);
start();
}
public void run()
{
System.out.println("Child thread :"+i);
try
{
for(int i=5; i<0; i--)
{

System.out.println (I)
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Child interrupted ");
}
System.out.println("Exiting child thread");
}
}

class Exthread
{
public static void main(String args[])
{
new Nthread(); //create a new thread
try
{
System.out.println("Parent thread :" +i);
for(int i=5; i<0; i--)
{
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread exiting.");
}
}

SR/JAVP1/301/1001/SC/3.0 151
Internet Programming Using Core Java – Part 1

In the program on the preceding page we are creating a new thread by extending the
Thread class. For the purpose of creating a child thread we are instantiating an object of
the Nthread class and from its constructor we are invoking the following constructor of
the Thread class :

Thread (String thread_name)

In the above syntax, thread_name specifies the name of the string.

The output of the above program is as follows:

SR/JAVP1/301/1001/SC/3.0 152
Internet Programming Using Core Java – Part 1

Implementing the the Runnable


interface
• Contains only run() method.
• The easiest way to create a thread is to create a class that
implements the Runnable interface.
• The code written under the run()defines an independent
path of execution for the thread and its entry and exit points.
• Once the run () method finishes the thread becomes dead.

Implementing the Runnable Interface


A thread can also be created by implementing the Runnable interface. In order to
implement this interface we have to override only the run () method.

The code that constitutes the new thread will be written inside the run () method. Now
the thread remains alive till it is inside the run () method. Once this method finishes the
thread becomes dead.

The program below illustrates the creation of a thread by implementing the Runnable
interface.

class MyThread1 implements Runnable


{
Thread t1;
MyThread1()
{
t1=new Thread(this, "my thread");//ensures that the run
method of MyThread1 object is invoked.
System.out.println("child thread's name : "+ t1);

//this start method will call run() automatically


//and the thread will start execution.
t1.start();
}
public void run( )
{
try
{
for (int a=0;a <=5; a++)
{ System.out.println("child thread : "+ a );

SR/JAVP1/301/1001/SC/3.0 153
Internet Programming Using Core Java – Part 1

Thread.sleep(400);
}
}
catch(InterruptedException e)
{ System.out.println(" disturbed while sleeping ");
}
finally
{ System.out.println(" child thread exiting");

}
}
}

class NewThread
{ public static void main(String args[])
{ MyThread1 thr = new MyThread1();
//Ascertaining whether the child thread has finshed
execution
System.out.println ("Child Thread is alive : " +
thr.t1.isAlive ());
try
{
//waiting for the child thread to finish
thr.t1.join (); //waiting for the child thread to
finish execution
}
catch (InterruptedException e)
{
System.out.println ("Main thread disturbed");
}
System.out.println ("Child thread finished execution :
" + thr.t1.isAlive ());//Again ensuring whether the child
thread has finished execution.
System.out.println ("Main thread exiting");
}
}

In the above program we are creating a new thread by implementing the Runnable
interface. For the purpose of creation of the new thread, from the MyThread1 class we
are invoking the following constructor of the Thread class:

Thread (Runnable threadOb, String thread_name)

In the above form of constructor, threadOb is an object of a class that implements the
Runnable interface and thread_name is the name that the new thread will have.

SR/JAVP1/301/1001/SC/3.0 154
Internet Programming Using Core Java – Part 1

One interesting thing about this program is that we are not explicitly putting the main
thread to sleep. Instead, we are making use of the isAlive () and the join () method
defined in the Thread class.

The output of the above program is as follows:

Child Thread’s name : Thread [my thread, 5, main]


child Thread is alive : true
child thread : 0
child thread : 1
child thread : 2
child thread : 3
child thread : 4
child thread : 5
child thread exiting
child thread finished execution
Main thread exiting

SR/JAVP1/301/1001/SC/3.0 155
Internet Programming Using Core Java – Part 1

Priority of Threads
• Enables the thread scheduler to determine to the order
when each should be allowed to execute.
• Integer values that states the relative priority of one thread
to another.
• Facilitates context switching
• Important methods for implementing thread are :
– final void setPriority (int level) : Used to set the priority level of the
invoking thread
– final int getPriority (): Returns the current priority of the invoking
thread.
• The relative priority level for a thread is determined by the
following three values:
– MAX_PRIORITY: value is 10.
– MIN_PRIORITY: value is 1.
– NORM_PRIORITY :Default priority level having a value of 5.

Priority of Threads
The thread scheduler decides when each thread should be allowed to run using thread
priorities. Usually higher-priority threads get more CPU time than lower-priority threads.
Thread priorities are integers that specify the relative priority of one thread to another. It
is used to decide when to switch from one running thread to the next. This is called a
context switch. The rules that determine when a context switch takes place are simple:

Ø A thread can voluntarily release control: This is done by explicitly sleeping. In


such a case, all the other threads are examined and the highest-priority thread that is
ready to run is given the CPU.
Ø A higher-priority thread can preempt a thread: In this case, as soon as the higher-
priority thread wants to run, it does. This is called preemptive multitasking.

The setPriority() method, belonging to the Thread class is used to set thread’s priority.
The syntax is:

final void setPriority(int level)

The level specifies the new priority setting for the calling thread. The value of level must
be within the range MIN_PRIORITY and MAX_PRIORITY. These values are 1 to 10,
respectively.To return a thread to default priority, specify NORM_PRIORITY, which is
currently 5. These priorities are defined as final variables within the Thread class.

SR/JAVP1/301/1001/SC/3.0 156
Internet Programming Using Core Java – Part 1

The getPriority() method of the Thread class is used to obtain the current priority
settings, this method returns an integer. The syntax is:

final int getPriority()

SR/JAVP1/301/1001/SC/3.0 157
Internet Programming Using Core Java – Part 1

Synchronization
• Ensures the accessing of a shared resource by multiple
threads in an orderly manner.
• Achieved with the help of a Monitor
• Monitor is an Object.
• Only one Thread can own a monitor at a time.
• When a Thread has entered a monitor, it is locked.
• All other Threads will be in the suspended state until the first
Thread exits.
• Synchronization can be done using:
– Using synchronized method
– Using synchronized block

Synchronization
Working with thread provides the advantage of CPU utilization. The flow of the program
can be controlled in a better way and thereby increasing the performance of the program.
But the things become complex when more than one thread is being used and usually this
is the scenario.

Consider a situation when there are two threads and both of them are trying to share the
same resource. One is reading from a file and the other is writing there. So the first thread
is reading whatever the second thread is writing. Now if the first thread is reading and
then the second thread starts writing, the first thread would read the wrong data. This will
result in data corruption. So there should be some mechanism, which will ensure that the
two threads are not working at the same time. To avoid this situation java provides
synchronization.

Synchronization is achieved with the help of a monitor. Synchronization is a way to


implement order in the process. To synchronize two threads means that they won’t
interfere with each other. If they are using some shared resources they won’t conflict.
They would use it when the other is not using it so that the data is not corrupted.
Synchronization is used to implement the concept of monitor.

In the next few topics we will try to be acquainted with the nuts and bolts of
synchronization.

The Monitor

A monitor is an object that is used as a mutually exclusive lock. Every object in Java is
having a lock with it. Monitor represents this lock. At a time, only one thread can control
the lock on an object. If one thread has acquired the lock, it has entered the monitor on

SR/JAVP1/301/1001/SC/3.0 158
Internet Programming Using Core Java – Part 1

that object. Now if any other thread tries to acquire the lock on the same object it would
be suspended until the first thread exits from the monitor. So there is no possibility that
an object will be used at the same time by more than one thread.

The concept of monitor is implemented by using the synchronized keyword.

A resource or an object is made up of pieces of codes. So to avoid two threads using the
same objects simultaneously, the restriction has to be put on code making up the
functionality of the object.

This can be done in two ways:

Ø Using Synchronized method


Ø Using Synchronized block

Now let us write a program wherein a particular method is being called by three instances
of another class. We will not use synchronization here to see the effects of not using
synchronization.

class MyCall
{
void call(String message)
{
System.out.println("Mycall is executing");
System.out.print("[" + message);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}

SR/JAVP1/301/1001/SC/3.0 159
Internet Programming Using Core Java – Part 1

class MyCaller implements Runnable


{
String message;
MyCall trigger;
Thread t;
public MyCaller(MyCall trig, String s)
{
trigger = trig;
message = s;
t = new Thread(this);
t.start();
}
public void run()
{
trigger.call(message);
}

}
class sync{
public static void main(String args[]){
MyCall trigger = new MyCall();
MyCaller c1 = new MyCaller(trigger, "Hello how is
life?");
MyCaller c2 = new MyCaller(trigger, "Synchronized");
MyCaller c3 = new MyCaller(trigger, "Fine");

// wait for threads to end


try{
c1.t.join();
c2.t.join();
c3.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}

In the above program, we are creating three classes. The first class called MyCall has a
method called call () which a parameter of type String called message. The call ()
method tries to display a message within square brackets. After displaying the opening
bracket and the message it invokes the sleep () method that will suspend the execution of
the current thread for a period of one second and then will display the closing bracket.

The second class is called MyCaller whose constructor takes two arguments: a reference
to the MyCall class and a String, which represents the message to be displayed. They are
stored in the two instance variables message and trigger respectively. The constructor
also creates a new thread. The run () method of the MyCaller class calls the call ()
method of the Mycall class passing the message to be displayed as an argument.

SR/JAVP1/301/1001/SC/3.0 160
Internet Programming Using Core Java – Part 1

Inside the sync class we are creating an instance of the MyCall class and three instances
of the MyCaller class with three distinct messages. The same instance of the MyCall
class is passed to the constructors of each instance of the MyCaller class.

Let us now see the output of this program.

Mycall is executing
[Hello how is life? Mycall is executing
Mycall is executing
[Synchronized [Fine]
]
]

Now, the above output looks a bit confusing to say the least. In this program the three
instances of the Mycaller class is trying to access the call () method at the same time. In
other words, three different threads are attempting to access the same resource (the call ()
method), on the same object (trigger) at the same time. This phenomenon is often
referred to as the race condition.

The solution to our above problem is the use of synchronized methods and objects, which
we are going to study in the following topics.

SR/JAVP1/301/1001/SC/3.0 161
Internet Programming Using Core Java – Part 1

Synchronized Methods
• A method can be made synchronized with the help of the
help of the keyword synchronized.
• The syntax for a synchronized method is as follows:
synchronized return_type methodname(parameter)
{
//executable statements
}
• Any thread using the synchronized method will automatically
invoke the monitor on the object owning that method and
thereby obtaining an exclusive lock on it.

Synchronized method
To make a particular method synchronized, the signature of such method must be
preceded with the keyword synchronized. Now, if a thread is using this method it will
automatically invoke the monitor of the object whose method it is.

Therefore, if some other thread wants to enter into the same method the same time it is
not possible, the other method has to wait because the first thread has acquired a lock on
the object.

In the code snippet below, we are making a method called get () synchronized.

synchronized int get(){


System.out.println(“ got number : “+ num);
return num;
}

Now, only one thread can access this method at a particular point of time. Let us now
rewrite the program we have developed in the previous topic to incorporate
synchronized methods.

SR/JAVP1/301/1001/SC/3.0 162
Internet Programming Using Core Java – Part 1

class MyCall
{
synchronized void call(String message)
{
System.out.println("Mycall is executing");
System.out.print("[" + message);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}

class MyCaller implements Runnable


{
String message;
MyCall trigger;
Thread t;
public MyCaller(MyCall trig, String s)
{
trigger = trig;
message = s;
t = new Thread(this);
t.start();
}
public void run()
{
trigger.call(message);
}

SR/JAVP1/301/1001/SC/3.0 163
Internet Programming Using Core Java – Part 1

class sync{
public static void main(String args[]){
MyCall trigger = new MyCall();
MyCaller c1 = new MyCaller(trigger, "Hello how is
life?");
MyCaller c2 = new MyCaller(trigger, "Synchronized");
MyCaller c3 = new MyCaller(trigger, "Fine");

// wait for threads to end


try{
c1.t.join();
c2.t.join();
c3.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}

In this program, we have declared the method call () as synchronized. This will prevent
the other threads from accessing it, when one particular thread is using it.

If we compile the above program we will obtain the correct output which is:

Mycall is executing
[Hello how is life?]
Mycall is executing
[Synchronized]
Mycall is executing
[Fine]

SR/JAVP1/301/1001/SC/3.0 164
Internet Programming Using Core Java – Part 1

Synchronized block

• Used for objects not possessing synchronized


methods.
• The syntax is as follows:
synchronized (object)
{
//statements to be synchronized
}

Synchronized blocks
For objects, which are not, having synchronized methods and which are to be used by
threads, the synchronization in the access is done with the help of synchronized block.
Whenever the call is being made to the shared object it would be put inside the
synchronized block.

The general form of the synchronized statement:

synchronized(object) {
// statements to be synchronized
}

The object in the above syntax is a reference to the object being synchronized.
Synchronized blocks ensure that a call to a member of the object, which is being
synchronized, is made only after the calling thread has entered the monitor of the object.

We will modify the above program to incorporate to incorporate a synchronized block


within the run () method of the MyCaller class.

SR/JAVP1/301/1001/SC/3.0 165
Internet Programming Using Core Java – Part 1

class MyCall
{
void call(String message)
{
System.out.println("Mycall is executing");
System.out.print("[" + message);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}

class MyCaller implements Runnable


{
String message;
MyCall trigger;
Thread t;
public MyCaller(MyCall trig, String s)
{
trigger = trig;
message = s;
t = new Thread(this);
t.start();
}
public void run()
{
synchronized (trigger)
{
trigger.call(message);
}
}

SR/JAVP1/301/1001/SC/3.0 166
Internet Programming Using Core Java – Part 1

class sync{
public static void main(String args[]){
MyCall trigger = new MyCall();
MyCaller c1 = new MyCaller(trigger, "Hello how is
life?");
MyCaller c2 = new MyCaller(trigger, "Synchronized");
MyCaller c3 = new MyCaller(trigger, "Fine");

// wait for threads to end


try{
c1.t.join();
c2.t.join();
c3.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}

The output of the above is the same as shown in the previous topic.

SR/JAVP1/301/1001/SC/3.0 167
Internet Programming Using Core Java – Part 1

Interthread Communication
• Java includes an elegant interprocess communication
mechanism via the following methods:
– the wait() method
– the notify() method
– the notifyAll() method

• All these methods can be called only from a


synchronized method.

Interthread Communication
Java includes an elegant interprocess communication mechanism between threads that
enables multiple threads to communicate with each other. The following methods are
responsible for achieving interprocess communication.

Ø the wait() method : The wait() method when invoked by a thread puts the thread in
waiting state. It will remain there till it is notified by some other thread to continue.
The waiting thread leaves the monitor. There may be more than one thread waiting at
a particular time. All the threads are put in a pool maintained by the object.

Ø the notify() method : This method when called within a synchronized method of an
object wakes the first waiting thread. Now the newly woken thread is in a ready to
run state.

Ø the notifyAll() method : This method wakes up all the threads waiting on an object
on which the notifyAll() method was called. The highest priority thread will run first.

All these methods can be called only from a synchronized method. These methods are
implemented as final methods in the Object class and so all classes have them.

SR/JAVP1/301/1001/SC/3.0 168
Internet Programming Using Core Java – Part 1

Daemon Thread
• They are created by the Java Virtual Machine
(JVM).
• They serve the user threads
• If the user thread dies, the daemon thread also dies
with it.
• Following methods deal with Daemon threads:
• void setDaemon(boolean on)
• boolean isDaemon()

Daemon Thread
The Daemon threads are created by the JVM. Daemon threads only live to serve the user
threads.

The only time the Java virtual machine checks to see if a particular thread is a daemon
thread is after a user thread has exited. When a user thread exits, the JVM checks to see if
there is any remaining user thread left. If there are no user threads remaining, then the
JVM schedules the next thread (user or the daemon). If there are only daemon threads
remaining, then the JVM exists and the program terminates.

The methods in the thread class that deal with daemon threads are:

void setDaemon(boolean on)


Sets the thread to be a daemon thread if on is true.

boolean isDaemon()
Returns true if the thread is a daemon thread and false if the thread is a user thread.

SR/JAVP1/301/1001/SC/3.0 169
Internet Programming Using Core Java – Part 1

Quiz
•What is a thread? Wat is the difference
between a Daemon thread and a user thread?
•What do you understand by synchronization?
How it is achieved in Java?

Quiz

SR/JAVP1/301/1001/SC/3.0 170
Internet Programming Using Core Java – Part 1

Exercise

Q1) Fill in the blanks in each of the following.

1. The ________ method is used to terminate a Thread’s execution.

2. Two reasons a thread could enter the dead state are _______ and ________.

3. A thread’s priority can be changed with the ________ method.

4. To wait for a designated number of milliseconds and then resume execution, a thread
should call the _________ method.

5. A _________ thread may be made active again by calling the resume method.

Q2) State whether each of the following is true or false.

1. A thread is not runnable if it is dead.

2. In Java, a higher priority runnable thread will preempt threads of lower priority.

3. Threads may yield to threads of lower priority.

4. The sleep method does not consume processor time while a thread sleeps.

5. Java provides a powerful capability called multiple inheritance.

SR/JAVP1/301/1001/SC/3.0 171
Internet Programming Using Core Java – Part 1

Summary
• Define a thread
• Appreciate the concept of Multithreading
• Learn about the Thread lifecycle
• Learn about the Thread states
• Understand the priority of a thread
• Get acquainted with the methods of the Thread class
• Create a thread
• Learn about Thread Synchronization
• Appreciate Interthread communication and the
concept of Daemon threads

Summary

At the end of this chapter, you are now able to:

Define a Thread
Appreciate the Concept of Multithreading
Learn about the Thread Lifecycle
Learn about the different Thread states
Understand the Priority of a Thread
Get acquainted with the methods of the Thread class
Create a Thread
Learn about Thread Synchronization
Appreciate Interthread Communication and the concept of
Daemon thread

SR/JAVP1/301/1001/SC/3.0 172
Internet Programming Using Core Java – Part 1

Input/Output in Java

Objectives
• Handle File I/O
• Appreciate the file class
• Implement Java streams
• Use the reader and writer class
• Get acquainted with the Java Collection Framework

Input/Output in Java

At the end of this chapter, you will be able to:

Handle File I/O


Appreciate the File class
Implement Java Streams
Use the Reader & Writer classes
Get acquainted with the Java Collections Framework

SR/JAVP1/301/1001/SC/3.0 173
Internet Programming Using Core Java – Part 1

Introduction

• The data used in any source code is


taken from an input source and the
output is sent to a particular destination
after achieving the desired result.
• Java has various classes and interfaces
which are implemented from the java.io
package
• These classes and interfaces are used
for authentic data handling

Introduction
The file I/O system is one of the most important systems used in Java. A programmer’s
job cannot be accomplished unless he can access the external data. The data used in any
source code is taken from an input source and the output is sent to a particular direction
after achieving the desired result.

Java has various classes and interfaces, which are implemented from the java.io package.

In Java, data can be retrieved from a source and the output can be sent to a destination.
Disk file is an example of source and destination. Other than disk file, network
connection and memory buffer are also considered as sources or destinations. The I/O
classes and interfaces necessary to handle these operations are stored inside java.io
package.

Some useful classes defined by java.io are as follows:

BufferedInputStream BufferedOutputStream
BufferedIReader File
FileDescriptor FileInputstream
FileOutputStream FileReader
FileWriter Inputstream
InputStraemReader OutPutStream

Many of these classes will be frequently used in the programs described in this chapter.

SR/JAVP1/301/1001/SC/3.0 174
Internet Programming Using Core Java – Part 1

File class

• Used to refer to a file or directory that


might exist in host machine’s file
system.
• Most of the classes which are defined
by the java.io operate on streams
principle but the file class does not.
• The file class has direct interaction with
the files and file systems.

File Class

The File class present under java.io package handles files and directories directly. It is
mainly used to get the properties of a file, such as time of creation, date of creation,
access permissions etc. A directory is also treated as a File object in Java. It has all the
common properties of file with a special property that returns list of filenames.

Most of the classes that are defined by the java.io package operate on stream principle
(which will be discussed in the later part of this chapter), but the file class does not. The
file class deals directly with the files and file systems. The file class describes the
properties of a file.

The information associated with a disk file can be obtained or manipulated using the File
object. Some of this information includes permissions, time, date and directory path.

Many programs used in Java uses files as source and destination of data. The file classes
can directly interact with the files and file systems.

A directory in Java is treated as a file. The directory has just one additional property that
is a list of filenames. The list of filenames can be examined by using a list () method.

SR/JAVP1/301/1001/SC/3.0 175
Internet Programming Using Core Java – Part 1

File class

• The constructors used in file class are :


– File(String dir path)
– File(String dir, String subpath)
– File(File dirobj, String subpath)
• There are various methods used to obtain the
standard properties of a file object.

File Class
File Class supports three forms of constructors:

Ø File(String dir path) : Here Directory path is the directory path name of the file.

Example: File f1=new File(“c:\java\test.txt”);

Ø File(String dir, String subpath) : Here dir is the Directory path specified as String
and subpath is the filename of the file.

Example: File f1=new File(“c:\java”, “test.txt”);

Ø File(File dirObj, String subpath): This format is equivalent to the previous one,
except that the dirObj is a File object instead of String.

Example: File f1=new File(“fobj”,”tst.txt”);

Here test.txt is any general text file. In addition, the


creation of a File object fobj never creates a file in the
physical disk.

SR/JAVP1/301/1001/SC/3.0 176
Internet Programming Using Core Java – Part 1

File class

• boolean exists()- returns true if file exists


• String getName()- returns last element in the path.
• String getParent()- returns name of directory
containing the file.
• boolean isDirectory()- returns true if File is a
Directory.
• boolean isFile()- returns true if File is an existing file
in the file system.
• String[] list()- returns an array containing names of all
files & directories under File object.

File Class contd.


Methods in File class:

To obtain the properties of the files as well as directories, there are different methods
defined under File class. Most of the methods are self-explanatory. Here are some of the
methods:

Methods Use
exists() Tests if the file exists or not and returns a
boolean value
getName() Returns the name of the file
getParent() Returns the name of the parent directory
equals() Compares two file objects and returns a
boolean value
getPath() Returns the path of the file
getAbsolutePath() Returns the absolute path of the file
isFile() Test whether it is a file or not
isDirectory() Tests whether it is a directory or not
lsatModified() Returns the when the file was last modified
length() Returns the length of the file
canRead() Tests whether we can be written
canWrite() Tests whether the file can be read
delete() This method is used to find the length of file
renameTo() This method is used to rename a file
list() This is used to list contents of the directory

SR/JAVP1/301/1001/SC/3.0 177
Internet Programming Using Core Java – Part 1

The example given below illustrates the usage of some of the above methods of the File
class:

import java.io.*;
class fileMethod
{
public static void main(String[] args)
{
File f=new File("c:\\java","test.txt");
File f1=new File("c:\\java");
System.out.println("File name is "+f.getName());
System.out.println("path is "+f.getPath());
System.out.println("Absolute path
"+f.getAbsolutePath());
System.out.println("Name of the Parent:
"+f.getParent());
System.out.println(f.exists() ? "exists" : "Does not
exist");
System.out.println(f.isFile() ? "Its a file" : "It
is a not a file");
System.out.println(f.isDirectory() ? "Its a
directory" : "It is not a directory");
System.out.println(f1.isDirectory() ? "Its a
directory" : "It is not a directory");
}
}

The output of the above program is as follows:

SR/JAVP1/301/1001/SC/3.0 178
Internet Programming Using Core Java – Part 1

As discussed the list() method is used to list the files of a particular directory. The
following example explains it.

import java.io.*;
class FileList{
public static void main(String[] args) throws IOException
{
File f1 = new File ("d:/java");
String ss[]=f1.list();
for (int j=0;j<ss.length;j++)
System.out.println(ss[j]);
}
}

The output of the program will display the list of files present in the java directory.

Now, there may be a necessity to restrict the number of files returned by the list ()
method to encompass only those file that agrees with a certain file pattern. For this
purpose, we make use of an overloaded version of the list () whose signature is as
follows:

String [] list (FilenameFilter obj)

In the above syntax, obj represents an instance of a class that implements the
FilenameFilter interface.

FilenameFilter interface defines only one method whose name and signature is shown
below:

boolean accept (File dirname, String file_name)

The accept () method returns true if the if the directory (denoted by dirname) contains
files that matches the file_name argument. Otherwise it returns False.

SR/JAVP1/301/1001/SC/3.0 179
Internet Programming Using Core Java – Part 1

The following example explains the usage of FilenameFilter interface:

import java.io.*;
class FileMethods implements FilenameFilter
{
String s;
public FileMethods(String s){
this.s="."+s;
}
public boolean accept( File f, String name)
{
return name.endsWith(s);
}
public static void main(String[] args) throws IOException
{
File f1 = new File ("d:/aspsidd");
FilenameFilter fnf= new FileMethods(args[0]);
String ss[]=f1.list(fnf);
System.out.println("Printing file names with the
extension "+args[0] + " of " +f1.getPath()+ " directory");
for (int j=0;j<ss.length;j++)
System.out.println(ss[j]);
}
}

If we pass “txt” as the command line argument then the output is

In the above example, the file with the extension txt present in the aspsidd directory is
displayed as we are passing txt as the parameter at runtime. When the list method is
executed with the parameter of FilenameFilter object then it calls the accept() method
implicitly which tests for the condition as supplied and returns a boolean value. In the
above example it tests for is the extension of the file .txt or not if yes teen it is stored in
the String ss.

SR/JAVP1/301/1001/SC/3.0 180
Internet Programming Using Core Java – Part 1

Streams

• Stream is a path of communication between source


of Information and the destination.
• Java perform I/O operations through Streams.
• A Stream is linked to a physical device by the Java
I/O system.
• Streams implement sequential access of data.
• Java provides three types of classes namely:
– Input Streams
– Output Streams
– Readers/Writers

Java Streams
In Java, the Input and Output operations are done through Streams. It is the path of
communication between the source of information and destination.

A stream is a sequence of bytes traveling from a source to a destination over a specified


communication path. If a program reads from a stream, it is the stream’s destination and
if it writes to a stream, it is the stream’s source.

The concept of stream is very much useful in Java. Because, when a programmer is
dealing with I/O using Stream, he need not bother about the type of devices he is making
use of. The stream object will take care of that. The stream abstracts the details of I/O
operations from the user.

Streams implement sequential access of data. It eventually means that the streams cannot
access data randomly. The stream class can only be used in those programs where there is
a scope of accessing data one by one starting from top.

Java provides three types of streams classes they are:

Ø Input Streams
Ø Output Streams
Ø Reader/Writer

These are abstract classes and all the methods of this class throw IOException.

SR/JAVP1/301/1001/SC/3.0 181
Internet Programming Using Core Java – Part 1

Input Streams and Output Stream Classes are byte


based and Reader/ writer classes are character based.

The following figure shows the hierarchy of the stream classes.

File

InputStream
Object

OutputStream

Reader

Writer

The byte Stream is responsible for handling input and output of bytes. The byte Stream
can be used with any type of objects; it can even be used with the binary data. This
versatility makes it most popular among the streams used in real programming
environment. InputStream and OutputStream are designed for byte streams. These two
abstract classes have different subclasses and each one of them represents different
devices like network connections, disk files or memory buffers.

SR/JAVP1/301/1001/SC/3.0 182
Internet Programming Using Core Java – Part 1

InputStream

ByteArrayInputStream FilterInputStream

FileInputStream Takes Filtered


Takes Byte
Array Byte Stream
as Input
To Read Bytes from a File

InputStream Class
The InputStream classes hierarchy is as shown below:

InputStream

SequenceInputStrea ByteArrayInputStrea
m FileInputStream m

PipedInputStream ObjectInputStrea FilterInputStream


m

BufferedInputStrea PushBackInputStream DataInputStream


m

InputStream class Hierarchy

SR/JAVP1/301/1001/SC/3.0 183
Internet Programming Using Core Java – Part 1

We are now going to undergo a detailed discussion about the constructors and methods of
InputStream Classes

ByteArrayInputStream

ByteArrayInputStream class uses a byte array as its input.

Constructors of the class are:

Ø ByteArrayInputStream(byte array [])


Ø ByteArrayInputStream(byte array [],int start, int count)

The methods and its use are listed below:

Method Use
available() Used to find the number of bytes that can be read from the
input stream.
read() Reads the next byte from the Input Stream
read(byte[]. int, int) Reads certain amount of data from an Input stream and stores
it in a Byte array
mark(int) Sets a mark on the current position of the stream
reset() Takes the control to the marked position
markSupported() Tests if this ByteArrayInputStream supports mark/reset
skip(long) Used to skip some bytes from the Input Stream

Note: The read () method returns the number of bytes read and returns –1 if it encounters
the end-of-file.

import java.io.*;
class bytearrayinput
{
public static void main(String ar[]) throws IOException
{
String s="Globsyn";
byte b[]=s.getBytes();
ByteArrayInputStream in=new ByteArrayInputStream(b);
int c;
while((c=in.read())!=-1)
{
System.out.println((char)c);
}
}
}

SR/JAVP1/301/1001/SC/3.0 184
Internet Programming Using Core Java – Part 1

The output of the above program is as follows:

FileInputStream

Is used to read data from a file.

Constructors are:

Ø FileInputStream(File) :- Creates an Input file stream to reads data from a file object.

Ø FileInputStream(FileDescriptor) :- Creates an Input file stream to reads data from a


file descriptor.

Ø FileInputStream(String) :-Reads from a file with a specified name.

The methods and its use are listed below:

SR/JAVP1/301/1001/SC/3.0 185
Internet Programming Using Core Java – Part 1

Method Use
available() Used to find the number of bytes that can be read from the
file input stream.
read() Reads the next byte from the Input Stream
read(byte[]) Reads data from an file input stream and stores it in a Byte
array
read(byte[]. int, int) Reads certain amount of data from an file input stream and
stores it in a Byte array
close() Closes the file input stream and releases the system resource
associated with it
finalize() Ensures that the close() method is called when there are no
reference to it.
skip(long) Used to skip some bytes from the Input Stream

FilterInputStream

This class is the baseclass of classes BufferedInputStream, DataInputStream and


PushbackInputStream that filter input streams. These streams provide additional
functionality. The class FilterInputStream overrides all methods of InputStream.

BufferedInputStream

It is used to read chunks of data from a buffered array. It prevents the physical read of
data every time.

Constructors are:

Ø BufferedInputStream(InputStream)
Ø BufferedInputStream(InputStream, int)

The methods supported by this class are the same as that of the ByteArrayInputStream.

Example:

Create a file c.txt which contains text “thefirstfileprogram”

SR/JAVP1/301/1001/SC/3.0 186
Internet Programming Using Core Java – Part 1

import java.io.*;
class bufinputstr{
public static void main(String a1[]) throws
IOException
{
FileInputStream fis=new FileInputStream("c.txt");
BufferedInputStream bis=new
BufferedInputStream(fis);
int a;
System.out.println("Start of file ___________");
a=bis.read();
for(int j=0;j<5;j++)
{
System.out.print((char) a);
a=bis.read();
}
System.out.println(" ");
bis.mark(10);
for(int j=0;j<5;j++)
{
System.out.print((char) a);
a=bis.read();
}
System.out.println(" ");
bis.reset();
for(int j=0;j<5;j++)
{
System.out.print((char) a);
a=bis.read();
}
bis.skip(5);
System.out.println(" ");
while (a!=-1)
{
System.out.print((char) a);
a=bis.read();
}
}
}

The output is:

SR/JAVP1/301/1001/SC/3.0 187
Internet Programming Using Core Java – Part 1

DataInputStream

A data input stream lets an application read primitive Java data types from an underlying
input stream.

Constructors are:

Ø DataInputStream(InputStream)

Some of the methods are:

Method Use
read(byte[]) Reads data from data input stream and stores it in a
Byte array
read(byte[]. int, int) Reads certain amount of data from data input stream
and stores it in a Byte array
readBoolean() Reads boolean value from data input stream
readByte() Reads a signed 8-bit from data input stream
readChar() Reads a Unicode character from data input stream
readDouble() Reads a double from data input stream
readFloat() Reads a float from data input stream
readInt() Reads a signed 32-bit integer from data input stream
readLine() Reads next line of text from data input stream
readLong() Reads a signed 64-bit integer from data input stream
readShort() Reads a signed 16-bit number from data input stream
skipBytes(int) Skips number of bytes of the data input stream as
specified

SR/JAVP1/301/1001/SC/3.0 188
Internet Programming Using Core Java – Part 1

Consider a situation where you want that the program will ask to input a string at
runtime.

import java.io.*;
class ipstr
{
public static void main(String a[]) throws IOException
{
DataInputStream ds=new DataInputStream(System.in);
System.out.println("Enter the string");
String s=ds.readLine();
System.out.println(" the string is "+ s);
}
}

The output is:

It will ask the user to enter the string at the runtime e.g if Globsyn is written and the enter
key is pressed the output will be.

Here is a code fragment to illustrate the DataInputStream:

try
{ FileInputStream f1=new FileInputStream(“myFile”);
DataInputStream d1=new DataInputStream(f1);
int a=d1.readDouble();
float ff=d1.readFloat();
d1.close();
f1.close();
} catch(IOException e) {}

SR/JAVP1/301/1001/SC/3.0 189
Internet Programming Using Core Java – Part 1

This code fragment indicates that the file “myFile” is expected to contain its first eight
bytes as double and the next four bytes as float.

OutputStream

ByteArrayOutputStream FilterOutputStream

Writes Byte Writes Filtered


Array to the FileOutputStream Byte Stream as
destination Output

To Write bytes to a file

OutputStream Class
The output class hierarchy starts from the OutputStream class. The OutputStream class hierarchy
is as shown below:

OutputStream

ObjectOutputStream ByteArrayOutputStream
FileOutputStream

PipedInputStream FilterOutputStream

BufferedInputStream DataOutputStream

SR/JAVP1/301/1001/SC/3.0 190
Internet Programming Using Core Java – Part 1

OutputStream class Hierarchy

Some examples of OutputStream classes are ByteArrayOutputStream, FileOutputStream


and FilterOutputStream. The working of all these OutputStreams is just the reverse of
InputStream.

ByteArrayOutputStream

It is used to write array of bytes.

Constructors are:

Ø ByteArrayOutputStream()
Ø ByteArrayOutputStream(int)

Some of the methods and its use is listed below in the table:

Method Use
size() Returns the current size of the buffer
toByteArray() Creates a new byte array
toString() Converts the buffer content into a string
write(int) Writes the specified byte into the byte array output
stream
write(byte[], int, int) Writes some byes as specified from the byte array to
the byte array output stream
writeTo(OutputStream) Writes the content of the byte array output stream to
the specified stream in the argument

Example:

import java.io.*;
class bytearrayoutput
{
public static void main(String ar[]) throws IOException
{
ByteArrayOutputStream in=new ByteArrayOutputStream();
String s="Globsyn";
byte b[]=s.getBytes();
in.write(b);
byte b1[]=in.toByteArray();
ByteArrayInputStream on=new ByteArrayInputStream(b1);
int c;
while((c=on.read())!=-1)
{
System.out.println((char)c);

SR/JAVP1/301/1001/SC/3.0 191
Internet Programming Using Core Java – Part 1

}
}
}

Ø Save the above code in a file bytearrayoutput.java


Ø Compile it using javac bytearrayoutput.java
Ø Execute it using java bytearrayoutput

The output is:

FileOutputStream

It is used to write byte or array of bytes to a File.

Constructors are:

Ø FileOutputStream(File)
Ø FileOutputStream(String)
Ø FileOutputStream(String, Boolean)

Methods and the use are listed below:

Method Use
close() Closes the file output stream and release
the system resources used
finalize() Ensures that the close() method is called
when there are no reference to it.
write(byte[]) Writes the byte array to the file output
stream

SR/JAVP1/301/1001/SC/3.0 192
Internet Programming Using Core Java – Part 1

write(byte[],int, int) Writes the bytes from the byte array as


specified to the file output stream
write(int) Writes the specified bytes to the file output
stream

Example:

Consider a situation where you want to store some data in a file and again retrieve it.

Create a text file test.txt

Write the following code.

import java.io.*;
public class Fileinout {
public static void main(String args[]) throws IOException
{
FileOutputStream outStream = new
FileOutputStream("test.txt");
String s = "This is a test.";
for(int i=0;i<s.length();++i)
outStream.write(s.charAt(i));
outStream.close();
FileInputStream inStream = new
FileInputStream("test.txt");
int inBytes = inStream.available();
System.out.println("inStream has "+inBytes+" available
bytes");
byte inBuf[] = new byte[inBytes];
int bytesRead = inStream.read(inBuf,0,inBytes);
System.out.println(bytesRead+" bytes were read");
System.out.println("They are: "+new String(inBuf,0));
inStream.close();
}
}

The output is:

Note: After the grogram is executed the test.txt file will contain the text “This is a test”

FilterInputStream

SR/JAVP1/301/1001/SC/3.0 193
Internet Programming Using Core Java – Part 1

This class is the baseclass of classes BufferedOutputStream, DataOutputStream and


PrintStream that filter input streams. These streams provide additional functionality. The
class FilterOutputStream overrides all methods of OutputStream.

BufferedOutputStream

It is used to write chunks of data to buffer

Constructors are:

Ø BufferedOutputStream(OutputStream)
Ø BufferedOutputStream(OutputStream, int)

Some of the methods and its use are listed below in the table:

Method Use
write(byte[], int, int) Write the specified amount of bytes
from a byte array to buffered output
stream
write(int) Write specified amount of bytes
flush() Flushes the buffered output stream

DataOutputStream

A data output stream lets an application to write primitive Java data types to an output
stream.

Constructors are:

Ø DataOutputStream(OutputStream)

Some of the methods and its use are listed below in the table:

Method Use
write(int) writes data to a data output stream
write(byte[]. int, int) Writes certain amount of data to data output
stream from a Byte array
writeBoolean() Writes boolean value to data output stream
writeByte() Write a signed 8-bit to data output stream
writeChar() Writes a Unicode character to data output stream
writeDouble() Writes a double to data output stream
writeFloat() Write a float to data output stream
writeInt() Reads a signed 32-bit integer from data input
stream

SR/JAVP1/301/1001/SC/3.0 194
Internet Programming Using Core Java – Part 1

writeLong() Writes a signed 64-bit integer to data output


stream
readShort() Writes a signed 16-bit number to data output
stream
PrintStream

The methods of this class are widely used in Java application. Whenever the print() or
println() method is sent to the System.out or System.err calss variables teen it implicitly
calls the PrintStream methods.

Constructors are:

Ø PrintStream(OutputStream)
Ø PrintStream(OutputStream, Boolean)

Some of the methods and its use:

Method Use
close() Closes the stream
print(char) Prints a character
print(double) Prints a double
print(float) Print a float number
print(String) Print a string
print(char[]) Prints a char array
print(long) Prints a long integer
print(int) Prints a integer
println(char) Prints a character and the control goes to the next
line
println(double) Prints a double and the control goes to the next line
println(float) Print a float number and the control goes to the next
line
println(String) Print a string and the control goes to the next line
println(char[]) Prints a char array and the control goes to the next
line
println(long) Prints a long integer and the control goes to the next
line
println(int) Prints a integer and the control goes to the next line

Here is a code sample:

try
{ FileOutputStream fo=new FileOutputStream(“myFile”);
DataOutputStream dd=new DataOutputStream(fo);
dd.writeDouble(123.456);
dd.writeInt(66);

SR/JAVP1/301/1001/SC/3.0 195
Internet Programming Using Core Java – Part 1

dd.close();
fo.close();
} catch(IOException e) {}

Here, the file “myFile” will be created with a double value and a float value. You can
read the data from this file using a DataInputStream.

SR/JAVP1/301/1001/SC/3.0 196
Internet Programming Using Core Java – Part 1

Character Stream

• Example of Character Stream :


– Reader Class
– Writer Class
Abstract Class

• Key methods:
– read()---> Returns an integer representation of
next available Character
– write()---> Writes a Single byte to an output
Stream

Character Streams

This type of Stream is used to read or write Unicode characters. It has two abstract
classes-- the Reader class and the Writer class.

These classes are again classified into two types: the low level classes communicate with
the I/O devices and the high level reader and writer classes communicate with low level
classes.

The functionality is almost similar to the InputStream and OutputStream classes except
that Reader and Writer class deals with the Unicode character.

Reader class contains a read() method to read a single character, an array of characters or
part of an array of characters. It returns –1 if it reaches at the end of the Input.

Here is the signature of different read() method:

int read() throws IOException


int read(char c[]) throws IOException
int read(char c[],int offset, int len) throws IOException

In the same way, the writer classes provide a write() method to write characters, Strings
or array of characters.

The signature of different write() methods:

void write(int ch) throws IOException

SR/JAVP1/301/1001/SC/3.0 197
Internet Programming Using Core Java – Part 1

void write(String str) throws IOException


void write(String str, int offset, int len) throws
IOException
void write(char ch[]) throws IOException
void write(char ch[], int offset, int len) throws
IOException

SR/JAVP1/301/1001/SC/3.0 198
Internet Programming Using Core Java – Part 1

Reader Class

BufferedReader FileReader

Takes input as To read the


LineNumberReader Buffered content of a
Character Stream File

Can read the Line Number

Reader Class
Example of a low level Reader is a FileReader class which takes a File Name as its Input.
The file must contain UTF Strings.
The Constructor are:

Ø FileReader(String pathname)
Ø FileReader(File f)

Examples of High level Readers are BufferedReader and LineNumberReader. These


classes take a low level Reader as its input.

BufferedReader class uses an internal buffer to hold a large block of data, thereby
minimising the I/O overhead.

The LineNumberReader class keeps track of the Line number of the text that has been
mentioned as its Input. There is a method called readLine() which returns the next Line
and getLineNumber() method returns the associated Line Number.

Here is a code fragment to use some of the Reader classes:

SR/JAVP1/301/1001/SC/3.0 199
Internet Programming Using Core Java – Part 1

try{
FileReader f=new FileReader(“myFile”);
LineNumberReader l=new LineNumberReader(f);
String s; int n;
while(( s=l.readLine() !=null)
{ System.out.println( l.getLineNumber() + “: “ + s);
}
l.close();
f.close();
} catch( IOException e) {}

Note: The Reader class supports InputStream class methods like read (), skip (), mark
(), markSupported (), reset () and close ()

Example:

import java.io.*;
class reader
{
public static void main(String s[]) throws Exception
{
FileReader f=new FileReader("c.txt");
int ch;
while( (ch=f.read())!=-1)
{
System.out.print((char)ch);
}
}

The output of this will display the content of c.txt file

SR/JAVP1/301/1001/SC/3.0 200
Internet Programming Using Core Java – Part 1

Writer Class

BufferedWriter PrintWriter
FileWriter

Ensures that
buffers are To write to a File
physically Provides formatted
written output methods

Writer Class

Examples of Writer classes are FileWriter, BufferedWriter and PrintWriter classes.

Here FileWriter class is a low level Writer class and the other two classes are High Level
Writer classes.

FileWriter class is used to write UTF Strings to the specified file.

The constructors are:

Ø FileWriter(String path)
Ø FileWriter(File f)

The BufferedWriter class is similar to the BufferedReader class except that it is used to
write large blocks of Data.

The PrintWriter class provides the character formatting capabilities. It supports the print()
and println() method for all types of data including objects.

Note: The Writer class supports OutputStream class methods like write (), flush () and
close ()

SR/JAVP1/301/1001/SC/3.0 201
Internet Programming Using Core Java – Part 1

CharArrayReader

• CharArray reader is an implementation of the


input stream which uses the character array
as the source.
• The constructors are :
– CharArrayReader(char array[])
– CharArrayRaeder(char array[],int start,int
numChars)

CharArrayReader
The CharArrayReader class is an implementation of the Input stream using a character
array as the source. The constructors of this class are as follows:

CharArrayReader(char array[]): In this constructor, the char array[] is the array 2


which acts as the source of the stream.

CharArrayReader(char array[], int start, int numChars): This constructor creates a


Subset of a particular array that begins with start and its length is numChars .

The following example make use of the CharArrayReader class:

import java.io.*;
public class DemoChar {
public static void main(String args[]) throws IOException{

String a = ”the king is great”;


int length = a.length();
char c1[] = new char [length];
a.getChars(0 ,length, c1,0);
CharArrayReader car1 = new CharArrayReader(c1);
CharArrayReader car2 = new CharArrayReader(c1,0,6);
int i;
System.out.println(“car1 is:”);
while((i = car1.read()) != -1)
{
System.out.print((char)i);
}

SR/JAVP1/301/1001/SC/3.0 202
Internet Programming Using Core Java – Part 1

System.out.println();
System.out.println(“car2 is:”);
while((i = car2.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
}
}

The output of the above program is:

SR/JAVP1/301/1001/SC/3.0 203
Internet Programming Using Core Java – Part 1

CharArrayWriter

• CharArrayWriter is the implementation of the


output stream which uses an array as the
destination.
• The constructors of this class are:
– CharArrayWriter()
– CharArrayWriter(int numChars)

CharArrayWriter
The CharArrayWriter class is an implementation of the output stream using a character
array as the destination.

The constructors of this class are as follows:

Ø CharArrayWriter (): In this constructor, a buffer with a default size is created.


Ø CharArrayWriter (int numChars): This constructor creates a buffer of a particular
size, the length of which is numChars.

The following example makes use of the CharArrayWriter class:

SR/JAVP1/301/1001/SC/3.0 204
Internet Programming Using Core Java – Part 1

import java.io.*;
public class DemoCharWriter {
public static void main(String args[]) throws
IOException{
CharArrayWriter cw = new CharArrayWriter();
String st = "This ends up in an array stream";
char buffer[] = new char[st.length()];
st.getChars(0,st.length(), buffer,0);
cw.write(buffer);
System.out.println("Buffer as a string");
System.out.println(cw.toString());
System.out.println("into an array");
char c[] = cw.toCharArray();
for (int a=0;a<c.length;a++){
System.out.print(c[a]);
}
}
}

The output is:

SR/JAVP1/301/1001/SC/3.0 205
Internet Programming Using Core Java – Part 1

Collection
• Collection represents a group of objects, known as
elements.
• It is used to store, retrieve and manipulate data.
• Some collection allow duplicate elements and others do
not.
• Collection framework is composed of three components.
– Interface :- Are abstract data types
– Implementations :- Are actual execution of interfaces
– Algorithms :- Are methods that perform computation on
objects that implement the interfaces

Collection
Collection represents a group of objects known as elements. It is used to store, retrieve
and manipulate data. Some collection allow duplicate elements and others do not. Some
are ordered and others unordered.

Collection framework is a undefined architecture for representing and manipulating


collections.

Collection framework is composed of three components.

Ø Interface :- Are abstract data types


Ø Implementations :- Are actual execution of interfaces
Ø Algorithms :- Are methods that perform computation on objects that implement the
interfaces

The advantages of using Collection framework:

Ø Reduces programming code by providing data structures and algorithms


Ø Increases program speed, as the implementations of each interface are
interchangeable
Ø Helpful in designing APIs
Ø Allows interoperability among unrelated APIs

SR/JAVP1/301/1001/SC/3.0 206
Internet Programming Using Core Java – Part 1

In the collection frame work the root interface is Collection. The methods of this
interface are common to all collections. The list of methods are listed in the following
table:

Return type Method Use


boolean add(Object o) Adds the object to the current collection
boolean addAll(Collection c) Adds all the elements of the collection c to
the current collection
void clear() Removes all the elements from the
collection
boolean contains(Object o) Checks if this collection contains the
specified element
boolean containsAll(Object o) Checks if this collection contains all the
elements in the specified collection
boolean equals(Object o) Compares the specified object with
collection
boolean isEmpty() Checks is the collection contains no
elements
boolean remove(Object o) Removes a single instance of the specified
element
boolean removeAll(Object o) Removes all the collection elements
int size() Returns the numeb rof elements in the
collection
object toArray() Returns a copy of the current collection to
an object array
object toArray(Object o[]) Returns a copy only those elements of the
current collection whose type matches with
object “o” to an array object.
boolean retainAll(Collection c) Retains only the elements of the Collection
“c” in the current collection and removes
the other elements.
int hashCode() Returns the hashcode of the current
collection

We will be discussing about the collection interfaces List, Map and Set Interface.

SR/JAVP1/301/1001/SC/3.0 207
Internet Programming Using Core Java – Part 1

Set Interface
• Set interface extends Collection interface.
• It does not allow duplicate elements
• It uses the methods of Collection interface.
• It restricts the use of add(), equals() and
hashCode() methods.

Set Interface
The Set interface extends the Collection interface. It contains no duplicate elements i.e. it
does not contain elements e1 and e2 where e1.equalsTo(e2). It uses the methods of
collection interface and does not define any methods of its own. This interface models
the mathematical set abstraction.

It restricts the add() method because it returns false if the user tries to add a duplicate
element to the set. The equals?(0 and the hashCode() methods are also restricted.

There are two set implementations:

Ø HashSet :- Stores elements in a hash table


Ø TreeSet :- Stores elements in a red-black tree

SR/JAVP1/301/1001/SC/3.0 208
Internet Programming Using Core Java – Part 1

List Interface
• List interface extends the Collection interface
• It is an ordered Collection
• The user has the control over where in the list
each element is inserted
• The list can contain duplicate elements
• User has access to elements by their integer
index
• In addition to Collection interface the interface
defines some of its own methods

List Interface
List interface extends the Collection interface. It is an ordered Collection and the user has
the control over where in the list each element is inserted. Moreover, the list can contain
duplicate elements.

User has access to elements by their integer index. In addition to Collection interface the
interface defines some of its own methods. Some of these methods are listed below:

Return type Method Use


void add(int Index, Object o) Inserts the element “o” at the position
specified by index in the List
boolean addAll(Collection c) Appends all the elements of the
collection to the List
boolean addAll(int index Collection c) Inserts all the elements of the
collection to the List at the position
specified by index
Object get(int index) Returns the object at the position
specified by the index
int indexOf(Object o) Returns the index of the object “o”
int lastIndexOf(Object o) Returns the index of the object “o”
searching from last
Object remove(int index) Removes the element at the position
specified by index from the List
Object set(int index, Object o) Replaces the element at the position
specified by index with “o”
List SubList(int formIndex, int Returns a list of element between
toIndex) fromIndex inclusive and toIndex,
exclusive.

SR/JAVP1/301/1001/SC/3.0 209
Internet Programming Using Core Java – Part 1

Map Interface
• An object that maps keys to values
• It cannot contain duplicate values
• Each key can map to at most one value only

Map Interface
An object that maps keys to values. It cannot contain duplicate values. Each key can map
to at most one value only. The methods present in this interface are listed below in the
table.

Return type Method Use


void clear() Removes all the mapping from the current
map
boolean containsKey(Object key) Returns true if the current map contains a
mapping for the specified key
boolean containsKey(Object value) Returns true if the current map maps to one
or more keys to the specified value
Set entrySet() Rerurns a set view of the mappings
contained in the map
boolean equals(Object o) Compares the if the object “o” is equal to
the current map
Object get(Object key) Returns the value to which the current
maps the key key
int hashCode() Returns the hashcode value of this map
boolean isEmpyt() Checks if the current map contains any
key-value mappings
Set keySet() Returns a set of view of the keys in the
current map
Onject remove(Object key) Remove any mapping of the current
mapping
int size() Returns the number of key-value mappings
in the current map

SR/JAVP1/301/1001/SC/3.0 210
Internet Programming Using Core Java – Part 1

Collection values() Returns a collection view of the values


contained in the current map.

SR/JAVP1/301/1001/SC/3.0 211
Internet Programming Using Core Java – Part 1

Quiz

Quiz
1. Fill in the blanks:

a) Stream is a sequence of _________________.


b) FileInputSytream class is used to ___________________________.
c) We can create a directory in Java using __________________ command.
d) BufferedReader class is used for_______________________.
e) Three methods present under File class are _______. _________ and ____________.

2. Select the correct answer(s)

a) Which of these can act both as an input stream and output stream?
• A file
• A network connection
• A pipe
• A string
• An array of chars

b) Which of these methods in the File class will return the name of the entry excluding the
specification of the directory in which it resides?

• GetAbsolutePath()
• GetParent()
• GetName()
• GetPath()
• None of the above

c) What will the method length in the class File return?

SR/JAVP1/301/1001/SC/3.0 212
Internet Programming Using Core Java – Part 1

• File
• FileDescriptor
• FileNameFilter
• String
• Char[]

d) Which of these classes provides the methods for writing binary representations of primitive
Java types?

• DataOutputStream
• FileOutputStream
• ObjectOutputStream
• PrintStream
• BufferedOutputStream

e) Which of these are valid parameter types for the write (0 method of the writer class?

• Type String
• Type char
• Type char[]
• Type int

3. Explain the methods used in the File class.


4. What does a byte stream do?
5. What are the abstract classes in character stream? Explain their working.
6. Name some of the principle classes and interfaces of java.io package.

7. Write the code for demonstrating a file having file name as Globsyn, the path as
/java/knowledge, whether the file exists or not, it’s properties (i.e readable,writable or both)
whether it is a directory or not and the file size.

8. Write a program using the reader class, which will acccept the some user input, and will
display onto the screen what the user as given as input.

9. Write a program using the writer class, which accepts some user input text, and calculates the
total number of bytes present in the text, and the total number of bytes read by the system.

SR/JAVP1/301/1001/SC/3.0 213
Internet Programming Using Core Java – Part 1

Summary

• Handle File I/O


• Appreciate the file class
• Implement Java streams
• Use the reader and writer class
• Get acquainted with the Java Collection Framework

Summary

After this chapter, you are now able to:

Handle File I/O


Appreciate the File class
Implement Java Streams
Use the Reader & Writer classes
Get acquainted with the Java Collections Framework

SR/JAVP1/301/1001/SC/3.0 214

You might also like