Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java3

The document states that the training data is current only until October 2023. No additional information or context is provided. The focus is solely on the training data timeline.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java3

The document states that the training data is current only until October 2023. No additional information or context is provided. The focus is solely on the training data timeline.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 64

Packages, Interfaces & Exception

Handling
Packages In Java

A java package is a group of similar types of


classes, interfaces and sub-packages.

Package in java can be categorized in two


form, built-in package and user-defined
package.

There are many built-in packages such as


java, lang, awt, javax, swing, net, io, util, sql
etc.
Advantage of Java Package

1) Java package is used to categorize the


classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


package keyword is used to create a
package in java.

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to
package");
}
}
Compiling pacakge

javac -d . Simple.java

The -d switch specifies the destination


where to put the generated class file. You
can use any directory name like /home (in
case of Linux), d:/abc (in case of windows)
etc. If you want to keep the package within
the same directory, you can use . (dot).
Types of packages:

• Built-in Packages
• User-defined packages

• Built in Package: These packages


consist of a large number of classes which
are a part of Java API.Some of the
commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g
classed which defines primitive data types, math
operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output
operations.
3) java.util: Contains utility classes which implement data
structures like Linked List, Dictionary and support ; for Date
/ Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the
components for graphical user interfaces (like button ,
menus etc).
6) java.net: Contain classes for supporting networking
operations.
User-defined packages

These are the packages that are defined by


the user. First we create a directory
myPackage (name should be same as the
name of the package). Then create the
MyClass inside the directory with the first
statement being the package names.
Example:

package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
How to import packages in Java?

Java has an import statement that allows


you to import an entire package (as in earlier
examples), or use only certain classes and
interfaces defined in the package.

The general form of import statement is:


import packagename.ClassName;
// To import a certain class only
import packagename.* ;
// To import the whole package
If you import a package, all the classes and
interface of that package will be imported
excluding the classes and interfaces of the
subpackages. Hence, you need to import
the subpackage as well.

Package inside the package is called the


subpackage. It should be created to
categorize the package further.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
How to access package from another
package?

There are three ways to access the package


from outside the package.

1)import package.*;
2)import package.classname;
3)fully qualified name.
Using packagename.*

The import keyword is used to make the


classes and interface of another package
accessible to the current package.
If you use package.* then all the classes and
interfaces of this package will be accessible
but not subpackages.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using packagename.classname

If you import package.classname then only


declared class of this package will be
accessible.
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using fully qualified name

If you use fully qualified name then only


declared class of this package will be
accessible. Now there is no need to import.
But you need to use fully qualified name
every time when you are accessing the
class or interface.

It is generally used when two packages


have same class name e.g. java.util and
java.sql packages contain Date class.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified
name
obj.msg();
}
}
How to run java package program

To Compile:
javac -d . filename.java

To Run:
java packagename.filename

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.
How to send the class file to another
directory or drive?
There is a scenario, user wants to put the
class file of A.java source file in classes
folder of c: drive. For example:

To Compile:

e:\sources> javac -d c:\classes Simple.java


To Run:
To run this program from e:\source directory,
you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Interfaces In Java
An Interface in Java programming language
is defined as an abstract type used to
specify the behavior of a class. An interface
in Java is a blueprint of a class. A Java
interface contains static constants and
abstract methods.

There can be only abstract methods in the


Java interface, not the method body. It is
used to achieve abstraction and multiple
inheritance in Java.
It cannot be instantiated just like the abstract
class.

Since Java 8, we can have default and static


methods in an interface.

Since Java 9, we can have private methods


in an interface.
Why use Java interface?
How to declare an interface?

An interface is declared by using the


interface keyword. It provides total
abstraction; means all the methods in an
interface are declared with the empty body,
and all the fields are public, static and final
by default. A class that implements an
interface must implement all the methods
declared in the interface.
syntax :
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Example:

// A simple interface
interface Player{
final int id = 10;
int move();
}

The Java compiler adds public and abstract


keywords before the interface method.
Moreover, it adds public, static and final
keywords before data members.
In other words, Interface fields are public,
static and final by default, and the methods
are public and abstract.
The relationship between classes
and interfaces
Difference Between Class and
Interface
S. No CIass Interface

1. In class, you can In an interface, you can’t


instantiate variables and instantiate variables and
create an object. create an object.

2. Class can contain The interface cannot


concrete(with contain concrete(with
implementation) methods implementation) methods

3. The access specifiers In Interface only one


used with classes are specifier is used- Public.
private, protected, and
public.
Implementation of interface
To implement an interface we use the keyword
implements

interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");
} }
class Circle implements Drawable{
public void draw(){
System.out.println("drawing circle");
}
//Using interface
public static void main(String args[]){
Drawable d=new Rectangle()/Circle();
//In real scenario, object is provided by
method e.g. getDrawable()
d.draw();
}}
Extending Interfaces

An interface can extend another interface in


the same way that a class can extend
another class. The extends keyword is used
to extend an interface, and the child
interface inherits the methods of the parent
interface.
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

An interface can extend more than one


inerfaces at once hence multiple inheritance
is possible with interfaces in java.
e.g.
public interface Hockey extends Sports,
Event
Exceptions in Java
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.
Exceptions can be caught and handled by
the program. When an exception occurs
within a method, it creates an object. This
object is called the exception object in java.
Errors represent irrecoverable conditions
such as Java virtual machine (JVM) running
out of memory, memory leaks, stack
overflow errors, library incompatibility,
infinite recursion, etc. Errors are usually
beyond the control of the programmer, and
we should not try to handle errors.
Major reasons why an exception Occurs

Invalid user input


Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
differences between Error and Exception
that is as follows:

Error: An Error indicates a serious problem


that a reasonable application should not try
to catch.

Exception: Exception indicates conditions


that a reasonable application might try to
catch.
Exception Hierarchy

All exception and error types are


subclasses of class Throwable.
Exceptions can be categorized in two ways:

1.)Built-in Exceptions
Checked Exception
Unchecked Exception

2.)User-Defined Exceptions
Built-in Exceptions:
Built-in exceptions are the exceptions that are available in
Java libraries. These exceptions are suitable to explain
certain error situations.

Checked Exceptions: Checked exceptions are called


compile-time exceptions because these exceptions are
checked at compile-time by the compiler.

Unchecked Exceptions: The unchecked exceptions are


just opposite to the checked exceptions. The compiler will
not check these exceptions at compile time. In simple
words, if a program throws an unchecked exception, and
even if we didn’t handle or declare it, the program would
not give a compilation error.
User-Defined Exceptions:

Sometimes, the built-in exceptions in Java


are not able to describe a certain situation.
In such cases, users can also create
exceptions, which are called ‘user-defined
Exceptions’.
try-catch for exception handling
import java.io.*;
class Excptest {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
} }}
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of
Bounds");
}
}}
Multi-catch block

A try block can be followed by one or more


catch blocks. Each catch block must contain
a different exception handler.

At a time only one exception occurs and at


a time only one catch block is executed.
All catch blocks must be ordered from
most specific to most general, i.e. catch for
ArithmeticException must come before catch
for Exception.
public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{

System.out.println("ArrayIndexOutOfBounds
Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
} }
Nested try blocks

A try block within a try block is called nested


try block in Java. This is needed when
different blocks like outer and inner may
cause different errors. To handle them, we
need nested try blocks.
class Main {
public static void main(String args[]) {
try {
int a[]=new int[10];
System.out.println(a[12]);
try {
System.out.println("Division");
int res = 100/ 0;
}
catch (ArithmeticException ex2) {
System.out.println("Sorry! Division by
zero isn't feasible!");
}
}
catch
(ArrayIndexOutOfBoundsException ex1) {

System.out.println("ArrayIndexOutOfBounds
Exception");
} }}
Java finally block
Java finally block is a block used to execute
important code such as closing the
connection, etc.

Java finally block is always executed


whether an exception is handled or not.
Therefore, it contains all the necessary
statements that need to be printed
regardless of the exception occurs or not.

The finally block follows the try-catch block.


class TestFinallyBlock {
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of code...");
} }
Java throw keyword
The Java throw keyword is used to throw an
exception explicitly.

We specify the exception object which is to


be thrownThese exceptions may be related
to user inputs, server, etc.

We can throw either checked or unchecked


exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.
Throwing Unchecked Exception
public class TestThrow1 {
public static void checksal(double salary) {
if(salary<5000) {
throw new
ArithmeticException("salary is too less");
}
else {
System.out.println("salary is ok!!");
}
}
public static void main(String args[]){

checksal(3000);
System.out.println("rest of the code...");

}
}
If we throw unchecked exception from a
method, it is must to handle the exception or
declare in throws clause.
Throwing Checked Exception
import java.io.*;

public class TestThrow2 {

public static void method() throws FileNotFoundException {

FileReader file = new FileReader("C:\\Users\\Admin\\


Desktop\\abc.txt");
BufferedReader fileInput = new BufferedReader(file);

throw new FileNotFoundException();

}
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Throwing User-defined Exception
public class TestThrow3
{
public static void main(String args[])
{ try
{
throw new UserDefinedException("This
is user-defined exception");
}

catch (UserDefinedException ude)


{
System.out.println("Caught the exception");

System.out.println(ude.getMessage());
} } }

class UserDefinedException extends Exception


{
public UserDefinedException(String str)
{
super(str);
}
}
Differences between throw and
throws
Basis of Differences throw throws
Definition Java throw keyword is Java throws keyword is
used throw an exception used in the method
explicitly in the code, signature to declare an
inside the function or the exception which might be
block of code. thrown by the function
while the execution of
the code.
Type of exception Using Using throws keyword,
throw keyword, we can we can declare both
only propagate checked and unchecked
unchecked exception exceptions. However,
i.e., the checked the throws keyword can
exception cannot be be used to propagate
propagated using throw checked exceptions only.
only.
Syntax The throw keyword is The throws keyword is
followed by an followed by class
instance of Exception names of Exceptions
to be thrown. to be thrown.

Declaration throw is used within the throws is used with the


method. method signature.

Internal implementation We are allowed to throw We can declare multiple


only one exception at a exceptions using throws
time i.e. we cannot throw keyword that can be
multiple exceptions. thrown by the method.
For example, main()
throws IOException,
SQLException.

You might also like