Java Unit 3 and 4
Java Unit 3 and 4
Java Unit 3 and 4
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
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.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a
body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
//abstract method
abstract void run();
void changeGear(){
System.out.println("gear changed");
}
}
class Honda extends Bike{
void run() {
System.out.println("running safely..");
}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
final keyword -
If a final keyword is used to before a method name then such type of
method is called final method
The final keyword in java is used to restrict the user. In java final
keyword can be used in many context.
Final can be:
Variable: If variable is final, you cannot change the value of final
variable (It will be constant).
Method: If you make any method as final, you cannot override it.
Class: If you make any class as final, you cannot extend it.
Final Variable-
class Bike{
final int speedlimit=90 ;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}
output: Compile Time Error
Final Method
class Bike{
final void run(){System.out.println("running");}
}
Final class
JAVA - PACKAGES:
What is package:
Packages are used in Java, in-order to avoid name conflicts and to
control access of class, interface and enumeration etc. A package
can be defined as a group of similar types of classes, interface,
enumeration or sub-package.
Using package, it becomes easier to locate the related classes and
it also provides a good structure for projects with hundreds of
classes and other files.
Benefits of using package in java:
Java package is used to categorize the classes and interfaces so
that they can be easily maintained.
Java package provides access protection.
Java package removes naming collision.
This packages can be provide reusability of code.
We can create our own package or extend already available package.
import package.*;
import package.classname;
fully qualified name.
Using packagename.*:
If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.
// File: A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello java");
}
}
// File: B.java
package mypack;
import pack.*;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
Output: Hello java
Using packagename.classname:
public class A {
public void msg() {
System.out.println("Hello");
}
}
// File: B.java
package mypack;
import pack.A;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
Output: Hello
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.
// File: A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
// File: B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); // using fully qualified name
obj.msg();
}
}
Output : Hello
Subpackage in java:
package com.javatpoint.core;
class Simple{
public static void main(String args[]){ System.out.println("Hello
subpackage");
}
}
To Compile: javac -d . Simple.java
There is a scenario, I want to put the class file of A.java source file
in classes folder of c: drive.
For example :
// File: Simple.java
package mypack;
public class Simple {
public static void main(String args[]) {
System.out.println("Welcome to package");
}
}
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
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
Classification of exceptions?
Errors − Errors are not exceptions, but problems may 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.
Error:
An Error indicates serious problem that a reasonable application
should not try to catch.
An Error is a severe situation generated when the user performs an
unexpected operation
Exception:
Exception indicates conditions that a reasonable application might
try to catch.
An Exception is an event that occurs during the program execution
and disrupts the normal flow of the program’s execution
Unchecked v/s Checked-
EXCEPTION HIERARCHY
The java.lang.Exception class is the base class for all exception classes.
All exception and errors types are sub classes of class Throwable,
which is base class of hierarchy.
The Exception class has two main subclasses: IOException class and
RuntimeException class
Exceptions Methods
Method Description
public String Returns a detailed message about
getMessage() the exception that has occurred.
This message is initialized in the
Throwable constructor.
public Throwable Returns the cause of the exception
getCause() as represented by a Throwable
object.
public String Returns the name of the class
toString() concatenated with the re- sult of
getMessage().
public void Prints the result of toString() along
printStackTrace() with the stack trace to System.err,
the error output stream.
public Returns an array containing each
StackTraceElement [] element on the stack trace. The
getStackTrace() element at index 0 represents the
top of the call stack, and the last
element in the array represents the
method at the bottom of the call
stack.
public Throwable Fills the stack trace of this
fillInStackTrace() Throwable object with the current
stack trace, adding to any previous
information in the stack trace.
try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ... additional catch blocks for handling different exception types
// optional
finally {
// block of code to be executed after try block ends, whether an
exception occurred or not
}
Throwing and catching exceptions
Catching Exceptions
A method catches an exception using a combination of the try and
catch keywords. The program code that may generate an exception
should be placed inside the try/catch block. The syntax for try/catch
is depicted as below−
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
class Exception_example {
public static void main(String args[]) {
int a, b;
try {
// Initialize a with a non-zero value
a = 2;
b = 10 / a; // raises the arithmetic exception
System.out.println("Try block.");
} catch (ArithmeticException e) {
// Catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After try/catch block.");
}
}
Output:
Division by zero.
After try/catch block.
class MultiCatch_Example {
public static void main(String args[]) {
try {
int a, b;
a = args.length;
System.out.println("a = " + a);
b = 10 / a; // may cause division-by-zero error
int arr[] = {10, 20};
arr[5] = 100;
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Here is the output generated by the execution of the program in both
ways:
C:\>java MultiCatch_Example a = 0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch
blocks.
C:\>java MultiCatch_Example arg1
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:5
Nested try block
Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In such
cases, exception handlers have to be nested.
try {
// statement 1;
// statement 2;
try {
// statement 1;
// statement 2;
} catch (Exception e) {
// Handle exception for the inner try block
}
} catch (Exception e) {
// Handle exception for the outer try block
}
try {
int a[] = new int[5];
a[6] = 3;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("other statement");
} catch (Exception e) {
System.out.println("handled");
}
System.out.println("normal flow..");
}
}
Throw keyword
The Java throw keyword is used to explicitly throw an exception. The
general form of throw is shown below:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throw- able. Primitive types, such as int or char, as well as
non-Throwable classes, such as String and Object, cannot be used as
exceptions.
There are two ways to obtain a Throwable object:
using a parameter in a catch clause
creating one with the new operator.
The following program explains the use of throw keyword.
public class TestThrow1 {
static void validate(int age) {
try {
if (age < 18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
} catch (ArithmeticException e) {
System.out.println("Caught inside ArithmeticException.");
throw e; // rethrow the exception
}
}
import java.io.*;
public class throw_Example2 {
public void function(int a) throws
RemoteException,ArithmeticException {
// Method implementation
}
// Remainder of class definition
}
Example
public class Finally_Example {
public static void main(String args[]) {
try {
int a,b;
a=0;
b=10/a;
} catch (ArithmeticException e) { System.out.println(“Exception thrown
:” + e);
}finally {
System.out.println(“The finally block is executed”);
}
}
}
Points to remember:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block
is present.
The try block cannot be present without either catch clause or finally
clause.
Any code cannot be present in between the try, catch, finally blocks.
USER DEFINED EXCEPTION IN JAVA
In Java, we can create our own exceptions that are derived classes of
the Exception class. Creating our own Exception is known as custom
exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user
need.
Consider the example 1 in which InvalidAgeException class extends
the Exception class.
Using the custom exception, we can have your own exception and
message. Here, we have passed a string to the constructor of
superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
Syntax:
class User_defined_name extends Exception{
………..
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
// printing the message from InvalidAgeException object
System.out.println("Exception occured: " + ex);
}
• File I/o or file handling defines that we can read and write data on
a file of java IO –Package contain all the class through which we can
perform Input/Ouput Operation in file .
• The File I/O uses the concept of stream to make I/O operation fast.
• Stream:- the stream is sequence of data on the on the basis of
java .io Package
• Stream :-
I/P Stream –System.in
O/P Stream-System.out
Error Stream-System.err
File handling Method
1. CanRead()
2. CanWrite()
3. CreateNewFile()
4. Delete()
5. Exists()
6. Length()
7. GetName()
8. getAbsolutepath()
9. Mddir()
10. List()
11. Read()
12.Write()
13.renameTo()
File handling Classes
1. File
2. FileReader
3. FileWriter
4. FileInputStream
5. FileOutputStream
6. BufferedInputStream
7. BufferedOutputStream
Operation on file:
1. Create File
2. Get file information
3. Read File
4. Wite File
Create File :To create a file in Java, you can use the
createNewFile() method. This method returns a boolean
value: true if the file was successfully created, and false if the
file already exists.
if(f.createNewFile())
{ System.out.println("file Successfully Create...!"); }
else
{ System.out.println("File already exist"); }
}
}
}
import java.io.*;
public class fileinfo
{
public static void main(String args[]) throws IOException
{ File f=new File("C:\\Users\\HOME\\Desktop\\ lc.txt");
if(f.exist ())
{ System.out.println(“File Name:“+getName()); }
else
{ System.out.println("File Doesn’t exist"); }
}
}
}
Input Stream Class:
• Input Stream:
• The Java InputStream class is the superclass of all input
streams. The input stream is used to read data from
numerous input devices like the keyboard, network, etc.
InputStream is an abstract class, and because of this, it is
not useful by itself. However, its subclasses are used to
read data.
• Java FileInputStream example 1: read single character
Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileOutputStream;
output:Success...
Welcome to java.
RandomAccessFile in Java
Applet
Applet is java program that can be embedded into html
pages.
Applets transported over the internet form one
computer to another and run
using applet viewer or can run on any java enabled
web browser using JVM.
An applet is a small program that is intended not to be
run on its own, but
rather to be embedded inside another application.
The applet class provides a standard interface between
applet and their environment
Advantages of applet
disadvantages of applet
Java applets requires JVM so first time it takes significant
startup time.
It is difficult to design and build good user interface in
applet as compare to html technology.
Some organization only allowed software installed by
administrator, As a result many users cannot view applet
by default.
Types of Applets:
. Local Applets
An applet developed locally and stored in a local system
is known as a local applet.
When a web page is trying to find a local applet, it does
not need to use the internet and therefore the local
system does not require the internet
connection.
It simply searches the directories in the local system;
locates and loads the specified applet
Remote Applet:
A remote applet is that which is developed by someone
else and stored on a remote computer connected to the
internet. If our system is connected to the internet, we
can download the remote applet into our system via at
the internet and run it.
Your browser must, of course, be connected to the
Internet at the time it needs to display the remote
applet.
For locate and load a remote applet, we must know the
applet’s address on the web. This address is known as
Uniform Resource Location (URL)
Applet/Application:
`}
}