Fepj - 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Reference Document

Front End Development & Programming using


Java
Interface in Java

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.

Interfaces similar as Class


An interface is similar to a class in the following ways −
• An interface can contain any number of methods.
• An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
Interfaces differs from Class
• We cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.

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{

public void draw(){System.out.println("drawing rectangle");}


}
class Circle implements Drawable{

public void draw(){System.out.println("drawing circle");}

}
//Using interface: by third user
class TestInterface1{

public static void main(String args[]){

Drawable d=new Circle();//In real scenario, object is provided by method e.g.

getDrawable()d.draw();
}}

Output: drawing circle

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

Implementing one Interface in two classes


interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2
{ public static void main(String[] args)
{ Bank b=new SBI();
System.out.println("Rate Of Interest @ SBI is: "+b.rateOfInterest());
}
}
Output : Rate Of Interest @ SBI is : 9.15
Multiple inheritance in Java by interface
Multiple Inheritance is a feature of an object-oriented concept, where a class can
inherit properties of more than one parent class. The problem occurs when there exist
methods with the same signature in both the super classes and subclass. On calling the
method, the compiler cannot determine which class method to be called and even on calling
which class method gets the priority.

• Multiple inheritance is not supported through class in java, but it is possible by an


interface.
• If a class implements multiple interfaces, or an interface extends multiple interfaces,
it is known as multiple inheritance.

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

Difference between Classes and interfaces


Java Package
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.
Package in Java is a concept to encapsulate a group of classes, sub packages and
interfaces.
Packages are used in Java in order to prevent naming conflicts, to control access, to
make searching/locating and usage of classes, interfaces, enumerations and annotations
easier, etc.
Since the package creates a new namespace there won't be any name conflicts with
names in other packages. Using packages, it is easier to provide access control and it is also
easier to locate the related classes.
It helps to reuse the code wherever required.

Advantage of Java Package


1. Java package is used to categorize the classes and interfaces so that they can
be easilymaintained.

2. Java package provides access protection.

3. Java package removes naming collision.

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;

Ex: import java.awt.Image;


import java.awt.*;
import java.util.Date;
import java.io.*;

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.

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.

// Name of the package must be same as the directory

// under which this file is saved

package myPackage;

public class MyClass

public void getNames(String s)

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

How to run java package program

To Compile: javac -d . Simple.java


To Run: java mypack.Simple

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.

Advantage of Exception Handling

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

Difference between checked and unchecked exceptions

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.

Hierarchy of Java Exception classes


Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
method. Java try block must be followed by either catch or finally block.

Syntax of java try-catch

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

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.

Java Multi catch block

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.

1. public class TestMultipleCatchBlock{


2. public static void main(String args[]){
3. try{
4. int a[]=new int[5]; 5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed"); 9. }
10. catch(Exception e){System.out.println("common task completed");
11. }
12. System.out.println("rest of the code..."); 13. } }

Java nested try example

Let's see a simple example of java nested try 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

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...");
}
}

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.

1. throw exception;

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{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){ validate(13);
System.out.println("rest of the code...");
}}
Output:
Exception in thread main java.lang.ArithmeticException:not valid

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to the programmer
that there may occur an exception so it is better for the programmer to provide the exception handling
code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked
exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers
fault that he is not performing check up before the code being used.

Syntax of java throws


1. return_type method_name() throws exception_class_name{
2. //method code 3. }
4.

Java throws example

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:

Java Custom Exception

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);}

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


}}

Output:Exception occured: InvalidAgeException:not valid rest of the code...

Multithreading

Multithreading in java is a process of executing multiple threads simultaneously. Thread is


basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking. But we use multithreading than
multiprocessing because threads share a common memory area. They don't allocate separate memory
area so saves memory, and context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

 It doesn't block the user because threads are independent and you can perform multiple
operations at same time.

 You can perform many operations together so it saves time.

 Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Life cycle of a Thread (Thread States)

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

How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

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.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Commonly used methods of Thread class:

 public void run(): is used to perform action for a thread.


 public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
 public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
 public void setName(String name): changes the name of the thread.
 public Thread currentThread(): returns the reference of currently executing thread.
 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
 public boolean isAlive(): tests if the thread is alive.
 public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
 public void suspend(): is used to suspend the thread(depricated).
 public void resume(): is used to resume the suspended thread(depricated).
 public void stop(): is used to stop the thread(depricated).
 public boolean isDaemon(): tests if the thread is a daemon thread.
 public void setDaemon(boolean b): marks the thread as daemon or user thread.
 public void interrupt(): interrupts the thread.
 public boolean isInterrupted(): tests if the thread has been interrupted.
 public static boolean interrupted(): tests if the current thread has been interrupted.

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 extending Thread class

class Multi extends Thread{


public void run(){ System.out.println("thread is running...");
}
public static void main(String args[]){ Multi t1=new Multi();
t1.start();
}}

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();
}}

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority (known as preemptive scheduling).
But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the


value of MAX_PRIORITY is 10.

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[]){

TestMultiPriority1 m1=new TestMultiPriority1(); TestMultiPriority1 m2=new TestMultiPriority1();


m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); m1.start();
m2.start();
}}

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method. Synchronized


method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.

Example of inter thread communication in java

Let's see the simple example of inter thread communication.

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(){

public void run(){c.deposit(10000);}


}
start();
}}
Thread Group in Java

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();

Exploring java.net and java.text

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy