Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
65 views66 pages

CHAPTER - 3 Java PACKAGES, INTERFACES & EXCEPTION HANDLING

The document provides an overview of Java packages, including built-in and user-defined packages, their hierarchical structure, and how to create and use them. It also explains access modifiers (private, default, protected, public) and interfaces, detailing their characteristics and differences from classes. Additionally, it covers exception handling, highlighting compile-time and run-time errors in Java programming.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views66 pages

CHAPTER - 3 Java PACKAGES, INTERFACES & EXCEPTION HANDLING

The document provides an overview of Java packages, including built-in and user-defined packages, their hierarchical structure, and how to create and use them. It also explains access modifiers (private, default, protected, public) and interfaces, detailing their characteristics and differences from classes. Additionally, it covers exception handling, highlighting compile-time and run-time errors in Java programming.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

 Package in java is a mechanism to encapsulate a group of

classes, sub packages and interfaces.


 Packages act as “Containers” for classes.
 Packages concept similar to “class libraries” in other
languages.
 Package in java can be categorized in two form, built-in
package and user-defined package.
Built-in package
 Java has already defined some packages and included that in
java software, these packages are known as built-in packages
or predefined packages.
 These packages contains a large number of classes and
interfaces useful for java programmers for different
requirements.
 Programmers can import these packages in their program and
can use the classes and interfaces of these packages in that
program.
 Built-in packages comes automatically in
your jdk/jre download. These packages comes in the form of
jar files.
 There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
Java API Packages
 Java API provides a large number of classes grouped into
different packages according to functionality.

 java.lang : Language support classes. These are classes


that java compiler itself uses and therefore they are
automatically imported. They include classes for
primitive types, strings, math functions, threads and
exceptions.
 java.util : Contains the collections framework, some
internationalization support classes, properties, random
number generation classes. Classes like ArrayList, LinkedList,
HashMap, Calendar, Date, TimeZone etc are part of this
package.
 java.io : Input/output support classes. They provide facilities
for the input and output of data.
 java.applet : Classes for creating and implementing applets.
 java.net : Provides classes for implementing networking
applications. Classes like Authenticator, HttpCookie, Socket,
URL, URLConnection, URLEncoder, URLDecoder etc are
part of this package.
 java.awt : Set of classes for implementing graphical user
interface. They include classes for windows, buttons, lists,
menus and so on.
Using System Packages
 The packages are organized in a hierarchical structure.
 There are two ways of accessing the classes stored in a
package.
The first approach is to use the fully qualified class name of
the class that we want to use.
This is done by using the package name containing the
class and then appending the class name to it using the
dot operator.
Example : if we want to refer to the class
ByteArrayInputStream in the io package, then we
may do so as follows:
import java.io.ByteArrayInputStream;
Notice that io is a package within the package java and
the hierarchy is represented by separating the levels with
dots.
 In many situations, we might want to use a class in a number
of places in the program or we may like to use many of the
classes contained in a package. We may achieve this easily as
follows:
import package.classname;
Or
import packagename;
 These are known as import statement and must appear at the
top of the file, before any class declaration, import is a
keyword.
The second statement imports every class contained in the
specified package.
Ex: import java.io.*;
Will bring all classes of java.io package.
Creating Packages
 We must first declare the name of the package using the package
keyword followed by a package name.
 This must be the first statement in a java source file(except for
comments and white spaces).
 Then we define a class, just as we normally define a class.
 Example:
package firstPackage; //package declaration
public class FirstClass //class definition
{
………….(body of class)
}
Note : Here the package name is firstPackage. The class
FirstClass is now considered a part of the firstPacakage.
 Declare the package at the beginning of a file using the form:
package packagename;
 Define the class that is to be put in the packages and declare it
public.
 Create a subdirectory under the directory where the main
source files are stored.
 Store the listing as the classname .java file in the subdirectory
created.
 Compile the file. This creates .class file in the subdirectory.

Remember : That case is significant and therefore the


subdirectory name must match the package name exactly.
 Java supports the concept of package hierarchy.
 This is done by specifying multiple names in a package
statement, separated by dots.
 Example: package firstPackage.secondPackage;
 This approach allows us to group related classes into a
package and then group related packages into a large package.
 A java package file can have more than one class definitions.
In such cases, only one of the classes may be declared public
and that class name with .java extension is the source file
name.
 When a source file with more than one class definition is
compiled, java creates independent .class files for those
classes.
Remember : To store this package in a subdirectory named
firstPackage/secondPackage.
 The import statement can be used to search a list of packages for a
particular class.
 The same approaches can be used to access the user-defined
packages as well.
 Example of importing a particular class:
import firstPackage.secondPackage.MyClass;
Import a single class that is MyClass.
 We can also use another approach as follows:
import packagename.*;
Import the whole package.
Note :
 That the statement must end with a semicolon(;)
 The import statement should appear before any class definitions in a
source file.
 Multiple import statements are allowed.
//This file is stored in Example folder with the name
Demo.class.
import mypack.*;
class Demo
{
public static void main(String args[])
{
Dell d=new Dell();
HP h =new HP();
d.disp();
h.display();
}
}
Using A Package
//This file is save in mypack folder which is under Example
folder
//file saved as Dell.class

package mypack; //package package-name


public class Dell
{
public void disp()
{
System.out.println("Dell Class");
}
}
Using A Package
//This file is save in mypack folder which is under Example
folder
//file saved as HP.class

package mypack;
public class HP
{
public void display()
{
System.out.println("HP Class");
}
}
 Step -1 : Download and install jdk in your system.
 Step - 2 : Now, open C:\program filesjavajdk-1.8bin
and copy all the path.
 Step - 3 : In window search and select “Edit the system
variables”
 Step – 4: Now, select ‘Environment Variables” in Advanced
 Step – 5: select path in user variables for admin and click on
the edit button ,next in variable value give semicolon and paste
the jdk path after that click on ok button.
 Step – 6: select path in system variables and click on the edit
button ,next in variable value give semicolon and paste the jdk
path after that click on ok button.

Finally click on ok button two times.


 The access modifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class. We can change
the access level of fields, constructors, methods, and class by
applying the access modifier on it.
Private: The private access modifier is accessible only within the
class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class
contains private data member and private method. We are accessing
these private members from outside the class, so there is a compile-
time error.
class A{ public class Simple{
private int data=40; public static void main(String args[]){
private void msg() A obj=new A();
{ System.out.println(obj.data);
System.out.println(“hi"); //Compile Time Error
} obj.msg();//Compile Time Error
} }
}

 Note: A class cannot be private or protected except nested class.


Default : If you don't use any modifier, it is treated as default by
default. The default modifier is accessible only within package. It
cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and
public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We
are accessing the A class from outside its package. Since A class is not
public, so it cannot be accessed from outside the package.
//save by A.java //save by B.java
package pack; package mypack; import pack.*;
class A{ class B{
void msg() public static void main(String args[]){
{ A obj = new A();
System.out.println(“Hi"); //Compiled Timed Error
} obj.msg();//Compiled Timed Error }
} }
 Note : In the above example, the scope of the class A and its method
msg() is default so it cannot be accessed from outside the package.
Protected: The protected access modifier is accessible within package
and outside the package but through inheritance only.
 The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class. It provides
more accessibility than the default modifier.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The
A class of pack package is public, so can be accessed from outside the
package. But msg method of this package is declared as protected, so it
can be accessed from outside the class only through inheritance.
//save by A.java //save by B.java
package pack; package mypack;
public class A{ import pack.*;
protected void msg() class B extends A{
{ public static void main(String args[]){
System.out.println("Hello"); B obj = new B();
} obj.msg();
} }
}
Output:Hello
Public : The public access modifier is accessible everywhere. It
has the widest scope among all other modifiers.
Example of public access modifier
//save by A.java //save by B.java
package pack; package mypack;
public class A{ import pack.*;
public void msg() class B{
{ public static void main(String args[]){
System.out.println("Hi"); A obj = new A();
} obj.msg();
} }
}

Output: Hi
Simple example of java package
 The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Syntax: javac -d directory javafilename
To Compile: javac -d . Simple.java
To Run: java mypack.Simple Output: Welcome to package
Note: The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. The . represents the current folder.
An interface in Java is a blueprint of a class. Like classes, interface
contain methods and variables but with a major difference. The
difference is that interfaces define only abstract methods and final
fields.
Syntax for interface
interface InterfaceName
Here, interface is the key word
{
and InterfaceName is any valid
variables declaration; java variable(just like class
methods declaration; names).
}

Variables Declaration : static final type VariableName = value;


Methods Declaration : return-type methodName1(parameter_list);
Note: All variables are declared as constants. Methods
declaration will contain only a list of methods without any body
statement.
 Interface by default abstract body. Interface variables is always static
& final.
 We can’t defined non-static variables inside interface body.
 An interface do not contain any constructors.
 We can’t create an object for interface.
 The default access modifier in a interface body is public.
 All methods inside interface are abstract methods.
 Inside interface any abstract methods are allowed, can’t define
concrete methods in a interface(concrete methods means method
declaration with method body).
 Static methods are allowed from java version 1.8 onwards.
 An interface is not extended by a class, it is implemented by a class
 An interface can extend multiple interfaces.
Class Interface
The members of a class can be The members of an interface are
constant or variables. always declared as constant.
i.e., their values are final.
The class definition can contain the The methods in an interface are
code for each of its methods. That is, abstract in nature,
the methods can be abstract or non- i.e., there is no code associated with
abstract. them. It is later defined by the class
that implements the interface.
It can be instantiated by declaring It cannot be used to declare objects.
objects. It cam only be inherited by a class.
It can use various access specifiers It can only use the public access
like public, private, or protected. specifier.
It can be inherited by another class It can be inherited by a class using
using the keyword extends the keyword implements and it
interface inherits another interface
using extends keyword
 Like classes, interface can also be extended.
 An interface can be sub-interfaced from other interfaces. The new
sub-interface will inherit all the members of the superinterface in
the manner similar to subclass.
 This is achieved using the keyword extends .

Name1(I)
 Syntax : interface name2 extends name1
{
body of name2 Extension
}
Name2(I)
Example:
interface ItemConstants
{
ItemConstants(I) ItemMethods(I)
int code = 1001;
String name = “Fan”; Extension
}
interface ItemMethods
{ Item(I)
void display();
}
interface Item extends ItemConstants.ItemMethos
{
………..
}
 Interface are used as “superclass” whose properties are inherited by
classes.
 A class which implements the abstract method of an interface is
know as implementation class. A class can implement an interface
by using implements keywords.
 Class can implement any number of interface.
 Empty interface without any methods and variables is known as
marker interface.
 Syntax: Interfacename(I)

class classname implements interfacename


{ Implementation
body of class
classname(C)
}
Example:
interface Printable{ //interface
void print(); //abstract method
}
interface Showable{ //interface
void show(); //abstract method
}
class Demo implements Printable,Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
Demo obj = new Demo();
obj.print();
obj.show();
}
}

Output:
Hello
Welcome
 We can declare interfaces as members of a class or another
interface. Such an interface is called a member interface or
nested interface.
 Interface in a class Interfaces (or classes) can have only public
and default access specifiers when declared outside any other
class.

 Syntax of Nested Interface


interface First{
interface Second{
……..
}
}
import java.util.*;
interface Test {
interface Yes {
void show();
}
}

class Testing implements Test.Yes {


public void show()
{
System.out.println(“Hello My Dear Students");
}
}
class A {
public static void main(String[] args)
{
Test.Yes obj;
Testing t = new Testing();
obj = t;
obj.show();
}
} Output:
Hello My Dear Srudents
EXCEPTION HANDLING
Errors may broadly be classified into two categories
 Compile-time errors.

 Run-time errors.

Compile-Time Errors
 All syntax errors will be detected and displayed by the java compiler
and therefor these errors are known as compile-time errors.
 The compiler display an error, it will not create the .class file. It is
therefore necessary that we fix all the errors before we can successfully
compile and run the program.
 Most of the compile-time errors are due to typing mistakes.
Example: class Demo{
public static void main(String[] args){
System.out.println(“Hello”) //Missing;
}
Error1.java : 3: ‘;’ expected
}
System.out.println(“Hello”)
^ 1 error
 A single error may be the source of multiple errors later in the
compilation. For example, use of an undeclared variable in a
number of places will cause a series of errors of type “undefined
variable”.
 The most common problems are:
 Missing semicolons.
 Missing(or mismatch of) brackets in classes and methods.
 Misspelling of identifiers and keywords.
 Missing double quotes in strings.
 Use of undeclared variables.
 Incompatible types in assignments / initialization.
 Bas references to objects.
 Use of = in place of == operator and so on.
 Other errors we may encounter are related to directory paths. An
error such as javac : command not found means that we have
 not set path correctly.
 A program may compile successfully creating the .class file but may
not run properly therefor these errors are known as Run-time
errors.
 The most common problems are:
 Dividing an integer by Zero.
 Accessing an element that is out of the bounds of an array.
 Trying to store a value into an array of an incompatible class or
type.
 Trying to cast an instance of a class to one of its subclasses.
 Passing a parameter that is not in a valid range or value for a
method.
 Trying to illegally change the state of a thread.
 Attempting to use a negative size for an array.
 Converting invalid string to a number.
 Accessing a character that is out of bounds of a string.
Example:
class Error
{
public static void main(String[] args)
{
int a = 10;
int b = 5;
int c = 5;
int x = a/(b-c); //Division by zero
System.out.println(“x = “ + x);
int y = a/(b+c);
System.out.println(“y = “ + y);
}
} java.lang.ArithmeticException: / by zero
at Error.main(Error.java:10)
 Exception is an abnormal condition.
 Exception is a condition that is caused by a run-time error in the
program.
 When the java interpreter encounters an error such as diving an
integer by zero, it creates an exception object and throws it( i.e.,
informs us that an error has occurred).
 If the exception object is not caught and handled properly, the
interpreter will display an error message.
 Error handling code that performs the following tasks.
 Find the problem(Hit the exception).
 Inform that an error has occurred(Throw the exception).
 Receive the error information(Catch the exception).
 Take corrective actions(Handle the exception).
Exception Type Cause of Exception
ArithmeticException Caused by math errors such as
division by zero.

ArrayIndexOutOfBoundsExcepti Caused by bad array indexes.


on

ArrayStoreException Caused when a program tries to


store the wrong type of data in an
array.

FileNotFoundException Caused by an attempt to access a


nonexistent file.
Exception Type Cause of Exception
IOException Caused by general I/O failures,
such as inability to read from a
file.
NullPointerException Caused by referencing a null
object.
NumberFormatException Caused when a conversion
between strings and number
fails.
OutOfMemoryException Caused when there’s not enough
memory to allocate a new object.
SecurityException Caused when an applet tries to
perform an action not allowed by
the browser’s security setting.
Exception Type Cause of Exception

StackOverFlowException Caused when the system runs out of


stack space.
StringIndexOutOfBoundsEx Caused when a program attempts to
ception access a nonexistent character
position in a string.

 The error handling code basically consists of two segments:


 To detect errors and to throw exceptions.
 To catch exceptions and to take appropriate actions.
Exceptions in Java can be categorized into two types :
 Checked exceptions : These exceptions are explicitly handled in
the code itself with the help of try-catch blocks. Checked
exceptions are extended from the java.lang.Exception class.
 Unchecked exceptions : These exceptions are not essentially
handled in the program code; instead the JVM handles such
exceptions. Unchecked exceptions are extended from the
java.lang.RuntimeException class.

It is important to note that checked and unchecked exceptions


are absolutely similar as far as their functionality is concerned;
the different lies only in the way they handled.
Keyword Description
try The "try" keyword is used to
specify a block where we should
place an exception code. It means
we can't use try block alone. The try
block must be followed by either
catch or finally.
catch The "catch" block is used to handle
the exception. It must be preceded
by try block which means we can't
use catch block alone. It can be
followed by finally block later.
finally The "finally" block is used to
execute the necessary code of the
program. It is executed whether an
exception is handled or not.
Keyword Description
throw The "throw" keyword is used to
throw an exception.

throws The "throws" keyword is used to


declare exceptions. It specifies
that there may occur an
exception in the method. It
doesn't throw an exception. It is
always used with method
signature.
try Block
Exception object
Statement that creator
causes an exception

Throws exception
Object
catch Block
Exception handler
Statement that
handles the exception
Exception handling mechanism
 Java uses a keyword try to preface a block of code that is
likely to cause an error condition and “throw” an exception.
 A catch block defined by the keyword catch “catches” the
exception “thrown” by the try block and handles it
appropriately.
 The catch block is added immediately after the try block.
 The try block can have one or more statements that could
generate an exception.
 If any one statement generates as exception, the remaining
statements in the block are skipped and execution jumps to the
catch block that is placed next to the try block.
 The catch block too can have one or more statements that are
necessary to process the exception.
 Remember that every try statement should be followed by
at least one catch statement; otherwise compilation error
will occur.
 Note that the catch statement works like a method
definition.
 The catch statement is passed a single parameter, which is
reference to the exception object thrown (by the try block).
 If the catch parameter matches with the type of exception
object, then the exception is caught and statements in the
catch block will be executed.
 The exception is not caught and the default exception
handler will cause the execution to terminate.
 Syntax of Exception handling
The basic concepts of exception handling are throwing an
exception and catching it.

try
{
statement //generates an exception
}
catch(Exception-type e)
{
statement; //processes the exception
}
 Using try and catch for exception handling.
class Error{
public static void main(String[] args){
int a = 10; int b = 5; int c = 5; int x, y ;
try{
x = a / (b-c); //Exception here
}
catch(ArithmeticException e){
System.out.println(“Division by Zero”);
}
y = a / (b+c);
System.out.println(“y = “ +y);
}
OUTPUT : Division by Zero
}
y=1
 When an exception in a try block is generated, the Java treats the
multiple catch statements like cases in a switch statement.
 The first statement whose parameter matches with the exception
object will be executed, and the remaining statements will be
skipped.
 Note : Java does not require any processing of the exception at
all. We can simply have a catch statement with an empty block to
avoid program abortion.
 Example:
catch (Exception e);
 The catch statement simply ends with a semicolon, which does
nothing. This statement will catch an exception and then ignore
it.
 It is possible to have more than one catch statement in the catch
block as illustrated below:
try
{
Statement ; //generates an exception
}
catch(Exception-Type-1 e)
{
Statement; //processes exception type 1
}
.
.
catch(Exception-Type-N e)
{
Statement; //processes exception type N
}
Example using multiple catch blocks
class Error{
public static void main(String[] args){
int a[] = {5, 10};
int b = 5;
try{
int x = a[2] / b – a[1];
}
catch(ArithmeticException e){
System.out.println(“Division by Zero”);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(“Array Index Error”);
}
catch(ArrayStoreException e){
System.out.println(“Wrong data Types”);
}
int y = a[1] / a[0]; Output : Array index error
System.out.println(“y = “+y); y=2
}
 Note : The array element a[2] does not exist because array a is
defined to have only two elements, a[0] and a[1]. Therefore, the
index 2 is outside the array boundary thus causing the block
catch(ArrayIndexOutOfBoundsException e)

 To catch and handle the error. Remaining catch blocks are


skipped.
 Java supports another statement known as finally statement that
can be used to handle an exception that is not caught by any of
the previous catch statements.
 finally block can be used to handle any exception generated
within a try block.
 It may be added immediately after the try block or after the last
catch block shown as follows:
 try{ try{
……… ……..
} }
finally{ catch{
………. ……….
} }
finally{
………..
}
class TestFinallyBlock {
public static void main(String args[]){
try{
int data=25/5; //do not throw any exception
System.out.println(data);
}
catch(NullPointerException e){ //catch won't be executed
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
} Output : 5
Finally block is always executed
Rest of the code
 The throw keyword is used to explicitly throw a single exception.
 There may be times when we would like to throw our own
exceptions. We can do this by using the keyword throw as
follows:

 Syntax :
throw new Trowabl’e subclass
 Exapmle:
throw new ArithmeticException();
throw new NumberFormatException();
Throwing our own exception
import java.lang.Exception;
class MyException extends Exception{
MyException(String message){
supre(message);
}
}
Class TestMyException{
public static void main(String[] args[]){
int x=5, y=1000;
try{
float z = (float) x / (float) y;
if(z < 0.01){
throw new MyException(“Number is too small”);
}
}
catch(MyException e){
System.out.println(“Caught my exception”);
System.out.println(e.getMessage());
}
finally{
System.out.println(“I am always here”);
} Output : Caught my exception
} Number is too small
} I am always here
 The object e which contains the error message “Number is too
small” is caught by the catch block which then displays the
message using the getMessage() method.
 The last line of output is produced by the finally block.
Java throws keyword
 We use the throws keyword in the method declaration to declare
the type of exceptions that might occur within it.
 The throws clause is used in such a situation. It is specified
immediately after the method declaration statement and just
before the opening brace.
Example : Use of throws
class Examplethrows
{
static void divide_m() throws ArithmeticException{
int x = 22, y = 0, z;
z = x/y;
}
public static void main(String[] args){
try{
divide_m();
}
catch(ArithmeticException e){
System.out.println(“Caught the exception “+ e);
}
}
}

Output : Caught the exception java.lang.ArithmeticException: / by zero


throw throws
Used to throw an exception for a Used to indicate what exception
method type may be thrown by a method

Cannot throw multiple exceptions Can declare multiple exceptions

Syntax: Syntax:
 throw is followed by an object  throws is followed by a
(new type). methods.
 used inside the method.  used with the method
signature.

You might also like