final year project center in coimbatore

65
Java workshop

Upload: cbeproject-centercoimbatore

Post on 13-Apr-2017

11 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: final year project center in Coimbatore

Java workshop

Page 2: final year project center in Coimbatore

Objectives:Static and instance members,Exceptions,Multithreading,Garbage collection andCollections

Page 3: final year project center in Coimbatore

Static members

Page 4: final year project center in Coimbatore

“static” keyword:

• “static” is used to maintain fixed values.• “static” keyword is used to access a member

without the existence of the object. “static” members can be accessed by using the class name directly.

• Instance members should be accessed by the object.

Page 5: final year project center in Coimbatore

• While declaring a member(may be method or variable), if we are not prefixing a member with “static” keyword, that member is called instance member.

• We can call the static variables as class variables because those members can be shared by all the objects of that class.

• Members of a class are:– Methods and– Variables.

Page 6: final year project center in Coimbatore

Syntax for static methods: [modifier] static return-type method-

name([parameters]){Logic for the method;}Eg:static int add(int a, int b){return (a+b);}

Page 7: final year project center in Coimbatore

Syntax for instance methods:[modifier] return-type method-name([parameters]){Logic for instance method;}Eg:double mul(double d1, double d2){return (d1*d2);}

Page 8: final year project center in Coimbatore

Syntax for class variables:[modifier] static type variable-name[=value];Eg:static int i=25;Syntax for instance variables:[modifier] type variable-name[=value];Eg:int i=25;

Page 9: final year project center in Coimbatore

• In terms of objects, for every instance member, separate copy will be created.

• For static members, one copy will be created and shared by all the objects.

• In the case of class and instance variables, if we are not performing the initialization, JVM will provide the default values.

Page 10: final year project center in Coimbatore

Eg:class Demo{int i;static int j;public static void main(String[] args){System.out.println(j);Demo d=new Demo();System.out.println(d.i);System.out.println(d.j);}}

Page 11: final year project center in Coimbatore

Eg:class Test{int i=10;static int j=20;public static void main(String[] args){System.out.println(j);Test t1=new Test();t1.i=100;t1.j=200;System.out.println(t1.i+”…”+t1.j);Test t2=new Test();System.out.println(t2.i+”…”+t2.j);}}

i=100j=

j =20t1 200

Static variable

Page 12: final year project center in Coimbatore

Important note:We can access instance members from

instance area only. We can’t access from static area.

Static members are accessible from instance as well as static areas.

Page 13: final year project center in Coimbatore

Exercise:I. int i=1;II. static int i=2;III. public static void main(String[] args)

{System.out.println(i);}

Which of the above code snippet combinations are possible?

a). I and II, b). I and III, c). II and III

Page 14: final year project center in Coimbatore

class Member{int i;public static void main(String[] args){System.out.println(i);}}

Page 15: final year project center in Coimbatore

Eg:class StatMethDemo{public static void add(int i, int j){System.out.println(i+j);}public static void main(String[] args){add(10,20);}}

Page 16: final year project center in Coimbatore

Eg:class InstMethDemo{public void add(int i, int j) //instance method{System.out.println(i+j);}public static void main(String[] args){add(10,20);}}

Page 17: final year project center in Coimbatore

Exceptions

Page 18: final year project center in Coimbatore

Exceptions:

• An abnormal event that disturbs the normal flow of the program is called an exception (or) simply it is an issue.

• Main objective of exception handling is graceful termination of the program.

• Exception handling means providing alternate way when an exception is raised. It doesn’t mean repairing an exception.

Page 19: final year project center in Coimbatore

Eg:class Test{public static void main(String[] args){System.out.println("Hi");System.out.println(10/0);System.out.println("Bye");}}

Page 20: final year project center in Coimbatore

When an exception is raised, JVM will provide the details(default mechanism) of the exception as follows:Name of the exception,Description, andStack trace(Location).Eg:

Exception in thread “main” java.lang.ArithmeticException : / by zero

at Test.main(Test.java:6)

Page 21: final year project center in Coimbatore

Throwable class is the root class for all exception hierarchy. It contains 2 sub-classes:• Exception(programmatic errors which are caused by

users, recoverable)• Error(internal errors, non-recoverable)

• Exceptions are of 2 types:Checked (Checked by the compiler for smooth

execution of the program at run-time)Eg: IOException, FileNotFoundException, etc.Unchecked (Not checked by the compiler)Eg: ArithmeticException, NullPointerException, ArrayIndexOutofBoundsException, etc.

Page 22: final year project center in Coimbatore

• Object

Exception Error

Throwable

RuntimeException IOException

ArithmeticException

NullPointerException

FileNotFoundException

Unchecked Exceptions

Checked Exceptions

Page 23: final year project center in Coimbatore

• Exception related keywords:– try (to maintain risky code)– catch (to catch the exceptions)– finally (to maintain clean-up code)– throw (to modify or create own exception

and handover it to the JVM)– throws (for handling checked

exceptions)

Page 24: final year project center in Coimbatore

Eg:class ExcDemo{

public static void main(String[] args){try{System.out.println(“Hello”);System.out.println(10/0);System.out.println(“Bye”);}catch(ArithmeticException e){System.out.println(e);}finally{System.out.println(“Finally block”);}}

}

Page 25: final year project center in Coimbatore

• “try” with multiple “catch” blocks combination is also possible. The order of “catch” blocks should be from child exception to parent exception.

Eg:class ExcDemo{public static void main(String[] args){try{System.out.println("Welcome");System.out.println(15/0);System.out.println("Good bye");}

Page 26: final year project center in Coimbatore

catch(ArithmeticException e) {System.out.println(e);}catch(Exception e){System.out.println(e);}}}

Page 27: final year project center in Coimbatore

“throw” keyword:• To handover our own created exception object to the

JVM explicitly.Eg:class ThrowDemo{

public static void main(String[] args){throw new ArithmeticException(“Arithmetic exception”);}

}

Page 28: final year project center in Coimbatore

“throws” keyword:• If there is any chance of occurring checked exception, we need to handle

it manually. This can be done in 2 ways:– Using try-catch (or)– Using “throws” keyword. The purpose of “throws” keyword is to delegate the responsibility of

exception handling to the caller.Eg:class ThrowsDemo{

public static void main(String[] args){Thread.sleep(2000);System.out.println(“Slept happily”);}

}

Page 29: final year project center in Coimbatore

Customized exceptions: Eg:class LessMarksException extends RuntimeException{

LessMarksException(String s){super(s);}

}class GoodMarksException extends RuntimeException{

GoodMarksException(String s){super(s);}

}

Page 30: final year project center in Coimbatore

class CustExceptionDemo{

public static void main(String[] args){int marks=Integer.parseInt(args[0]);if(marks<50){throw new LessMarksException("Poor marks");}else if(marks>80){throw new GoodMarksException("Good marks");}else{System.out.println("Average score");}}

}

Page 31: final year project center in Coimbatore

Multithreading

Page 32: final year project center in Coimbatore

• Performing several activities simultaneously(multitasking).

• Thread based multitasking• Each task is separate independent task of the same

program.• Each task is called a thread.• Applicable at programmatic level.

• Thread is a light weight process.• The main objective of multitasking is to reduce

response time of the system.• Java provides in-built support for

multithreading.

Page 33: final year project center in Coimbatore

Runnable

Thread

MyThread MyRunnable

Page 34: final year project center in Coimbatore

• Implementation of multithreading can be done in 2 ways:– By extending Thread class:Eg:

Class MyThread extends Thread{public void run(){for(int i=0;i<4;i++){System.out.println(“child thread”);}}}

Job of the

thread

Defining a thread

Page 35: final year project center in Coimbatore

Class ThreadDemo{

public static void main(String[] args) // Main thread{MyThread t=new MyThread(); // Instatiation of threadt.start(); // Starting child threadfor(int i=0;i<4;i++){System.out.println(“Main thread”);}}

}

Page 36: final year project center in Coimbatore

• By implementing Runnable interface:Class MyRunnable implements Runnable{

public void run(){

for(int i=0;i<4;i++){System.out.println(“Child thread”);}

}}

JobDefining

Page 37: final year project center in Coimbatore

Class ThreadDemo{

public static void main(String[] args){MyRunnable r=new MyRunnable();Thread t=new Thread(r);t.start();for(int i=0;i<4;i++){System.out.println(“Main thread”);}}

}

Target runnable

Page 38: final year project center in Coimbatore

• The purpose of ThreadScheduler is to get the opportunity for execution when multiple threads are awaiting.

ThreadScheduler

Main threadChild thread

Page 39: final year project center in Coimbatore

Thread life cycle:

New/ Born

Ready/ Runnable

RunningDead

MyThread t=new MyThread();

t.start()

If ThreadScheduler allocated CPU

If run() completes

Waiting state

wait()

when wait() completes

Page 40: final year project center in Coimbatore

Thread synchronization:• This can be done by using “synchronized”

keyword.• “synchronized” keyword is applicable for

methods and blocks.• If a method (or) block is declared as

“synchronized”, then at a time only one thread is allowed to execute.

• Advantage of “synchronized” is to avoid data inconsistency problems.

Page 41: final year project center in Coimbatore

Declaration:[modifier] synchronized return-type method-

name([parameters]){Logic for synchronized method;}Eg:public synchronzied void access(){System.out.println(“Only one thread can be accessed”);}

Page 42: final year project center in Coimbatore

Eg:class TestSync implements Runnable{int balance;public synchronized void run() //synchronized method{for(int i=0;i<5;i++){increment();System.out.println("Bal is:"+balance);}}public void increment(){int i=balance;balance=i+1;}}

Page 43: final year project center in Coimbatore

class SyncDemo{public static void main(String[] args){TestSync t=new TestSync();Thread a=new Thread(t);Thread b=new Thread(t);a.start();b.start();}}

Page 44: final year project center in Coimbatore

Methods for preventing thread from execution: yield() (to cause current thread to pause

and to give chance for remaining threads of same priority)

join() (to make the thread to wait for the completion of other thread)

sleep() (for making a thread to sleep for specified number of milli-seconds)

Page 45: final year project center in Coimbatore

Program for yield():class MyThread extends Thread{public void run(){for(int i=0;i<5;i++){Thread.yield();System.out.println("child");}}}

Page 46: final year project center in Coimbatore

class YieldDemo {public static void main(String[] args){MyThread t=new MyThread();t.start();for(int i=0;i<5;i++){System.out.println("main");}}}

Page 47: final year project center in Coimbatore

Thread interruption:• One thread can interrupt another thread by using interrupt().Eg:class MyThread extends Thread{public void run(){try{for(int i=0;i<20;i++){System.out.println("lazy");}Thread.sleep(5000);}catch(InterruptedException e){System.out.println("got interrupted");}}}

Page 48: final year project center in Coimbatore

class InterruptDemo{public static void main(String[] args){MyThread t=new MyThread();t.start();t.interrupt();System.out.println("active");}}

Page 49: final year project center in Coimbatore

Garbage collection

Page 50: final year project center in Coimbatore

• In old languages like C++, the programmer is responsible for the creation and destruction of objects.

• In Java, programmer is only responsible for the creation of objects. Object destruction is not required.

• Sun introduced one assistant which is running in background for the destruction of useless objects which is called garbage collector.

• We can request JVM to run garbage collector in 2 ways:– By System class (using gc())– By Runtime class

Page 51: final year project center in Coimbatore

• In Runtime object, we can use the following methods:– freeMemory() Returns free memory available

in the heap.– totalMemory() Returns total memory of the

heap– gc() For requesting JVM to run

garbage collector• Before destroying any object, GC always calls finalize()

which is present in Object class. The object which is eligible for GC, the corresponding finalize() will be executed.

• When calling gc(), it may not be impacted immediately.

Page 52: final year project center in Coimbatore

Eg:class RuntimeDemo{public static void main(String[] args){Runtime r=Runtime.getRuntime();System.out.println(r.totalMemory());System.out.println(r.freeMemory());for(int i=0;i<500;i++){java.lang.String d=new java.lang.String();d=null;}System.out.println(r.freeMemory());r.gc();System.out.println(r.freeMemory());}}

Page 53: final year project center in Coimbatore

Eg:class Test{public static void main(String[] args){//String s=new String("hello");//s=null;Test t=new Test();t=null;System.gc();System.out.println("End of main");}public void finalize(){System.out.println("Finalize called");}}

For String class finalize()

Page 54: final year project center in Coimbatore

Collections

Page 55: final year project center in Coimbatore

• Array is indexed collection of fixed number of homogeneous elements. Limitations of arrays are:– Fixed in size,– Can hold only homogeneous data elements.– Underlying data structure not available.

• To overcome the above limitations, we can go for Collection.

• To use the properties of Collection, we need to import a package named with java.utilCollections are growable in nature.Can hold homogeneous and heterogeneous elements.Underlying data structures are available.

Page 56: final year project center in Coimbatore

Collection hierarchy: Collection

List Set

HashSetArrayList LinkedList SortedSet

Map

HashMap Hashtable

Page 57: final year project center in Coimbatore

Collection interface:• If we want to represent a group of individual objects

as single entity, then we can use Collection.• Few methods available in Collection interface:– boolean add(Object o);– boolean addAll(Collection c);– boolean remove(Object o);– boolean isEmpty();– int size();

Page 58: final year project center in Coimbatore

ArrayList class:• Underlying data structure is resizable (or) growable array.• Insertion order is preserved.• Duplicate objects are allowed.• Heterogeneous objects are allowed.• “null” insertion is possible. Best suitable if our frequent operation is retrieval. ArrayList implements RandomAccess interface.Constructors:ArrayList(): Creates empty ArrayList object with default capacity

10. If max. capacity is reached, new capacity =currentcapacity*(3/2)+1

ArrayList(int size): Empty ArrayList object with specified capacity will be created.

ArrayList(Collection c): Creates an equivalent ArrayList object for c.

Page 59: final year project center in Coimbatore

Eg:import java.util.*;class ALDemo{public static void main(String[] args){ArrayList sampleList=new ArrayList();l.add("A");l.add(10);l.add("A");l.add(null);System.out.println(sampleList);l.remove(2);l.add(1,"B");System.out.println(sampleList);l.add(0);System.out.println(sampleList);}}

Page 60: final year project center in Coimbatore

HashSet class:• Underlying data structure is Hashtable.• Insertion order is not preserved.• Duplicate objects are not allowed.• Heterogeneous objects are allowed.• “null” insertion is possible, but only once.Best suitable if our frequent operation is

search.HashSet implements Serializable and

Cloneable interfaces.

Page 61: final year project center in Coimbatore

Eg:import java.util.*;class HSDemo{public static void main(String[] args){HashSet sampleSet=new HashSet();h.add("B");h.add("A");h.add("Z");h.add(null);h.add(10);System.out.println(sampleSet);}}

Page 62: final year project center in Coimbatore

Hashtable class:• Underlying data structure is Hashtable.• Heterogeneous objects are allowed.• Insertion order is not preserved and it is based

on hashCode.• “null” insertion is not allowed.

Page 63: final year project center in Coimbatore

Eg:import java.util.*;class HtDemo{public static void main(String[] args){Hashtable h=new Hashtable();h.put(new Temp(5),"A");h.put(new Temp(2),"B");h.put(new Temp(6),"C");h.put(new Temp(15),"D");h.put(new Temp(23),"E");h.put(new Temp(16),"F");System.out.println(h);}}

6=C

5=A, 16=F

15=D

2=B

23=E

0

1

2

3

4

5

6

7

8

9

10

Page 64: final year project center in Coimbatore

class Temp{int i;Temp(int i){this.i=i;}public String toString(){return i+"";}public int hashCode(){return i;}}

Page 65: final year project center in Coimbatore

Thank you