Fepj - 3
Fepj - 3
Fepj - 3
An interface in java is a blueprint of a class. It has static constants and abstract methods. An
interface is a reference type in Java. It is similar to class. It is a collection of abstract methods.
A class implements an interface, thereby inheriting the abstract methods of the interface.
Abstraction means hiding the irrelevant details from the user to focus only on the essential
details to increase efficiency thereby reducing complexity. In Java, abstraction is achieved
using abstract classes and methods. The interface in java is a mechanism to achieve
abstraction. There can be only abstract methodsin the java interface not method body. It is
used to achieve abstraction and multiple inheritance in Java.
Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. An interface contains behaviors that a class implements. Java
Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
Properties of Interfaces
• Interfaces have the following properties −
• An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
• Methods in an interface are implicitly public.
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare
an interface −
public interface NameOfInterface
{
// Any number of final, static fields
// Any number of abstract method declarations
}
Example :
interface printable
{
public void print();
public void travel();
}
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
}
//Using interface: by third user
class TestInterface1{
getDrawable()d.draw();
}}
Implementing Interfaces
A class uses the implements keyword to implement an interface. The
implements keyword appears in the class declaration following the extends portion of the
declaration.
class Demo_interface implements printable
{ public void print()
{
System.out.println("Hello all, we are learning concept of interfaces");
}
public static void main(String args[])
{
Demo_interface DM = new Demo_interface();
DM.print();
}
}
Output : Hello all, we are learning concept of interfaces
Example :
interface Printable
{ void print(); }
interface Showable
{ void show(); }
class Multiple_inhertance_using_interfaces implements Printable,Showable
{
public void print(){ System.out.println("\nHey, this is Print method from first
interface"); }
public void show(){ System.out.println("\nHello, this is show method from second
interface"); }
public static void main(String args[])
{ Multiple_inhertance_using_interfaces obj = new
Multiple_inhertance_using_interfaces();
obj.print();
obj.show();
}
}
Output : Hey, this is Print method from first interface
Hello, this is show method from second interface
Declaration of Packages
To create a package simply include a package keyword as the first statement in a
Java source file.
Any classes declared within that file will belong to the specified package .
The package statement defines a name space in which classes are stored.
Example :1) To import the Vector class from util package.
import java.util.vector;
2) To import all the classes from util package
import java.util.*;
First Statement is used to import Vector class from util package which is contained
inside java.
Second statement imports all the classes from util package.
Example:
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Importing Packages
To create package hierarchy separate each package name from the one above it by use of a
period. If we need use some classes from different package we should import that package
using import statement .
Syntax:
import pkg1[.pkg2].*;
import pkg1.class_name;
Types of Packages
Built-in Packages
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.
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.
package myPackage;
System.out.println(s);
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application. Exception
normally disrupts the normal flow of the application that is why we use exception handling.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){} Syntax of try-finally block
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only. You can
use multiple catch block with a single try.
Problem without exception handling
Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1{
public static void main(String args[]){ int data=50/0;//may throw exception System.out.println("rest
of the code...");
}}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the code...
statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Solution by exception handling
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);} System.out.println("rest of the code...");
}}
1. Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement
is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch
block.
Let's see a simple example of java multi-catch block.
class Excep6{
public static void main(String args[]){
try{ try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5]; a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} System.out.println("other
statement);
}catch(Exception e){System.out.println("handeled");} System.out.println("normal flow..");
}
1. }
Java finally block is a block that is used to execute important code such as closing connection, stream
etc. Java finally block is always executed whether exception is handled or not. Java finally block
follows try or catch block.
Usage of Java finally
Case 1
Let's see the java finally example where exception doesn't occur. 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 the code...");
}
}
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.
1. throw exception;
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.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{ m();
}
void p(){
try{ n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){ Testthrows1 obj=new Testthrows1(); obj.p();
System.out.println("normal flow..."); } } Output:
If you are creating your own Exception that is known as custom exception or user-defined exception.
Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message. Let's see a simple
example of java custom exception.
class InvalidAgeException extends Exception{ InvalidAgeException(String s){
super(s);
}}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{ validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
Multithreading
It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
Threads are independent so it doesn't affect other threads if exception occur in a single thread.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle
in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Thread class
Thread class provide constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
Java Thread Example by implementing Runnable interface class Multi3 implements Runnable{
public void run(){ System.out.println("thread is running...");
}
public static void main(String args[]){ Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); t1.start();
}}
Example of priority of a Thread: class TestMultiPriority1 extends Thread{ public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
class Customer{
int amount=10000;
synchronized void withdraw(int amount){ System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount; System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){ System.out.println("going to deposit...");
this.amount+=amount; System.out.println("deposit completed... "); notify();
}
}
class Test{
public static void main(String args[]){ final Customer c=new Customer(); new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call. Java thread group is
implemented by java.lang.ThreadGroup class. Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
ThreadGroup(String name) ThreadGroup(ThreadGroup parent, String name)
Let's see a code to group multiple threads.
1. ThreadGroup tg1 = new ThreadGroup("Group A");
2. Thread t1 = new Thread(tg1,new MyRunnable(),"one");
3. Thread t2 = new Thread(tg1,new MyRunnable(),"two");
4. Thread t3 = new Thread(tg1,new MyRunnable(),"three");
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the class
that implements Runnable interface and "one", "two" and "three" are the thread names.
Now we can interrupt all threads by a single line of code only.
Thread.currentThread().getThreadGroup().interrupt();
java.net
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide
the low-level communication details, allowing you to write programs that focus on solving the
problem at hand.
The java.net package provides support for the two common network protocols −
•TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.
•UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets
of data to be transmitted between applications.
This chapter gives a good understanding on the following two subjects −
•Socket Programming − This is the most widely used concept in Networking and it has been
explained in very detail.
•URL Processing − This would be covered separately.