Professional Documents
Culture Documents
Objectives
After studying this unit, you should be able to:
z Understand the concept of classes, method.
z Learn about inheritance, package and interface.
z Understand about exception handling.
7.1 Introduction
Java enables the user to deploy application on the internet .The future of computing is
highly influenced by the internet, and java will remain a big part of future. Java is the
internet programming language. Java is cross-platform, object oriented, network based,
multimedia ready. Its inception is in May 1995, it quickly became a mature language for
deploying mission critical application. Java is general-purpose programming language,
can be used to develop standalone applications. In this chapter we will study the basics
of java programming.
7.2 Class
Notes A class is a user defined data type with a template that serves to define its properties
and operations. Once the class has been defined, we can create ‘Variables’ of that type.
These variables are termed as instances of classes, which are the actual objects.
Class as Datatype
Java has four kinds of named data types and two categories of variables. The data
types are primitives, classes, interfaces and arrays. Variables can either contain
primitive values or refer to objects.
A class creates a new data type that can be used to create objects. A class creates
a logical framework that defines the relationship between its members.
When you declare an object of a class, you are creating an instance of that class.
Thus, a class is a logical construct. An object has physical reality.
Simple Class
class Movie
{
String title;
int length;
int cost;
char type;
void getdata (int x, int y, int z)
{
length = x;
cost = y;
type = z;
}
Movie (String s)
{
title = s;
}
}
Declaring Objects
Class is a static definition that enables us to understand all the objects of that class.
Objects exist at run time. They hold attributes and they send messages to each other
Classes, however, do not exist at run time.
Each instance of the class (that is, each object of the class) contains its own copy of
the variables.
In case of the movie class, each individual movie is an instance of movie. “Gone
with the wind” is one distinct instance of movie while “Last action her” is another. Each
has its own set of variables. For e.g. mov1 and mov2 objects have four instance
variables each – mov1.title, mov1.length, mov2.title, mov2.length.
New Operator
Each new object is identified within Java by a unique object reference.
objectref = new Classname( );
For e.g. to create two movie objects
z Movie Mov1 = new Movie (“Gone with the wind”);
z Movie mov2 = new Movie (“Last action Hero”);
The above statements create new instance variables of Movie type named mov1 and
mov2. New operator assigns object’s reference to mov1 and mov2 which points to the
location of that object in memory. New operator allocates memory for the new objects
and also calls a special initialization method in the class called constructor. It returns a
reference to the new object. New operator knows how much memory is required by
looking at the class definition. It calls the constructor to initialize the instance variables
in the new object. However, declaring a new object variable receives a chunk of
memory only large enough to hold a reference to an object.
Class definition typically includes:
z Access Modifier : Specifies the availability of the class from other .
Class.
z Class Keyword : Tells Java that the following code block defines a class.
z Instance Fields : Variable and constants that are used by objects of the
Class.
z Constructors : Methods having the same name as class, used to
Control the initial sate of any class object
z Instance Methods : Define the functions that can act upon objects in this
Class.
z Class Methods : Methods used to control the values of class fields.
public class employee
{
// Instance Variables
String custName;
String Address;
float Amt;
7.3 Method
A Java method is equivalent to a function, procedure, or subroutine in other languages
except that it must be defined inside a class definition. Instance methods form the
foundation of encapsulation and are a key to providing a consistent interface to the
class.
Adding Methods to Classes
Methods are declared inside the body of the class but immediately after the declaration
of instance variables. The general form of a method declaration is
Returntype methodName (parameter list)
{
Method-body;
}
z A Returntype can be a primitive type such as int, a class type such as string or void.
z A MethodName begins with a lowercase letter and compound words in the method
name should begin with uppercase letter according to Java convention.
z An optional parameter list/argument list must be inside parentheses, separated by
commas.
z The method-body must be enclosed in braces.
Return Value
The return type specifies the type of value the method would return. This could be a
simple data type such as int as well as any class type or it could even be void type if the
method does not return any value.
e.g.: class Box
{
double width;
double height;
double depth;
double volume( )
{
return width * height * depth;
}
class ABC
{
Use the dot operator with instance variable and to call instance methods. The general
syntax is
Notes Objref.instance variable;
Objref.MethodName (arguments);
7.4 Constructor
When an object is created, Java performs default initialization, char variables are set to
‘\u0000’, byte, short, int, long to zero, boolean to false, float to 0.0
All objects that are created must be given initial values. We can do it,
1. By assigning the value to instance variable using dot operator.
2. Through instance method for e.g. getdata( )
3. By using constructor method to initialize an object when it is first created.
Constructors have the same name as class itself.
Constructors do not specify a return type.
Constructor is called automatically by the run time system.
For e.g.
class Rectangle
{
int length, width;
Rectangle (int x, int y) // constructor
{
length = x;
width = y;
}
int rectArea( )
{
return (length * width);
}
}
class ABC
{
public static void main (String args[ ])
{ Rectangle rect = new Rectangle( )
Rectangle rect1 = new Rectangle (15, 10) //
calling constructor
int area1 = rect1. rectArea ( );
System.out.println (“Area1 = “+ area1);
}
}
If you do not provide any constructors, a default no-arg constructor is provided for you.
This constructor takes no arguments and does nothing. If you want a specific no
Discarding an Object:
z When you have finished using an object, you can set its reference to null. This
indicates that the variable no longer refers to the object and object will be marked
for garbage collection. The Java Virtual Machine automatically decrements the
number of active references to an object whenever an object is de-referenced, goes
out of scope.
z All Java objects automatically grab the memory that they need when they are
created, and when the object is no longer needed, the Java garbage collection
process reclaims the memory.
finalize ( ) Method
Notes JVM is supposed to run an object’s finalize method after it has decided that an object
has no references and thus, should be recovered, but before actually reclaiming the
memory.
Java manages memory automatically– so an object does not need to explicitly free
up any secondary memory it might have allocated. To allow an object to clean up
resources other than memory, such as open files, Java allows a class to provide a
finalize( ) method. Unfortunately, there is no guarantee as to when this will happen. It is
implementation specific.
If an object holds another resource such as a file, the object should reclaim it.
Finalize method is called automatically before garbage collection.
Example:
class test
{
int a;
test (int i)
{
a = i;
}
test incrbyten( )
{
test temp = new test (a+10);
return temp;
}
}
class Retob
{
public static void main (String args[ ])
{
test ob1 = new test (2);
test ob2;
ob2 = ob1.incrbyten( );
System.out.println (“ob1.a:” + ob1.a);
System.out.prinln (“ob2.a:” + ob2.a);
}
}
Output : ob1.a:2
ob2.a:12
Each time when incrbyten( ) is invoked, a new object is created, and a reference to it is
returned to the calling routine.
One of the most important uses of object parameters involves the constructor. You
may want to construct a new object so that it is initially the same as the existing object.
class rectangle
Amity Directorate of Distance and Online Education
122 Internet and Java Programming
{
int width;
Notes
int height;
rectangle (int w, int h)
{
width = w;
height = h;
}
rectangle (rectangle r)
{
width = r.width;
height = r.height;
}
}
class ABC
{
public static void main (String args[ ])
{
Rectangle rect1 = new Rectangle (10, 15);
Rectangle rect2 = new Rectangle (rect1);
}
}
7.9 Recursion
Recursion is a process by which a function calls itself repeatedly, until some specific
condition has been satisfied. The process is used for repetitive computations in which
each action is stated in terms of the previous result.
For e.g. to calculate the factorial of a positive integer quantity, the following
expression would be given:
n! = 1x2x3 - - - - xn where n is the specified integer. It can also be written as
n! = n x (n-1) !
This is a recursive statement of the problem in which the desired action is written in
terms of the previous result.
Now 1! = 1 by definition. This provides a stopping condition for recursion.
When a recursive program is executed, the recursive function calls are not
executed immediately. Rather, they are placed on a stack until the condition that
terminates the recursion is encountered.
The function calls are then executed in reverse order as they are “popped” off the
stack.
class f
{
int num;
int fact (int n)
{
if (n = = 1)
implement all of the methods specified in that interface. A class can implement many
interfaces but can extend only one class. The general syntax for defining interface is:
Notes
interface InterfaceName
{
variable declaration;
method declaration;
}
Here interface is a keyword and interfaceName is any valid Java variable.
Example:
interface Item
{
static final int code = 1001;
static final String name = "fan";
void display ( );
}
Variables are declared as constants using static final keywords. Note that the code for
display ( ) is not included in the interface. The class that implements this interface must
define the code for the method.
Example:
interface Area
{
final static float pi = 3.14F
float compute (float x, float y);
}
class Rectangle implements Area
{
public float compute (float x, float y)
{
return (x * y);
}
}
class Circle implements Area
{
public float compute (float x, float y)
{
Variables in Interfaces
Interface can be used to declare a set of constants that can be used in different classes.
The constant values will be available to any class that implements the interface.
class Students
{
int rollNumber;
void getNumber (int n)
{
rollNumber = n;
}
void putNumber( )
{
System.out.println (“RollNo.” + rollNumber);
}
}
class Test extends Students
{
float part1, part2;
void getMarks (float m1, float m2)
{
part1 = m1;
part2 = m2;
}
7.12 Package
One way of reusing the code is by extending classes and implementing the interfaces.
But this is limited to reusing the classes within a program. If we need to use classes
from some other programs without physically copying them into the program under
consideration, we use packages. Packages act as containers for grouping logically
related classes and interfaces.
Benefits of Packages
z Classes contained in packages of other programs can be easily reused.
z Two classes in two different packages can have the same name. They can be
uniquely identified by packagename.classname.
z Packages also provide a way for separating "design" from "coding".
z You can define classes inside a package that are not accessible by code outside
that package. You can also define class members that are only exposed to other
members of the same package.
If we want to refer to color class in awt package once in our program, we can do so by
java.awt.color
But when we want to use the same class at many places or we want to use many
classes from the same package we can use
import packagename.classname;
or
import packagename.*;
The second statement imports every class contained in specified package. Packages
can be named using the standard Java naming rules.
java.awt.Point pts [ ];
This statement declares an array of Point type objects using the fully qualified class
name.
Creating Packages
Notes To create a package, simply include a package command as the first statement in a
Java source file. Any class declared within that file will belong to the specified package.
If you omit the package statement, the class names are put into a default package
which has no name.
package first_package;
public class firstclass
{
}
The file should be stored as firstclass.java and should be located in a directory named
first_package. The compiled class file should also be stored in the directory that has the
same name as the package. Java also supports the concept of package hierarchy. This
is done by specifying multiple names in a package statement, separated by dots -
package firstpackage.secondPackage;
Store this package in a subdirectory named
first_package\secondPackage.
There is no practical limit on the depth of a package hierarchy except that which is
imposed by file system. A Java package file can have more than one class definition. In
such cases, only one of the classes may be declared as public and that class name with
.Java extension is the source file name. More than one file can include the same
package statement. The package statement simply specifies to which package the
classes defined in a file belong. Most real world packages are spread across many files.
A simple example:
Package firstpack;
class Acct
{
String Name;
int AcctNo;
float Balance;
Acct (String, int A, Float Bal)
{
name = n;
AcctNo = A;
Balance = Bal;
}
void disp( )
{
if (Balance < 0 )
System.out.println (“Warning”);
System.out.println (“name” + “Rs” + Balance);
}
}
class AccBalance
{
public static void main (String args[ ] )
{
Important Packages
java.lang They include classes for primitive types, strings, math functions,
threads and exceptions.
java.util Language utility classes such as vectors, hash tables, random
numbers, date etc.
java.io They provide facility for the input and output of data.
java.awt Include classes for windows, buttons, lists, menus and so on.
java.net Include classes for communicating with local computers as well as
with Internet server.
java.applet Classes for creating applets.
java.sql Classes for sending SQL statements to relational databases.
java.math Classes for extended precision arithmetic
7.13 Inheritance
Reusability is one of the important aspect of the OOP paradigm. Java supports the
concept of reusing the code that already exists. Inheritance allows the creation of
hierarchical classifications. Using inheritance, you can create a general class that
defines traits common to a set of related items. This class can then be inherited by
other, more specific classes each adding those things that are unique to it. A class that
is inherited is called superclass. The class that does the inheriting is called a subclass.
Defining Subclass
class subclassname extends superclassname
{
variable declarations;
method declarations;
}
The subclass now contains its own variables and methods as well as those of the
superclass.
class employee
{
int empno;
String name;
String address;
employee (int eno, String ename, String addr)
{
empno = eno;
name = ename;
address = addr;
}
disp( )
{
System.out.println(“eno”+empno+“name” + name);
}
}
7.14 Multithreading
Multithreading allows a running program to perform several tasks, apparently, at the
same time. Java uses threads to enable the entire environment to be asynchronous. It
makes maximum use of CPU because idle time can be kept to minimum. This helps
reduce inefficiency by preventing the waste of CPU cycles. For example, it is useful for
networked environment as data transfer over network is much slower than the rate at
which the computer works. Multithreading lets you gain access to this idle time and put
it to good use. Single-threaded system works on an event loop with polling approach.
In this model, a single thread of control runs in an infinite loop, polling a single event
queue to decide what to do next. Once this polling mechanism returns with a signal
(e.g. that a network file is ready to be read), then the event loop dispatches control to
the appropriate event handler. Until this event handler returns, nothing can happen in
the system. This wastes CPU time. The benefit of Java multithreading is that the main
loop / polling mechanism is eliminated.
The Java runtime system depends on threads for many things and all class libraries
are designed with multithreading in mind. Threads are used extensively in Java
enabled browsers such as Hot Java. A thread exists in several states, like-
z Running thread
z Ready to run as soon as it gets CPU time
z Suspended thread
z Suspended thread can be resumed
z Thread can be blocked
z Thread can be terminated.
Thread
Any single path of execution is called thread. The path is defined by elements such as
stack (for handling calls to other methods with the code) and set of registers to store
temporary memory. These elements are collectively known as context. Every program
has at least one thread. Each thread has its own stack, priority and virtual set of
registers. If there are two pieces of code that do not have the same context, then they
are executed in two different threads.
Threads subdivide the runtime behavior of a program into separate, independently
running subtasks. Switching between threads is carried out automatically by JVM. Even
in a single processor system, thread provides an illusion of carrying out several tasks
simultaneously. This is possible because switching between threads happens very fast.
When we create a thread object, it is said to be in newborn state. At this stage we
can start the thread using start( ) method or kill it using stop( ) method. The thread in
runnable state means that the thread is ready for execution and is waiting for CPU time.
Running state means CPU has given its time to the thread for execution.
A thread is said to be in blocked state when it is suspended, sleeping or waiting in
order to satisfy some condition. The suspended thread can be revived by using the
resume( ) method. The Thread which is sleeping can enter into runnable state as soon
as the specified time period is elapsed. The thread in the wait( ) state can be scheduled
to run again using the notify( ) method. The thread dies when its run( ) method
completes its execution. A thread can be killed using the stop( ) method.
Notes
Where is Threads Used?
Word processing program handles a print request in a separate thread. Many users find
it convenient to continue working in word-processing application even after submitting
print request. Downloading a file from Internet and browsing another site are
implemented in different threads in the browser program. The Oracle database is
another example of a program that uses threads. Database “connect” request to a
common resource is handled by different threads. Operating Systems (specially
networked OS) are written using threads. Operating systems usually run many
applications such as a web browser and a word processing program at the same time.
A multithreaded program can indirectly benefit the end user because it can efficiently
use the CPU.
If a program is waiting for user response over the network, during this waiting time
other useful tasks can be performed simultaneously. A thread program can directly
benefit the user in applications that employ GUI components. When a button is pressed
to execute one task, the program can make other buttons available to perform other
independent programs.
In the above program, main thread initiated three new threads and started them.
The output of the program will not be sequential. They do not follow any specific order.
Notes They are running independently and each executes whenever it has a chance. Note
that every time we run this program we get different output sequence.
class DemoJoin
{
public static void main( )
{
Nthread ob1 = new Nthread (“One”);
Nthread ob2 = new Nthread (“Two”);
Nthread ob3 = new Nthread (“Three”);
System.out.println (“Thread one is alive” +
ob1.t.isAlive( );
System.out.println (“Thread Two is alive” +
ob2.t.isAlive( );
System.out.println (“Thread Three is alive” +
ob3.t.isAlive( );
try
{
System.out.println (“waiting for thread to finish”);
ob1.t.join( );
ob2.t.join( );
ob3.t.join( );
}
catch (InterruptedException e)
{
System.out.println (“Main thread Interrupted”);
}
System.out.println (“Thread one is alive” + ob1.t.isAlive(
);
System.out.println (“Thread Two is alive” + ob2.t.isAlive(
);
System.out.println (“Thread Three is alive” + ob3.t.
isAlive( );
System.out.println (“Main thread exiting”);
}
}
Sample Output : New thread : Thread [One, 5, main]
New thread : Thread [Two, 5, main]
At some point, the exception is caught and processed. Exceptions can be generated by
the Java run-time system or they can be manually generated by your code.
Notes
Java exception handling is managed by 5 keywords:
try, catch, throw, throws, finally.
When an error occurs, its mechanism performs the following tasks:
z Find the problem (hit the exception).
z Inform that an error has occurred (throw the exception).
z Receive the error information (catch the exception).
z Take corrective actions (handle the exception).
When an exception occurs within a Java method, the method creates an exception
object and hands it over to the run-time system. This process is called throwing an
exception. The exception object contains information about the exception including its
type and the state of the program when the error occurred.
When a Java method throws an exception, the Java runtime system searches all
the methods in the call stack to find one that can handle this type of exception. This is
known as catching the exception. If the runtime system does not find an appropriate
exception handler, the whole program terminates.
In traditional programming, error handling often makes the code more confusing to
read. Java separates the details of handling errors from the main work of the program
and they cannot be ignored.
The general form of exception handling block-
try
{
// block of code to monitor for errors
}
catch (ExceptionType exob)
{
// code to handle exception occurred
}
catch (ExceptionType exob2)
{
// code to handle exception
}
Types of Exceptions
All exception types are subclasses of the built in class Throwable. The hierarchy of
Throwable class is shown in the diagram.
java.lang.object
- java.lang.Throwable
java.lang.Error
Unrecoverable errors
java.lang.Exception
java.lang.Runtime Exception
various unchecked exceptions
various checked exceptions.
Uncaught Exceptions
class Error2
{
public static void main (String args[ ])
{
int a = 10;
int b = 5;
int c = 5;
int x = a/b-c;
System.out.println (“x = “+ x);
int y = a / (b+c);
System.out.println (“y =” + y);
}
}
When the Java run-time system detects attempt to divide by zero, it constructs a new
exception object and then throws this exception. This causes the execution of Error2
class to stops because once an exception has been thrown, it must be caught and dealt
with. In this example, exception is caught by the default handler.
Any exception that is not caught by your program, will be processed by default
handler. Java Runtime System generates an error condition which causes the default
handler to print the error and to terminate the program.
The errors are printed by Stack Trace. The stack trace will always show the
sequence of method invocations that led up to the error. The call stack is useful for
debugging because it pinpoints the precise sequence of steps that led to the error.
terminate. The scope of the variable named in the catch clause is restricted to the catch
code block.
Notes
A succession of catch clause can be attached to a try statement. If the thrown
exception cannot be assigned to the variable in the first catch clause, the JVM looks at
the second and so on. If the code block in the try statement executes without throwing
an exception, all of the catch clauses are ignored and execution resumes after the last
catch.
The order of the catch clause must reflect the exception hierarchy, with the most
specific exception first. If the first catch was the most general, none of the others could
be reached.
class Error3
{
public static void main (String args[ ])
{
int a = 10, b = 5, c = 5, x, y;
try
{
x = a/(b-c);
}
catch (Arithmetic Exception e)
{
System.out.println (“Division by zero”);
}
y = a/(b+c);
System.out.println (“y =” + y);
}
}
Output : Division by zero
y = 1
Note that the program did not stop at the point of exceptional condition. It catches the
error, prints appropriate error message and then continues the program execution after
catch block.
7.16 Summary
A Java method is a collection of statements that are grouped together to perform an
operation. Some methods may return a value of certain type which could be used like
any other value resulting from an expression. A method definition consists of a method
header and a method body. In creating a method, you give a definition of what the
method is to do. To use a method, you have to call or invoke it. There are two ways to
call a method; the choice is based on whether the method returns a value or not. When
calling a method, you need to provide arguments, which must be given in the same
order as their respective parameters in the method specification. The Java compiler
determines which method is used based on the method signature. Overloading
methods can make programs clearer and more readable. Methods that perform closely
related tasks should be given the same name. The scope of a variable is the part of the
program where the variable can be referenced. A variable defined inside a method is
referred to as a local variable. The scope of a local variable starts from its declaration
and continues to the end of the block that contains the variable. A local variable must be
declared before it can be used. Sometimes you will want to pass information into a