Internet Programming Using Core Java - Part 1: Student Reference
Internet Programming Using Core Java - Part 1: Student Reference
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
• 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
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
SR/JAVP1/301/1001/SC/3.0 4
Internet Programming Using Core Java – Part 1
History of Java
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 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
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.
SR/JAVP1/301/1001/SC/3.0 8
Internet Programming Using Core Java – Part 1
Features of JAVA
Features of Java
The following definition of Java by Sun Microsystems lists all the features of Java.
Ø 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.
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.
Ø 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.
Ø 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
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.
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.
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
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.
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.
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.
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:
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:
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
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
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.
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.
Ø 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
Ø 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.
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.
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.
SR/JAVP1/301/1001/SC/3.0 20
Internet Programming Using Core Java – Part 1
Keywords
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:
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
Ø 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
SR/JAVP1/301/1001/SC/3.0 22
Internet Programming Using Core Java – Part 1
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.
SR/JAVP1/301/1001/SC/3.0 23
Internet Programming Using Core Java – Part 1
Operators
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:
SR/JAVP1/301/1001/SC/3.0 25
Internet Programming Using Core Java – Part 1
Ø Increment
Ø Decrement
The increment operator can be used in two ways:
++iVar;
IVar ++;
ivar1 = 5;
iVar2 = ++iVar1;
ivar1=5;
ivar1 = iVar1 + 1;
iVar2 = iVar1;
ivar1 = 5;
ivar2 = iVar1++;
SR/JAVP1/301/1001/SC/3.0 26
Internet Programming Using Core Java – Part 1
iVar1 = 5;
iVar2 = iVar1;
ivar1=iVar1 + 1;
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.
SR/JAVP1/301/1001/SC/3.0 27
Internet Programming Using Core Java – Part 1
Decision Constructs
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.
SR/JAVP1/301/1001/SC/3.0 28
Internet Programming Using Core Java – Part 1
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”.
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.
SR/JAVP1/301/1001/SC/3.0 30
Internet Programming Using Core Java – Part 1
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.
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
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 {
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 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 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”.
SR/JAVP1/301/1001/SC/3.0 33
Internet Programming Using Core Java – Part 1
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.
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
while(Boolean expression)
{
statements;
}
The loop executes only if the expression is true from the very
first time.
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.
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
do
{
statements;
} while(condition);
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 executes a set of statements for certain number of times until the condition is
matched. The general syntax for the for loop:
The for loop contains three parts and the use is:
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
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.
SR/JAVP1/301/1001/SC/3.0 39
Internet Programming Using Core Java – Part 1
Example:-
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.
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
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
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
To create an array, the type has to be specified. The syntax of declaring a one-
dimensional array is:
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:
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:
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 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:
char c[]={‘a’,’b’,’c’,’d’}
Values can also be assigned to each element of a single dimensional array as shown
below:
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:
SR/JAVP1/301/1001/SC/3.0 44
Internet Programming Using Core Java – Part 1
Multidimensional Arrays
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.
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:
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++;
}
}
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
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
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
Quiz
SR/JAVP1/301/1001/SC/3.0 48
Internet Programming Using Core Java – Part 1
Exercise
Q2) Find the errors in each of the following code segments and explain how to correct
it.
x = 1;
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
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
SR/JAVP1/301/1001/SC/3.0 51
Internet Programming Using Core Java – Part 1
SR/JAVP1/301/1001/SC/3.0 52
Internet Programming Using Core Java – Part 1
Defining a class
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
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:
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.
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.
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
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.
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:
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.
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 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);
}
}
SR/JAVP1/301/1001/SC/3.0 59
Internet Programming Using Core Java – Part 1
Methods
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.
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.
SR/JAVP1/301/1001/SC/3.0 60
Internet Programming Using Core Java – Part 1
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 :
SR/JAVP1/301/1001/SC/3.0 61
Internet Programming Using Core Java – Part 1
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.
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;
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:
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.
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.
class DemoClass {
int inum1;
int inum2;
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);
}
}
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;
class TestCallByRef {
public static void main (String args []) {
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.
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;
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
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.
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.
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:
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
Ø 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();
}
}
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
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.
SR/JAVP1/301/1001/SC/3.0 71
Internet Programming Using Core Java – Part 1
Method Overloading
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:
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;
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
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.
SR/JAVP1/301/1001/SC/3.0 75
Internet Programming Using Core Java – Part 1
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
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;
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.
1 2 3
SR/JAVP1/301/1001/SC/3.0 77
Internet Programming Using Core Java – Part 1
Inheritance
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 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 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
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 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;
}
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
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( );
}
}
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
SR/JAVP1/301/1001/SC/3.0 84
Internet Programming Using Core Java – Part 1
Overriding
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.
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
}
}
This is a furniture
This is a Chair
SR/JAVP1/301/1001/SC/3.0 86
Internet Programming Using Core Java – Part 1
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
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;
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 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);
}
}
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
{
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 :
SR/JAVP1/301/1001/SC/3.0 90
Internet Programming Using Core Java – Part 1
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:
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
SR/JAVP1/301/1001/SC/3.0 91
Internet Programming Using Core Java – Part 1
Abstract class
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:
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.
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
30
38
This is the Abstract class
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
Summary
SR/JAVP1/301/1001/SC/3.0 95
Internet Programming Using Core Java – Part 1
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
SR/JAVP1/301/1001/SC/3.0 96
Internet Programming Using Core Java – Part 1
Packages
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.
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.
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.
package pack.subpack;
However, the classes that we create in the package subpack must be stored in the
directory structure pack\subpack.
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.
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.*;
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:
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
package pack;
SR/JAVP1/301/1001/SC/3.0 100
Internet Programming Using Core Java – Part 1
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;
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.
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.
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
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.
SR/JAVP1/301/1001/SC/3.0 104
Internet Programming Using Core Java – Part 1
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 .
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);
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.
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.
interface ABC {
void method1();
void method2();
}
interface XYZ {
void method3();
}
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();
}
}
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
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:
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();
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);
}
}
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);
}
abcd
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
cd
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
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));
}
}
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.
Ø 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.
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);
}
}
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
Quiz
SR/JAVP1/301/1001/SC/3.0 118
Internet Programming Using Core Java – Part 1
Summary
Summary
SR/JAVP1/301/1001/SC/3.0 119
Internet Programming Using Core Java – Part 1
SR/JAVP1/301/1001/SC/3.0 120
Internet Programming Using Core Java – Part 1
Exceptions in Java
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:
SR/JAVP1/301/1001/SC/3.0 121
Internet Programming Using Core Java – Part 1
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.
Ø ClassNotFoundException
Ø IllegalAccessException
Ø InterruptedException
Ø ArithmeticException
Ø ArrayStoreException
Ø IllegalArgumentException
Ø IllegalMonitorStateException
Ø ArrayIndexOutOfBoundsException
SR/JAVP1/301/1001/SC/3.0 122
Internet Programming Using Core Java – Part 1
SR/JAVP1/301/1001/SC/3.0 123
Internet Programming Using Core Java – Part 1
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.
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.
10
12
13
SR/JAVP1/301/1001/SC/3.0 125
Internet Programming Using Core Java – Part 1
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);
}
}
}
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
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.
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.
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") ;
}
}
}
SR/JAVP1/301/1001/SC/3.0 128
Internet Programming Using Core Java – Part 1
SR/JAVP1/301/1001/SC/3.0 129
Internet Programming Using Core Java – Part 1
Ø 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.
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 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:
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
{
SR/JAVP1/301/1001/SC/3.0 132
Internet Programming Using Core Java – Part 1
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 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.
SR/JAVP1/301/1001/SC/3.0 134
Internet Programming Using Core Java – Part 1
Quiz
Quiz
SR/JAVP1/301/1001/SC/3.0 135
Internet Programming Using Core Java – Part 1
Exercise
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.
Q2) What happens if an exception occurs and an appropriate exception handler cannot be
found?
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
Summary
SR/JAVP1/301/1001/SC/3.0 137
Internet Programming Using Core Java – Part 1
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
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
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?
SR/JAVP1/301/1001/SC/3.0 139
Internet Programming Using Core Java – Part 1
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
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
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 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
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:
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:
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:
Dead state:
SR/JAVP1/301/1001/SC/3.0 144
Internet Programming Using Core Java – Part 1
SR/JAVP1/301/1001/SC/3.0 145
Internet Programming Using Core Java – Part 1
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 () 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.
Sets the name of the thread to that specified by newname. The signature of this method
is:
Returns a string that specifies the thread name. The signature of this method is:
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:
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:
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.
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:
SR/JAVP1/301/1001/SC/3.0 149
Internet Programming Using Core Java – Part 1
Thread Creation
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.
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
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 :
SR/JAVP1/301/1001/SC/3.0 152
Internet Programming Using Core Java – Part 1
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.
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:
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.
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:
The setPriority() method, belonging to the Thread class is used to set thread’s priority.
The syntax is:
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:
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.
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.
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.
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 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");
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.
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.
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("]");
}
}
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");
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
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.
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.
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("]");
}
}
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");
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
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:
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
2. Two reasons a thread could enter the dead state are _______ and ________.
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.
2. In Java, a higher priority runnable thread will preempt threads of lower priority.
4. The sleep method does not consume processor time while a thread sleeps.
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
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
SR/JAVP1/301/1001/SC/3.0 173
Internet Programming Using Core Java – Part 1
Introduction
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.
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
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
File Class
File Class supports three forms of constructors:
Ø File(String dir path) : Here Directory path is the directory path name of the file.
Ø File(String dir, String subpath) : Here dir is the Directory path specified as String
and subpath is the filename of the file.
Ø File(File dirObj, String subpath): This format is equivalent to the previous one,
except that the dirObj is a File object instead of String.
SR/JAVP1/301/1001/SC/3.0 176
Internet Programming Using Core Java – Part 1
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");
}
}
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:
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:
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
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]);
}
}
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
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.
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.
Ø 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
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
InputStream Class
The InputStream classes hierarchy is as shown below:
InputStream
SequenceInputStrea ByteArrayInputStrea
m FileInputStream m
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
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
FileInputStream
Constructors are:
Ø FileInputStream(File) :- Creates an Input file stream to reads data from a file object.
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
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:
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();
}
}
}
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)
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);
}
}
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.
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
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
ByteArrayOutputStream
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
}
}
}
FileOutputStream
Constructors are:
Ø FileOutputStream(File)
Ø FileOutputStream(String)
Ø FileOutputStream(String, Boolean)
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
Example:
Consider a situation where you want to store some data in a file and again retrieve it.
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();
}
}
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
BufferedOutputStream
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
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)
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
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
• 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.
In the same way, the writer classes provide a write() method to write characters, Strings
or array of characters.
SR/JAVP1/301/1001/SC/3.0 197
Internet Programming Using Core Java – Part 1
SR/JAVP1/301/1001/SC/3.0 198
Internet Programming Using Core Java – Part 1
Reader Class
BufferedReader FileReader
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)
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.
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);
}
}
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
Here FileWriter class is a low level Writer class and the other two classes are High Level
Writer classes.
Ø 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
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:
import java.io.*;
public class DemoChar {
public static void main(String args[]) throws IOException{
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();
}
}
SR/JAVP1/301/1001/SC/3.0 203
Internet Programming Using Core Java – Part 1
CharArrayWriter
CharArrayWriter
The CharArrayWriter class is an implementation of the output stream using a character
array as the destination.
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]);
}
}
}
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.
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:
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.
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:
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.
SR/JAVP1/301/1001/SC/3.0 210
Internet Programming Using Core Java – Part 1
SR/JAVP1/301/1001/SC/3.0 211
Internet Programming Using Core Java – Part 1
Quiz
Quiz
1. Fill in the blanks:
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
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
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
Summary
SR/JAVP1/301/1001/SC/3.0 214