1 / 65

Java workshop (Session 6)

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.

Télécharger la présentation

Java workshop (Session 6)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java workshop (Session 6) Presented by Y.Srikanth

  2. Objectives: • Static and instance members, • Exceptions, • Multithreading, • Garbage collection and • Collections

  3. Static members

  4. “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.

  5. 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.

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

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

  8. 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;

  9. 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.

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

  11. 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

  12. 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.

  13. 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

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

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

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

  17. Exceptions

  18. 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.

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

  20. 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)

  21. 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.

  22. Object Throwable Exception Error RuntimeException IOException ArithmeticException FileNotFoundException NullPointerException Checked Exceptions Unchecked Exceptions

  23. 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)

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

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

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

  27. “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”); } }

  28. “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”); } }

  29. Customized exceptions: Eg: class LessMarksException extends RuntimeException { LessMarksException(String s) { super(s); } } class GoodMarksException extends RuntimeException { GoodMarksException(String s) { super(s); } }

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

  31. Multithreading

  32. 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.

  33. Runnable Thread MyThread MyRunnable

  34. 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

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

  36. By implementing Runnable interface: Class MyRunnable implements Runnable { public void run() { for(inti=0;i<4;i++) { System.out.println(“Child thread”); } } } Defining Job

  37. 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

  38. The purpose of ThreadScheduler is to get the opportunity for execution when multiple threads are awaiting. ThreadScheduler Child thread Main thread

  39. 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

  40. 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.

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

  42. 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; } }

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

  44. 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)

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

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

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

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

  49. Garbage collection

  50. 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

More Related