Java - Unit3 2023-24 (CS Major)
Java - Unit3 2023-24 (CS Major)
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.
As shown in the figure given above, a class extends another class, an interface extends another interface, but
a class implements an interface.
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.
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
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.
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.
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.
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.
{
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.
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
4) Throw is used within the method. Throws is used with the method
signature.