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

Java - Unit3 2023-24 (CS Major)

Uploaded by

web
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)
26 views

Java - Unit3 2023-24 (CS Major)

Uploaded by

web
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/ 11

UNIT-3

Interface in Java
An interface is just like Java Class, but it only has static constants and abstract methods. Java uses
Interface to implement multiple inheritance.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the
abstract class.
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.
}
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

As shown in the figure given above, a class extends another class, an interface extends another interface, but
a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.
1. interface A{
2. final double pi = 3.14; //(Interface variable)
3. void print();
4. }
5. class B implements A{
6. public void print(){System.out.println("Hello "+pi);}
UNIT-3

7. public static void main(String args[]){


8. B obj = new B();
9. obj.print();
10. }
11. }
Output: Hello 3.14
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. A7 obj = new A7();
12. obj.print();
13. obj.show();
14. }
15. }
Output: Hello
Welcome
Interface inheritance
A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. TestInterface4 obj = new TestInterface4();
UNIT-3

12. obj.print();
13. obj.show();
14. }
15. }
Test it Now
Output : Hello
Welcome

Java Packages
What is package and explain types of packages ?
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can
be categorized in two forms,
1. Built-in package and
2. User-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.

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 and code reusability.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple
4. {
5. public static void main(String args[])
6. {
7. System.out.println("Welcome to package");
8. }
9. }
UNIT-3

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory name
like d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use .
(dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output: Welcome to package
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 access package from another package?
There are two ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
6.
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
Output:Hello
UNIT-3

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
1.
2. //save by A.java
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1.
2. //save by B.java
3. package mypack;
4. import pack.A;
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

Exception Handling
Explain types of error in java?
Compile time errors: Compile time errors refer to syntax and semantics in compile time. For example, if you
do operations that involves different types. Ex: adding a string with an int, or dividing a string by a real. These
are also refereed as Checked exceptions.
Run Time error: Run time errors are those that are detected when the program execute. For example,
division by zero. The compiler cannot know if the operation x/a-b will leads to division by zero until the
execution. These are also refereed Unchecked exceptions.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For
example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
What is an exception and explain types ?
An exception (or exceptional event) is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of
memory.
There are two types of exceptions in Java:
1)Checked exceptions 2)Unchecked exceptions
UNIT-3

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks
them during compilation to see whether the programmer has handled them or not. If these exceptions are not
handled/declared in the program, you will get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to
be thrown
FileReader fr = new FileReader(file);
^
1 error
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at
compile-time so compiler does not check whether the programmer has handled them or not but it’s the
responsibility of the programmer to handle these exceptions and provide a safe exit.For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
UNIT-3

public class Unchecked_Demo {


public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For
example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Exception Handling Mechanism


3.Explain about exception handling mechanism in java ?
In java, exception handling is done using five keywords,

Keyword Description

Try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.

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 important code of the program. It is executed
whether an exception is handled or not.

Throw The "throw" keyword is used to throw an exception.

Throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

a) Using try and catch


Try is used to guard a block of code in which exception may occur. This block of code is called guarded
region.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
guarded code, the catch block that follows the try is checked, if the type of exception that occurred is listed in
the catch block then the exception is handed over to the catch block which then handles it.
Example using Try and catch
UNIT-3

class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
Output: Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero inside try block. The
program control is transferred outside try block. Thus the line "This line will not be executed" is never parsed
by the compiler. The exception thrown is handled in catch block. Once the exception is handled, the program
control is continue with the next line in the program i.e after catch block. Thus the line "After exception is
handled" is printed.

b) Multiple catch blocks:


A try block can be followed by multiple catch blocks. You can have any number of catch blocks after a single
try block. If an exception occurs in the guarded code the exception is passed to the first catch block in the list. If
the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed
down to the next catch block. This continues until the exception is caught or falls through all catches.
Example for Multiple Catch blocks
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
UNIT-3

{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}
Output: divide by zero
Note: At a time, only one exception is processed and only one respective catch block is executed.

c) finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code is
always executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup
type statements that you want to execute, no matter what happens in the protected code. A finally block appears
at the end of catch block.

Example
demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
UNIT-3

}
}
}
Output : Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.

d) Java throw keyword


The Java throw keyword is used to explicitly throw an exception. We can throw either checked or
unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception.
We will see custom exceptions later.

The syntax of java throw keyword is given below.


throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error);

Java throw keyword example


In this example, we have created the validate method that takes integer value as a parameter. If the age
is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
1. public class TestThrow1{
2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code...");
11. }
12. }

Output:
Exception in thread main java.lang.ArithmeticException:not valid
Explain difference between throw and throws in Java?
There are many differences between throw and throws keywords. A list of differences between throw and
throws are given below:
No. throw throws
1) Java throw keyword is used to explicitly Java throws keyword is used to declare
throw an exception. an exception.
2) Checked exception cannot be propagated Checked exception can be propagated
using throw only. with throws.
UNIT-3

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method
signature.

5) You cannot throw multiple exceptions. public void method()throws


IOException,SQLException.

You might also like