650 likes | 758 Views
Java workshop (Session 6). Presented by Y.Srikanth. Objectives:. Static and instance members, Exceptions, Multithreading, Garbage collection and Collections. Static members. “static” keyword:. “static” is used to maintain fixed values.
E N D
Java workshop (Session 6) Presented by Y.Srikanth
Objectives: • Static and instance members, • Exceptions, • Multithreading, • Garbage collection and • Collections
“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.
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.
Syntax for static methods: [modifier] static return-type method-name([parameters]) { Logic for the method; } Eg: staticint add(int a, int b) { return (a+b); }
Syntax for instance methods: [modifier] return-type method-name([parameters]) { Logic for instance method; } Eg: double mul(double d1, double d2) { return (d1*d2); }
Syntax for class variables: [modifier] static type variable-name[=value]; Eg: static inti=25; Syntax for instance variables: [modifier] type variable-name[=value]; Eg: inti=25;
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.
Eg: class Demo { inti; 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); } }
Eg: class Test { inti=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=100 j= t1 j =20 200 Static variable
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.
Exercise: • inti=1; • static inti=2; • 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
class Member { inti; public static void main(String[] args) { System.out.println(i); } }
Eg: class StatMethDemo { public static void add(inti, int j) { System.out.println(i+j); } public static void main(String[] args) { add(10,20); } }
Eg: class InstMethDemo { public void add(inti, int j) //instance method { System.out.println(i+j); } public static void main(String[] args) { add(10,20); } }
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.
Eg: class Test { public static void main(String[] args) { System.out.println("Hi"); System.out.println(10/0); System.out.println("Bye"); } }
When an exception is raised, JVM will provide the details(default mechanism) of the exception as follows: • Name of the exception, • Description, and • Stack trace(Location). Eg: Exception in thread “main” java.lang.ArithmeticException : / by zero at Test.main(Test.java:6)
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.
Object Throwable Exception Error RuntimeException IOException ArithmeticException FileNotFoundException NullPointerException Checked Exceptions Unchecked Exceptions
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)
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”); } } }
“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"); }
catch(ArithmeticException e) { System.out.println(e); } catch(Exception e) { System.out.println(e); } } }
“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”); } }
“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”); } }
Customized exceptions: Eg: class LessMarksException extends RuntimeException { LessMarksException(String s) { super(s); } } class GoodMarksException extends RuntimeException { GoodMarksException(String s) { super(s); } }
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"); } } }
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.
Runnable Thread MyThread MyRunnable
Implementation of multithreading can be done in 2 ways: • By extending Thread class: Eg: Class MyThread extends Thread { public void run() { for(inti=0;i<4;i++) { System.out.println(“child thread”); } } } Defining a thread Job of the thread
Class ThreadDemo { public static void main(String[] args) // Main thread { MyThread t=new MyThread(); // Instatiation of thread t.start(); // Starting child thread for(inti=0;i<4;i++) { System.out.println(“Main thread”); } } }
By implementing Runnable interface: Class MyRunnable implements Runnable { public void run() { for(inti=0;i<4;i++) { System.out.println(“Child thread”); } } } Defining Job
Class ThreadDemo { public static void main(String[] args) { MyRunnable r=new MyRunnable(); Thread t=new Thread(r); t.start(); for(inti=0;i<4;i++) { System.out.println(“Main thread”); } } } Target runnable
The purpose of ThreadScheduler is to get the opportunity for execution when multiple threads are awaiting. ThreadScheduler Child thread Main thread
MyThread t=new MyThread(); Thread life cycle: New/ Born t.start() Ready/ Runnable when wait() completes If ThreadScheduler allocated CPU Waiting state Running Dead wait() If run() completes
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.
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”); }
Eg: class TestSync implements Runnable { int balance; public synchronized void run() //synchronized method { for(inti=0;i<5;i++) { increment(); System.out.println("Bal is:"+balance); } } public void increment() { inti=balance; balance=i+1; } }
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(); } }
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)
Program for yield(): class MyThread extends Thread { public void run() { for(inti=0;i<5;i++) { Thread.yield(); System.out.println("child"); } } }
class YieldDemo { public static void main(String[] args) { MyThread t=new MyThread(); t.start(); for(inti=0;i<5;i++) { System.out.println("main"); } } }
Thread interruption: • One thread can interrupt another thread by using interrupt(). Eg: class MyThread extends Thread { public void run() { try { for(inti=0;i<20;i++) { System.out.println("lazy"); } Thread.sleep(5000); } catch(InterruptedException e) { System.out.println("got interrupted"); } } }
class InterruptDemo { public static void main(String[] args) { MyThread t=new MyThread(); t.start(); t.interrupt(); System.out.println("active"); } }
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