0% found this document useful (0 votes)
23 views

Bca Vi Java Unit03

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Bca Vi Java Unit03

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

STUDY MATERIAL

(for the Paper)

BCA-307: Object Technologies & Programming using Java


(Unit-III)
(of)
BCA-VI (Maharshi Dayanand University, Rohtak)

Compiled
(Strictly from Academic Purpose only)
(by)

Dr. Sandeep Maan


Assoc Prof in Computer Science
Govt. College for Girls, Sec-14, Gurugram
(Email ID: [email protected])

Contents Referred/Adopted from


(Book)
The Complete Reference, Seventh Edition
by
Herbert Schildt, THM 2007

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 1
MDU Syllabus
(BCA-307 : Object Technologies & Programming using Java)
UNIT – III
Packages: Defining Package, CLASSPATH, Package naming, Accessibility of Packages , using
Package Members.

Interfaces: Implementing Interfaces, Interface and Abstract Classes, Extends and Implements
together.

Exceptions Handling : Exception , Handling of Exception, Using try-catch , Catching Multiple


Exceptions , Using finally clause , Types of Exceptions, Throwing Exceptions, Writing Exception
Subclasses.

PACKAGES IN JAVA

We know each class must be given a unique name to avoid name collision. But this
may lead to the problem of exhausting of suitable name that describes the purpose
of the class. So, we need a method to choose a class name that is reasonably unique
and do not collide with the names chosen by OTHER PROGRAMMERS. This is
done using a mechanism called package where a chunk of classes is managed as a
group and are exposed only to the members of that group and not from outside. So,
if any other programmer now chooses same name for his class that is not part of
this package no issue of name collusion would ever arise. So, the programmer just
need to have knowledge of members of this chunk called as package. It is just like
a director in windows. In order to create a package first we create a windows
directory (assuming we are using windows operating system) by the name of
package.

Defining a package

It defined the name space in which the class is stored and is must be the first line
of the program. It the package statement is not included in the program then it class
name is put into the default package.
Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 2
Syntax:

package my;

Suppose the class file is stored in the subdirectory (subdir) in directory (mydir) of
windows then we shall use

package mydr.subdir.my;

Finding Package & Classpath

Now important question become how java run time system know where to look for
the package. There are three scenarios

1. Default: It will investigate present working directory. So, if package in some


sub directory of current directory is would be found.
2. We can specify the directory path using the CLASSPATH environment
variable.
3. We can set the directory path using the -classpath option with ‘java’ and
‘javac’ command to specify the directory path.

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 3
Accessibility of package

1. First we outline the accessibility of different class member with different


access modifier

private No access protected public


modifier
Same class Yes Yes Yes Yes
Same package No Yes Yes Yes
subclass
(Inheritence)
Same package No No Yes Yes
non sub class
Different package No No No Yes
sub class
(Inheritence)

2. Importing the package (Accessing the contents of the package): Import


statement is used to include a package in the program.
e.g.
import java.util.Date;

It imports Data class under the util package (directory).

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 4
e.g.

1. Program Sum.java //To create member of a package say “My”

package My; //Declare the package

public class Sum {

int sum;

public sum (int a, int b) {

sum =a + b ;

public void show () {

System.out.println(sum);

2. Program Try.java //To access member of package “My”

import My.*;
Class Try {
public static void main(String s[]) {
Sum s(1,2);
s.show();
}

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 5
Interface

They are fully abstract class(es) in JAVA (means their object cannot be created).
They are different from a Class (type) as

1. in them all variables (i.e. attributes) are final, and


2. methods (i.e. member functions) are abstract.

They are employed in java

1. to implement dynamic method resolution (Polymorphism) at run time means


that which interface method is to be called can be decided upon run time
while is case of classes it is decided at compile time.
2. to introduce flavour of multiple inheritance is JAVA.

Example

Step 01: Create an interface (suppose to find area of a circle)

interface Area {

float pi=3.14;

void area(int rad);

Step 02: Implement the interface: Now we define a class that would implement the
above interface.

public class My implements Area{

public void area(int rad) {

System.out.println(“Area=” + pi*rad*rad);

}
Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 6
}

Step 03: Accessing implementation through Interface reference

We can implement the interface by creating object of its implementing class e.g.

class Test {

public void static main (String s[]) {

Area a=new My();

a.area(4);

Here we cannot access other methods of class My.

Important Concepts:

1. Abstract Class: An abstract class is one whose object cannot created and
that can only be extended.
2. Polymorphism: Now let us define another class say Try that implements
the same interface.

public class Try implements Area {

public void area(int rad) {

System.out.println(“Area=” + rad);

//(AND)

class Test {

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 7
Try t=new Try();

t.area(4);

Here the output will be 4. Here the area method defined in class Test will be called
which is decided at run time.

3. Partial Implementation of Interface: If some class implementing the


interface do not implement it completely rather defines some of its abstract
methods, then that class must also be abstract i.e. its object cannot be created.
4. Nested Interface: An interface may be defined within the scope of some
other class or interface. Then it may be declared as public, private or
protected. Whereas a top level interface can either be public or default.
5. Extending an Interface and multiple inheritance in JAVA: An interface
can inherit another interface by extending it. E.g.

interface A {

int a=2;

interface B implements A {

public void sum (int x) {……}

And so on.

6. Multiple inheritance is implemented in java by impending more than one


interface in same derived class. A derived class can not extend more than
one base class in JAVA but it can implement multiple interface.
Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 8
7. Extend and Implement together

So we can say in JAVA a derived class can extend only one base class bur it can
simultaneously implement one or more interface e.g.

class try extends X implements A,B,C { …………………}

Exception Handling in JAVA

When we write a program there may be two type of errors viz. logical and physical.
Logical errors are those which are not caught by the compiler and program may
produce unexpected result(s) whereas the physical errors like syntax errors are
caught during the compile time.

Now an exception is an unwanted or unexpected event, which occurs during the


execution of a program i.e at run time, that disrupts the normal flow of the
program’s instructions and the program/application terminates abnormally if it is
not handled. It may be caused by

1. Invalid data entered by the user.


2. Files required not found.
3. Network & other hardware error

etc.

So we can summarize

Error: An Error indicates serious problem that a reasonable application should not
try to catch.

Exception: Exception indicates conditions that a reasonable application might try


to catch.

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 9
Exceptions in JAVA

1. Checked Exception: Exception those are checked at the compile time itself
and notified thereof like
public class My
{
public static void main (String s[])
{
File file=new File(“c:/tmp.txt”);
FileReader fr=new FileReader(file);
}

In this if file “tmp.txt” is not found compiler will notify and program won’t
be compiled itself.

2. Unchecked Exception: That occur at time of execution, are also called as


run time exceptions and include programming bugs, logical error etc.
public class My
{
public static void main (String s[])
{
int a=5, b=0;
System.out.println(a/b);
}
}
Here we are trying to divide by zero.

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 10
Exception Handling

1. Default: On occurrence of an unhandled exception an Object of type


Exception is created with current state of program & description about
exception and this is handed over to run time environment and programs
stops executing printing the exception information over the console.
2. JAVA provides a class hierarchy to tackle with exceptions. They are handled
via five key words i.e. try, catch, throw, throws and finally. Program
statement that we want to monitor for probable exceptions are written inside
the try block. In case of exception the control of program is transferred
directly to the catch block, bypassing the statement causing exception. We
can automate the system generated exception by using keyword throws and
all such exceptions will be handled by the Java system itself. If we want that
any code must be absolutely executed after try block is completed, then we
may write it into the finally block.

e.g.

public class My {

public static void main(String s[]) {

try {

int x=5;

int y = 0;

System.out.println(x/y);

catch (ArithmeticException e) {

System.out.println(“Divide by zero”);

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 11
}

We can have multiple catch block that will tackle different type of exceptions
like ArtihmeticException, IOException and so on. Here which catch block will
be executed depends upon the type of exception occurred.

3. Nested try Statement: We may have a try block that is nested inside the
other try block. In such case of an exception occurs for which no catch block
is specified inside inner try block then the catch block of outer try block
would be searched to handle the exception.
4. throw: We may write statement to throw an exception then the statement
after the throw statement in the try block are not executed and control will
be transferred to respective catch block.

e.g.

class My {

public void try () {

try {

………….

throw new ArithmeticException(“Error”);

……….

catch (ArtihmeticException ae){

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 12
{

…………………………

5. throws: It provides guard against those exceptions we do not want to handle


some exception by our self. It is necessary in Java to specify throws clause
to handle exceptions except errors and run time exceptions.

e.g.

public class My {

public static void try () {

…….

try {

throw new IllegalException(“try”);

It will cause error because neither the catch block is provided to handle the
exception nor throws has been implemented. So correct implementation would be

public class My {

public static void try () throws IllegalException{

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 13
…….

try {

throw new IllegalException(“try”);

6. finally: This block is always executed after try/catch blocks irrespective of


1. the exception is thrown
2. or it is caught by some catch block
3. or an exception actually occurred.

It is a very useful block which can be utilized to implement critical functions like
closing file handle, freeing up space. E.g.

public class My {

public void try(){

try {

……………

throw new RunTimeException(“Hello”);

} finally {

System.out.println(“Inside finally”);

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 14
}

Writing Exception Subclass

If we want to create an exception of custom type to be handled in the program, then


we make use of inbuilt Exception class. This class does not specify any method of
itself but inherits methods provided by Throwable class. It defines four type of
constructors. Two of these are viz.

1. Exception ()
2. Exception (String msg)

e.g. let us write a program with custom exception to ensue that a variable is not
assigned any value except ‘a’

Step 01: Write your exception class

class MyException extends Exception {

MyException(String a){

return (a);

Step 02: Create a class to implement your exception

class Test {

public void test (String x) {

if(x!=’a’) throw new MyException(x);

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 15
}

public static void main (String a[]) {

Test t=new Test();

t.test(‘b’);

Here custom exception will be thrown as value passed is not ‘a’.

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 16
Bibliography & Other References
1. Programming in Java, E Balagurusamy.
2. The Complete Reference JAVA, TMH Publication.
3. Beginning JAVA, Ivor Horton, WROX Public.
4. JAVA 2 UNLEASHED, Tech Media Publications.
5. Patrick Naughton and Herbertz Schildt, “Java-2 The Complete Reference”,
1999, TMH.
6. Java Programming by Dr. Ramesh et al., Unique Publications.

Compiled by: Dr. Sandeep Maan, Assoc Prof in Computer Sc, GCG Sec-14, Gurugram.
Reference: The Complete Reference, Seventh Edition, Herbert Schildt, THM 2007.
Note: For academic purpose only. For detailed explanation of contents please consult the above referred book
Page. 17

You might also like