Learn java

6,094 views
5,978 views

Published on

Published in: Technology
15 Comments
63 Likes
Statistics
Notes
No Downloads
Views
Total views
6,094
On SlideShare
0
From Embeds
0
Number of Embeds
353
Actions
Shares
0
Downloads
0
Comments
15
Likes
63
Embeds 0
No embeds

No notes for slide

Learn java

  1. 1. Learn Java <ul><li>www.shareittips.com </li></ul>www.shareittips.com
  2. 2. OOPS <ul><li>Object Oriented Programming Structure </li></ul><ul><li>Features of OOPS </li></ul><ul><ul><li>Objects / Instance </li></ul></ul><ul><ul><li>Classes </li></ul></ul><ul><ul><li>Inheritance </li></ul></ul><ul><ul><li>Polymorphism </li></ul></ul><ul><ul><ul><li>Overloading / Static Polymorphism / Compile-time polymorphism </li></ul></ul></ul><ul><ul><ul><li>Overriding / Dynamic polymorphism / Run-time polymorphism </li></ul></ul></ul><ul><ul><li>Encapsulation </li></ul></ul><ul><ul><li>Abstraction </li></ul></ul>www.shareittips.com
  3. 3. OOPS <ul><li>Objects – Real time entity </li></ul><ul><li>Classes – Blueprint of an object. It gives structure to the objects </li></ul><ul><li>Inheritance – Deriving base class properties and behaviour to the child class </li></ul><ul><li>Polymorphism - One object in different forms </li></ul><ul><li>Encapsulation - Hiding the irrelevant details to the irrelevant entity </li></ul><ul><li>Abstraction – Revealing the relevant details to the relevant entity. </li></ul>www.shareittips.com
  4. 4. Structure of Java Compiler class C { @NonNull Object field; C( @NonNull Object p) { field = p; } @NonNull Object get() { return field; } } Source File Class File Comments www.shareittips.com Parser Class File Writer Error Type Checker
  5. 5. History of Java <ul><li>The original name of Java was Oak, and it was developed as a part of the Green project at Sun Microsystems. </li></ul><ul><li>Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridon at Sun Microsystems in 1991. </li></ul><ul><li>Sun formally announced the Java SunWorld in 1995. </li></ul>www.shareittips.com
  6. 6. Features of JAVA <ul><li>Object Oriented Programming language </li></ul><ul><li>Platform Independent </li></ul><ul><li>Robust </li></ul><ul><li>Portable </li></ul><ul><li>Scalable </li></ul><ul><li>Multithreaded </li></ul><ul><li>Architecturally neutral </li></ul><ul><li>Secured </li></ul>www.shareittips.com
  7. 7. Components of Java <ul><li>JDK – Java Development Kit </li></ul><ul><li>JRE – Java Run-time Environment </li></ul><ul><li>JVM - Java Virtual Machine </li></ul>www.shareittips.com
  8. 8. Java Virtual Machine <ul><li>The Java Virtual Machine provides a platform- </li></ul><ul><li>independent way of executing code, by abstracting the </li></ul><ul><li>differences between operating systems and CPU </li></ul><ul><li>architectures. </li></ul><ul><li>JVM is Write Once-Run Anywhere (WORA) software. </li></ul><ul><li>JVM forms part of large system JRE. </li></ul><ul><li>JVM's main job is interpreting java byte code and </li></ul><ul><li>translating this into actions or OS calls. </li></ul><ul><li>JVM is OS dependent which makes java source code as </li></ul><ul><li>machine independent. </li></ul>www.shareittips.com
  9. 9. JRE and JVM www.shareittips.com
  10. 10. Purpose of Features of OOPS <ul><li>Classes - Classification </li></ul><ul><li>Encapsulation - maintainability, flexibility and extensibility. </li></ul><ul><li>Polymorphism – one method will behave differently. </li></ul><ul><li>Inheritance – Reusability, Easier updates, Do not break what is already working. </li></ul>www.shareittips.com
  11. 11. Structure of JAVA Program <ul><li>Package declaration; </li></ul><ul><li>Import statements </li></ul><ul><li>Class declaration </li></ul><ul><li>{ </li></ul><ul><li>Variable declaration/ definition; </li></ul><ul><li>method declaration / definition; </li></ul><ul><li>} </li></ul>www.shareittips.com
  12. 12. Main method <ul><li>class <classname> </li></ul><ul><li>{ </li></ul><ul><li>public static void main(String[] args) </li></ul><ul><li>{ </li></ul><ul><li>// Object instantiation </li></ul><ul><li><classname> m = new <classname>(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>www.shareittips.com
  13. 13. CamelCase Convention <ul><li>Variables - myVariable </li></ul><ul><li>Method - myMethod() </li></ul><ul><li>Class - MyClass </li></ul><ul><li>Package - mypackage </li></ul><ul><li>Constants - MYCONSTANT </li></ul>www.shareittips.com
  14. 14. Types of Variable <ul><li>Local variable (variable inside method or block) </li></ul><ul><li>Class Variable (Static Variable) </li></ul><ul><li>Instance Variable ( variable inside the class) </li></ul><ul><li>Note: </li></ul><ul><li>Local variables require explicit initialization. </li></ul><ul><li>Instance variables are initialized automatically. </li></ul>www.shareittips.com
  15. 15. Variable Initialization <ul><li>Variable Value </li></ul><ul><li>byte 0 </li></ul><ul><li>short 0 </li></ul><ul><li>int 0 </li></ul><ul><li>long 0L </li></ul><ul><li>float 0.0F </li></ul><ul><li>double 0.0D </li></ul><ul><li>char 'u0000' </li></ul><ul><li>boolean false </li></ul><ul><li>All reference types null </li></ul>www.shareittips.com
  16. 16. Constructor <ul><li>It is a Spl. Method </li></ul><ul><li>Purpose: To initialize the class members </li></ul><ul><li>Features: </li></ul><ul><ul><li>Same name as that of the class name </li></ul></ul><ul><ul><li>No return type including VOID </li></ul></ul><ul><ul><li>Can have access specifier </li></ul></ul><ul><ul><li>Can be overloaded </li></ul></ul><ul><ul><li>Constructors are NOT inherited </li></ul></ul><ul><ul><li>Invoked automatically whenever the object is created. </li></ul></ul><ul><ul><li>The no. of time of invocation depends on no. of object created </li></ul></ul>www.shareittips.com
  17. 17. Arrays <ul><li>Group data objects of the same type, in a contiguous block of memory. </li></ul><ul><li>An array is an object; it is created with new. </li></ul><ul><li>Can be declared as a primitive type or Class type. </li></ul><ul><li>Array index starts with 0. </li></ul><ul><li>You cannot resize an array. </li></ul><ul><li>You can use the same reference variable to refer to an entirely new array. </li></ul>www.shareittips.com
  18. 18. Array Declaration and Instantiation <ul><li>Array declaration </li></ul><ul><ul><li><element type>[] <array name>; </li></ul></ul><ul><ul><li>int[] myArray; </li></ul></ul><ul><li>Constructing an array </li></ul><ul><ul><li> <array name> = new <element type> [<array size>]; </li></ul></ul><ul><ul><li>myArray = new int[5]; </li></ul></ul>www.shareittips.com
  19. 19. Initializing an Array <ul><li>Explicit initialization in one line. </li></ul><ul><ul><li><element type>[] <array name> = { <array initialize list> }; </li></ul></ul><ul><ul><li>Primitive array: </li></ul></ul><ul><ul><li>***************** </li></ul></ul><ul><ul><li>int[] myArray = { 1 , 2 , 3 , 4 , 5 } ; </li></ul></ul><ul><ul><li>Reference Array: </li></ul></ul><ul><ul><li>******************** </li></ul></ul><ul><ul><li>Object[] objArr = { new Pizza(), new Pizza(), null }; </li></ul></ul>www.shareittips.com
  20. 20. Initializing an Array <ul><li>Explicit initialization can also be done using array subscripts. </li></ul><ul><li>int[] myArray = new int[3]; </li></ul><ul><li> myArray [0] = 10; </li></ul><ul><li> myArray [1] = 20; </li></ul><ul><li> myArray [2] = 30; </li></ul>www.shareittips.com
  21. 21. Inheritance <ul><li>Deriving the parent class properties and methods to the child class. </li></ul><ul><li>Types of inheritance: </li></ul><ul><ul><li>Single level inheritance </li></ul></ul><ul><ul><li>- one super and one sub class </li></ul></ul><ul><ul><li>Multilevel inheritance </li></ul></ul><ul><ul><li>- The sub class of one level forms the super class of another level </li></ul></ul><ul><ul><li>Multiple inheritance [ not supported by java] </li></ul></ul><ul><ul><ul><li>- many super and one sub class </li></ul></ul></ul><ul><ul><li>Hierarchical inheritance </li></ul></ul><ul><ul><ul><li>- one super and many sub classes </li></ul></ul></ul><ul><ul><li>Hybrid inheritance </li></ul></ul><ul><ul><li>- multiple and multi level combined. </li></ul></ul>www.shareittips.com
  22. 22. Inheritance <ul><li>Two important concepts </li></ul><ul><ul><li>Generalization - Up the hierarchy </li></ul></ul><ul><ul><li>Specialization - Down the hierarchy </li></ul></ul><ul><li>Purpose : Reusability (without changing its identity) </li></ul><ul><li>Syntax: </li></ul><ul><li><modifier> class <name> extends <superclass> { </li></ul><ul><li><declaration>* </li></ul><ul><li>} </li></ul>www.shareittips.com
  23. 23. IS-A & HAS-A relationship <ul><li>When you want to know if one thing should extend another, use the IS-A test. </li></ul><ul><li>Eg : Triangle IS-A Shape </li></ul><ul><li>Do not apply inheritance if the subclass and super class do not pass the IS-A test. </li></ul><ul><li>Is-a relationship can be described in Java keyword extends. </li></ul><ul><li>The IS-A relationship – Unidirectional </li></ul>www.shareittips.com
  24. 24. IS-A & HAS-A relationship <ul><li>When two classes are related, but not through inheritance, (for example, one class has a reference to another class) then you say that the two classes are joined by HAS-A relationship. </li></ul><ul><li>Has-a relationship can be described in Java code as member fields. </li></ul><ul><li>Note: </li></ul><ul><li>Code reuse is also best achieved by aggregation when there is no is-a relationship </li></ul>www.shareittips.com
  25. 25. IS-A & HAS-A relationship <ul><li>class Car </li></ul><ul><li>{ </li></ul><ul><li>} </li></ul><ul><li>class BMW extends Car => IS-A R/S </li></ul><ul><li>{ </li></ul><ul><li> boolean auto_gear = “true” => Has-A R/S </li></ul><ul><li>} </li></ul>www.shareittips.com
  26. 26. Polymorphism <ul><li>Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions that is one interface with multiple methods. </li></ul><ul><li>Types: </li></ul><ul><ul><li>Overloading => Ad-Hoc Polymorphism </li></ul></ul><ul><ul><li>- Same method name with different set of </li></ul></ul><ul><ul><li>parameters. </li></ul></ul><ul><ul><li> - Early Binding </li></ul></ul><ul><ul><li>Overriding => True polymorphism </li></ul></ul><ul><ul><ul><li>- Same method name with same set of parameters. </li></ul></ul></ul><ul><ul><ul><li>- Late Binding </li></ul></ul></ul>www.shareittips.com
  27. 27. Types of Overloading <ul><li>Function Overloading </li></ul><ul><li>Constructor Overloading </li></ul><ul><li>NO operator Overloading in Java </li></ul><ul><li>Rules : </li></ul><ul><ul><li>No. of parameter should change </li></ul></ul><ul><ul><li>Datatype of the parameter should change </li></ul></ul><ul><ul><li>Sequence of passing the paramter should change. </li></ul></ul>www.shareittips.com
  28. 28. Overriding <ul><li>The overridden method in the superclass is NOT inherited by the subclass, and the new method in the subclass must uphold the following rules of method overriding: </li></ul><ul><ul><li>The new method definition must have the same method signature (i.e., method name and parameters) and the same return type. </li></ul></ul><ul><ul><li>Overridden Methods Cannot Be Less Accessible. </li></ul></ul><ul><li>A subclass cannot override fields of the superclass, but it can hide them. </li></ul><ul><li>Works only with inheritance. </li></ul><ul><li>Constructors cant be Overridden. </li></ul><ul><li>Super keyword is used to invoke an overridden method in the superclass. </li></ul>www.shareittips.com
  29. 29. this() and super() call for constructor <ul><li>this() construct is used to implement local chaining of constructors in the class when an instance of the class is created. </li></ul><ul><li>The this() call invokes the constructor with the corresponding parameter list. </li></ul><ul><li>super() method is used to invoke the IMMEDIATE base class constructor. This allows the subclass to influence the initialization of its inherited state when an object of the subclass is created. </li></ul><ul><li>this() and super() call must occur as the first statement in a constructor. </li></ul>www.shareittips.com
  30. 30. Example : this() and super() class GParent { int a,b,c; GParent() { System.out.println(&quot;From gparent&quot;); } GParent(int a,int b) { //this(a,b,100); this(); System.out.println(&quot;a= &quot;+a+&quot; b = &quot;+ b); } GParent(int a,int b,int c) { this.a=a; this.b=b; this.c=c; System.out.println(&quot;a= &quot;+a+&quot; b = &quot;+ b + &quot; c= &quot; +c); } } www.shareittips.com
  31. 31. Example : this() and super() class Parent extends GParent { int x,y; Parent() { System.out.println(&quot;From parent&quot;); } Parent(int x,int y) { super(x,y); this.x=x; this.y = y; System.out.println(&quot;x= &quot;+x+&quot; y = &quot;+ y); } } www.shareittips.com
  32. 32. Example : this() and super() class Child extends Parent { Child() { super(23,343); System.out.println(&quot;From child&quot;); } } class SuperEx { public static void main(String[] a) { //Parent p = new Parent(12,23); Child d = new Child(); } } www.shareittips.com
  33. 33. instanceof operator <ul><li>Use instanceof to test the type of an object. </li></ul><ul><li>Restore full functionality of an object by casting. </li></ul><ul><li>Example: </li></ul><ul><li>public void doSomething(Employee e) { </li></ul><ul><li>if ( e instanceof Manager ) </li></ul><ul><li>{ </li></ul><ul><li>Manager m = (Manager) e; </li></ul><ul><li>} </li></ul><ul><li>// rest of operation </li></ul><ul><li>} </li></ul>www.shareittips.com
  34. 34. Static Keyword <ul><li>It’s a Access Modifier </li></ul><ul><li>The static keyword is used as a modifier on variables, methods, and nested classes. </li></ul><ul><li>The static keyword declares the attribute or method is associated with the class as a whole rather than any particular instance of that class. </li></ul><ul><li>Thus static members are often called class members, such as class attributes or class methods. </li></ul>www.shareittips.com
  35. 35. Static Keyword <ul><li>A static method can access only the static variable. But the normal variable can access both static and normal variable. </li></ul><ul><li>Static members will get loaded into the memory only once. </li></ul><ul><li>Static members are subjected to change common for all the instance. </li></ul><ul><li>NO NEED FOR OBJECT to access the static member. </li></ul>www.shareittips.com
  36. 36. Static Variable Example class StatEx { int i=10; static int j = 20; public void normalMethod() { System.out.println(&quot;Instance var = &quot; + i++); System.out.println(&quot;Static var = &quot; + j++); } public static void main(String arg[]) { StatEx s1 = new StatEx(); StatEx s2 = new StatEx(); s1.normalMethod(); s2.normalMethod(); } } www.shareittips.com
  37. 37. Static Method Example class StatEx { int i=10; static int j = 20; public static void staticMethod() { //System.out.println(&quot;Instance var = &quot; + i++); //illegal System.out.println(&quot;Static var = &quot; + j++); } public static void main(String arg[]) { staticMethod(); staticMethod(); } } www.shareittips.com
  38. 38. Static Initializer Example class StatEx1 { static int counter; //static initializer static { counter=10; System.out.println(&quot;Static block invoked &quot;+counter); } public static void sMethod() { System.out.println(&quot;Static method&quot; + counter++); } } www.shareittips.com
  39. 39. Static Initializer Example class StatEx { public static void main(String arg[]) { System.out.println(&quot;from main&quot;); StatEx1.sMethod(); StatEx1.sMethod(); } } www.shareittips.com
  40. 40. Final Keyword <ul><li>Variable become Constant </li></ul><ul><li>Method cant be Overridden </li></ul><ul><li>Class cant be inherited </li></ul><ul><li>Note: </li></ul><ul><ul><li>All final variable need Explicit initialization </li></ul></ul>www.shareittips.com
  41. 41. Wrapper Class <ul><li>Conversion of primitive types to the object equivalent done through wrapper classes. </li></ul><ul><li>Allow objects to be created from primitive types. </li></ul><ul><li>Wrapped values are immutable (Cant modify) . To wrap another value, you need to create another object. </li></ul><ul><li>Wrapper class are present in java.lang package </li></ul><ul><li>All the wrapper classes are declared final. </li></ul>www.shareittips.com
  42. 42. Primitive Data Types and Corresponding Wrapper Classes All the wrapper classes except Boolean and Character are subclasses of an abstract class called Number , whereas Boolean and Character are derived directly from the Object class. www.shareittips.com Primitive Data Type Wrapper Class Constructor Arguments boolean Boolean boolean or String byte Byte byte or String char Character char short Short short or String int Integer int or String long Long long or String float Float double or float or String double Double double or String
  43. 43. Boxing and Unboxing <ul><li>Converting a value type to a reference type is known as Boxing. </li></ul><ul><li>Converting a reference type to a value type is known as UnBoxing. </li></ul><ul><li>int x=10; </li></ul><ul><li>Integer n = new Integer(x); //Boxing </li></ul><ul><li>int y = n.intValue(); //UnBoxing </li></ul>www.shareittips.com
  44. 44. AutoBoxing and AutoUnboxing <ul><li>Example: </li></ul><ul><li>int x=10; </li></ul><ul><li>Integer n = x; //AutoBoxing </li></ul><ul><li>int y = n; //AutoUnBoxing </li></ul>www.shareittips.com
  45. 45. Methods to Extract the Wrapped Values www.shareittips.com Method Class public boolean booleanValue() Boolean public char charValue() Character public byte byteValue() Byte, Short, Integer, Long, Float, Double public short shortValue() Byte, Short, Integer, Long, Float, Double public int intValue() Byte, Short, Integer, Long, Float, Double public long longValue() Byte, Short, Integer, Long, Float, Double public float floatValue() Byte, Short, Integer, Long, Float, Double public double doubleValue() Byte, Short, Integer, Long, Float, Double
  46. 46. Methods to Convert Strings to Primitive Types www.shareittips.com Wrapper Class Method Signature Method Arguments Boolean static boolean parseBoolean(…) String Character Not available Byte static byte parseByte(…) String, or String and radix Short static short parseShort(..) String, or String and radix Integer static int parseInt(…) String, or String and radix Long static long parseLong(…) String, or String and radix Float static float parseFloat(…) String Double static double parseDouble(…) double or String
  47. 47. Wrapper Conversion methods <ul><li>Primitive xxxValue() </li></ul><ul><ul><li>To convert Wrapper to primitive </li></ul></ul><ul><li>Primitive parseXxx(String) </li></ul><ul><ul><li>To convert a String to a primitive </li></ul></ul><ul><li>Wrapper valueOf(String) </li></ul><ul><ul><li>To convert a String to a Wrapper </li></ul></ul>www.shareittips.com
  48. 48. Object Class <ul><li>Root class of Java => Object </li></ul><ul><li>equals() method = > Check only values </li></ul><ul><li>toString() method =>Check value & reference </li></ul><ul><li>hashCode() => return the address of the object </li></ul><ul><li>Object Class is in java.lang package. </li></ul>www.shareittips.com
  49. 49. Abstract Class <ul><li>Class which have a abstract method (method without definition) is abstract class. </li></ul><ul><li>Can have normal method and variable </li></ul><ul><li>Cant be instantiated </li></ul><ul><li>Methods may or may not be implemented by the child class. </li></ul><ul><li>Use abstract keyword to declare a class as abstract. </li></ul><ul><li>Abstract method cannot be private or final </li></ul><ul><li>A class can inherit only one abstract class. </li></ul><ul><li>NEED RELATIONSHIP between classes </li></ul>www.shareittips.com
  50. 50. Interface <ul><li>Interface is to support multiple inheritance in Java. </li></ul><ul><li>Interfaces should be implemented by the child class </li></ul><ul><li>Can have only abstract method. </li></ul><ul><li>Interface contain only constants.NO Variables. </li></ul><ul><li>All the fields are public static final in nature. </li></ul><ul><li>Interfaces cant be instantiated </li></ul><ul><li>A class can implement many interfaces. </li></ul><ul><li>All the methods should be implemented by the child class. </li></ul><ul><li>NO NEED FOR RELATIONSHIP </li></ul>www.shareittips.com
  51. 51. enum <ul><li>Assigning a integral constant to a symbolic name => enum </li></ul><ul><li>Use enum when you want a variable to hold only a predetermined set of values. </li></ul><ul><li>You use the keyword enum and not class to declare an enum. </li></ul><ul><li>Just like a class, an enum can have constructors, methods, and fields. </li></ul><ul><li>An enum cannot be declared within a method. </li></ul><ul><li>You cannot instantiate an enum with the new operator. </li></ul>www.shareittips.com
  52. 52. enum <ul><li>The enums do not participate in class hierarchy: they cannot extend and they cannot be extended. </li></ul><ul><li>You cannot directly call an enum constructor. </li></ul><ul><li>An enum may have a main() method and therefore can be executed by name from the command line like an application. </li></ul>www.shareittips.com
  53. 53. Enum Example1 enum Edge { TOP,BOTTOM,LEFT,RIGHT }; class MyClass { public static void main(String[] a) { Edge e = Edge.TOP; int i = e.ordinal(); System.out.println(e); System.out.println(i); } } www.shareittips.com
  54. 54. Enum Example2 enum Edge { TOP,BOTTOM,LEFT,RIGHT; public static void main(String[] a) { Edge e = Edge.TOP; int i = e.ordinal(); System.out.println(e); System.out.println(i); } } www.shareittips.com
  55. 55. Enum Example3 public enum Day { MONDAY(8,true), TUESDAY(8,true), WEDNESDAY(8,true), THURSDAY(8,true), FRIDAY(8,true), SATURDAY(4,false), SUNDAY(0,false); private int hours; private boolean weekday; www.shareittips.com
  56. 56. Enum Example3 Day(int whours,boolean wday) { hours=whours; wday=weekday; } public int getHours() { return hours; } public boolean isWeekDay() { return weekday; } www.shareittips.com
  57. 57. Enum Example3 public static void showDay(Day d) { if(d.isWeekDay()) { System.out.println(d +&quot; is a weekday and has &quot;+ d.getHours() +&quot; hours working hours&quot;); } else { System.out.println(d +&quot; is a not weekday and has &quot;+ d.getHours() +&quot; hours working hours&quot;); } } www.shareittips.com
  58. 58. Enum Example3 public static void main(String[] ar) { Day day; day = Day.SUNDAY; showDay(day); } } www.shareittips.com
  59. 59. Inner Class <ul><li>A class that is declared within another class or interface, is called a nested class. </li></ul><ul><li>There are four categories of nested classes </li></ul><ul><ul><li>Regular class - class within the class </li></ul></ul><ul><ul><li>Method-local class – class within the method of the outer class </li></ul></ul><ul><ul><li>Static nested class - inner classes marked with the static modifier (top-level nested class) </li></ul></ul><ul><ul><li>Anonymous class - part of a method argument. </li></ul></ul><ul><li>All inner classes are nested classes, but not all nested classes are inner classes. </li></ul>www.shareittips.com
  60. 60. Example for Regular InnerClass class MyOuter { int x =7; class MyInner { public void InnerMethod() { System.out.println(&quot;x == &quot; + x); } } public void OuterMethod() { MyInner inn = new MyInner(); inn.InnerMethod(); } www.shareittips.com
  61. 61. Example for Regular InnerClass public static void main(String[] a) { MyOuter mo = new MyOuter(); MyOuter.MyInner mi = mo.new MyInner(); mi.InnerMethod(); mo.OuterMethod(); //mi.OuterMethod(); illegal //mo.InnerMethod(); illegal } } www.shareittips.com
  62. 62. Method-local inner class <ul><li>A method-local inner class can be instantiated only within the method where the inner class is defined. </li></ul><ul><li>Can access the outer class level variable. </li></ul><ul><li>CANT access the variable inside the method in which the inner class is created except a final variable. </li></ul><ul><li>Method-local inner class can be declared abstract and final. </li></ul><ul><li>method-local inner class can't use any access specifiers. </li></ul>www.shareittips.com
  63. 63. Method-local inner class class MouterClass { int x =10; public void OuterMethod() { final int j=90; class MinnerClass { public void minnerMethod() { System.out.println(&quot;Hello ...&quot; + x + j); } } MinnerClass mic = new MinnerClass(); mic.minnerMethod(); } public static void main(String[] a) { MouterClass moc = new MouterClass(); moc.OuterMethod(); } } www.shareittips.com
  64. 64. Static nested class <ul><li>Static nested classes are inner classes marked with the static modifier. </li></ul><ul><li>A static nested class is not an inner class, it's a top-level nested class. </li></ul><ul><li>A static nested class cannot access non-static members of the outer class. </li></ul>www.shareittips.com
  65. 65. Static nested class class OuterClass { static int i =10; public void method() { System.out.println(&quot;i == &quot; + ++i); } static class InnerClass { public void display() { System.out.println(&quot;i == &quot; + i); } } www.shareittips.com
  66. 66. Static nested class public static void main(String[] a) { OuterClass.InnerClass ic = new OuterClass.InnerClass(); ic.display(); OuterClass oc = new OuterClass(); oc.method(); } } www.shareittips.com
  67. 67. Anonymous Inner Classes <ul><li>Anonymous inner classes have no name. </li></ul><ul><li>Anonymous inner classes cannot have constructor. </li></ul>www.shareittips.com
  68. 68. Anonymous Inner Classes import java.awt.*; import java.awt.event.*; class FrameExample { private Frame f; public FrameExample() { f = new Frame(&quot;Hello .....!&quot;); } public void launchFrame() { f.setSize(170,170); f.setBackground(Color.blue); f.setVisible(true); www.shareittips.com
  69. 69. Anonymous Inner Classes // Add a window listener f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent evt) { System.exit(0); } }); //Anonymous Inner Classes } public static void main(String args[]) { FrameExample f = new FrameExample(); f.launchFrame(); } } www.shareittips.com
  70. 70. Exception Handling <ul><li>An exception in Java is a signal that indicates the occurrence of some important or unexpected condition during execution. </li></ul><ul><li>Error Types: </li></ul><ul><ul><li>happens due to problems originating from the execution environment. (Error Class) </li></ul></ul><ul><ul><li>happens due to problems originating inside the application itself. (Exception Class) </li></ul></ul><ul><li>Exception Should be Handled or Thrown to the exception handler. </li></ul>www.shareittips.com
  71. 71. Exceptions <ul><li>Errors (represented by subclasses of Error) occur in the Java virtual machine (JVM) and not in the application itself. </li></ul><ul><li>The exceptions (represented by subclasses of Exception), on the other hand, generally originate from within the application. </li></ul><ul><li>Types: </li></ul><ul><ul><li>Checked Exception </li></ul></ul><ul><ul><li>Unchecked Exception </li></ul></ul>www.shareittips.com
  72. 72. Checked Exception <ul><li>Checked exceptions are generally related to how the program interacts with its environment. </li></ul><ul><li>This is the category of exceptions for which the compiler checks (hence the name checked exceptions) to ensure that your code is prepared for them. </li></ul><ul><li>The programmer is required to write code to deal with checked exceptions. The compiler checks that such code exists. </li></ul><ul><li>It MUST be thrown programmatically or Handled. </li></ul>www.shareittips.com
  73. 73. Unchecked Exception <ul><li>Occur due to program bugs. </li></ul><ul><li>Runtime exceptions are not checked by the compiler . </li></ul><ul><li>Write the correct code to avoid the runtime exceptions than write the code to catch them but it is not illegal to catch them. </li></ul><ul><li>Runtime exceptions and errors combined are also called unchecked exceptions and they are mostly thrown by the JVM . </li></ul>www.shareittips.com
  74. 74. The Exception Class Hierarchy Object Throwable Exception Error RuntimeException Others… Others… Others… www.shareittips.com
  75. 75. Exception-handling mechanism <ul><li>Contains five keywords: </li></ul><ul><ul><li>try - catch – throw - throws – finally </li></ul></ul><ul><ul><li>Method throws ExceptionName{ </li></ul></ul><ul><ul><li>try{ </li></ul></ul><ul><ul><li>--risky code goes here </li></ul></ul><ul><ul><li>} catch(ExceptionClassName ObjectName){ </li></ul></ul><ul><ul><li>-- Exception handler block code </li></ul></ul><ul><ul><li>throw Exception_Instance //Ducking it </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>finally{ </li></ul></ul><ul><ul><li>-- cleanup your code goes here </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>www.shareittips.com
  76. 76. About try-catch-finally <ul><li>A try block should be followed by at least one catch block. </li></ul><ul><li>The code inside try block is called as protected code. </li></ul><ul><li>Can have one or more catch block. </li></ul><ul><li>If you have multiple catch block, make sure that the last catch block contain the super most class in the hierarchy. </li></ul><ul><li>You may also write an optional “finally” block. This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code. </li></ul><ul><li>The catch block may or may not contain throw keyword. </li></ul><ul><li>The try block can also be nested. </li></ul>www.shareittips.com
  77. 77. Example 1 class PrintStack { public static void main(String args[]) { int Num1= 30 , Num2 = 0; try { int Num3=Num1/Num2; } catch(ArithmeticException obj) { System.out.println(&quot;Exception&quot;+obj); obj.printStackTrace(); } } } www.shareittips.com
  78. 78. Rules in Exception <ul><li>The Declare or Handle Rule </li></ul><ul><ul><li>Handle the exception by using the </li></ul></ul><ul><ul><li>try-catch-finally block. </li></ul></ul><ul><li>Declare that the code causes an exception by using the throws clause. </li></ul><ul><li>You do not need to declare runtime exceptions or errors. </li></ul><ul><li>You can choose to handle runtime exceptions. </li></ul>www.shareittips.com
  79. 79. Passing the exception <ul><ul><li>In any method that might throw an exception, you may declare the method as “throws” that exception, and thus avoid handling the exception yourself </li></ul></ul><ul><ul><li>Example </li></ul></ul><ul><ul><ul><li>public void myMethod throws IOException { … normal code with some I/O } </li></ul></ul></ul>www.shareittips.com
  80. 80. Throws clause class UncheckedThrows { public void show() throws ArithmeticException { System.out.println(&quot;Hai I am not handled&quot;); } public static void main(String[] arg) { new UncheckedThrows().show(); } } www.shareittips.com
  81. 81. Method Overriding and Exceptions <ul><li>The overriding method can throw: </li></ul><ul><ul><li>No exceptions </li></ul></ul><ul><ul><li>One or more of the exceptions thrown by the </li></ul></ul><ul><ul><li>overridden method. </li></ul></ul><ul><ul><li>One or more subclasses of the exceptions </li></ul></ul><ul><ul><li>thrown by the overridden method. </li></ul></ul><ul><li>The overriding method cannot throw: </li></ul><ul><ul><li>Additional exceptions not thrown by the </li></ul></ul><ul><ul><li>overridden method. </li></ul></ul><ul><ul><li>Super classes of the exceptions thrown by </li></ul></ul><ul><ul><li>the overridden method </li></ul></ul>www.shareittips.com
  82. 82. User Defined Exception <ul><li>Create User-Defined Exception as a Class that </li></ul><ul><li>EXTENDS Exception Class. </li></ul><ul><li>Instantiate the created Exception and use it in the catch block as a handler. </li></ul>www.shareittips.com
  83. 83. Example 2 import java.io.*; class MyException extends Exception { MyException() { System.out.println(&quot;UserDefined Error occured&quot;); } public String toString() { return &quot;MyException thrown&quot;; } } www.shareittips.com
  84. 84. Example 2 cont… class UserExceptions { public void valid() { try { String str1,str2; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(&quot;Enter Login id&quot;); str1=br.readLine(); System.out.println(&quot;Enter password&quot;); str2=br.readLine(); if(str1.equals(str2)) System.out.println(&quot;Hai welcome&quot;); else throw new MyException(); } www.shareittips.com
  85. 85. Example 2 cont … catch(MyException e) { System.out.println(&quot;Sorry U r not a valid user&quot; + e); valid(); } catch(IOException ioe){} } public static void main(String[] arg) throws IOException { UserExceptions e1=new UserExceptions(); e1.valid(); } } www.shareittips.com
  86. 86. String Class Facts <ul><li>An object of the String class represents a string of characters. </li></ul><ul><li>The String class belongs to the java.lang package , which does not require an import statement. </li></ul><ul><li>Like other classes, String has constructors and methods. </li></ul><ul><li>Unlike other classes, String has two operators, + and += (used for concatenation). </li></ul><ul><li>String class is declare final , therefore immutable. </li></ul>www.shareittips.com
  87. 87. Literal Strings <ul><li>are anonymous objects of the String class </li></ul><ul><li>are defined by enclosing text in double quotes. “This is a literal String” </li></ul><ul><li>don’t have to be constructed. </li></ul><ul><li>can be assigned to String variables. </li></ul><ul><li>can be passed to methods and constructors as parameters. </li></ul><ul><li>have methods you can call. </li></ul>www.shareittips.com
  88. 88. Literal String Example <ul><li>//assign a literal to a String variable </li></ul><ul><li>String name = “Priya”; </li></ul><ul><li>//calling a method on a literal String </li></ul><ul><li>char Initial = “Priya”.charAt(0); </li></ul><ul><li>//calling a method on a String variable </li></ul><ul><li>char Initial = name.charAt(0); </li></ul>www.shareittips.com
  89. 89. Immutability <ul><li>Once created, a string cannot be changed: none of its methods changes the string. </li></ul><ul><li>Such objects are called immutable . </li></ul><ul><li>Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change. </li></ul>www.shareittips.com
  90. 90. Advantages Of Immutability <ul><li>Uses less memory </li></ul>String word1 = &quot;Java&quot;; String word2 = word1; String word1 = “Java&quot;; String word2 = new String(word1); word1 OK Less efficient: wastes memory word2 word1 word2 www.shareittips.com “ Java&quot; “ Java&quot; “ Java&quot;
  91. 91. Disadvantages of Immutability <ul><li>Less efficient — you need to create a new string and throw away the old one even for small changes. </li></ul>String word = “Java”; char ch = Character.toUpperCase(word.charAt (0)); word = ch + word.substring (1); word www.shareittips.com “ java&quot; “ Java&quot;
  92. 92. Empty Strings <ul><li>An empty String has no characters. It’s length is 0. </li></ul><ul><li>Not the same as an uninitialized String. </li></ul>String word1 = &quot;&quot;; String word2 = new String(); private String errorMsg; errorMsg is null Empty strings www.shareittips.com
  93. 93. Copy Constructors <ul><li>Copy constructor creates a copy of an existing String. Also rarely used. </li></ul><ul><li>Not the same as an assignment. </li></ul>String word1 = new String(“Java”); String word2 = new String(word); word1 word2 Copy Constructor: Each variable points to a different copy of the String. String word1 = “Java”; String word2 = word; word1 word2 Assignment: Both variables point to the same String. www.shareittips.com “ Java&quot; “ Java&quot; “ Java&quot;
  94. 94. Other Constructors <ul><li>Most other constructors take an array as a parameter to create a String. </li></ul><ul><li>String index starts with 0 like arrays. </li></ul>char[] letters = {‘J’, ‘a’, ‘v’, ‘a’}; String word = new String(letters);//”Java” www.shareittips.com
  95. 95. Methods in String Class <ul><li>char charAt(i) => Returns the char at position i. </li></ul><ul><li>int length(); => Returns the number of characters in the string. </li></ul><ul><li>String substring() => Returns a substring object </li></ul><ul><li>substring(i,k) substring(i) </li></ul><ul><li>“ television&quot;.substring (2,5); “television&quot;.substring (2); </li></ul>television i k television i www.shareittips.com
  96. 96. Methods in String Clas <ul><li>indexOf() => returns the index position of the character. </li></ul><ul><li>equals() </li></ul><ul><li>equalsIgnoreCase() </li></ul><ul><li>compareTo() </li></ul><ul><li>compareToIgnoreCase() </li></ul><ul><li>trim() </li></ul><ul><li>replace() </li></ul><ul><li>toUpperCase() </li></ul><ul><li>toLowerCase() </li></ul>www.shareittips.com
  97. 97. StringBuffer Class <ul><li>String Buffers are mutable strings. </li></ul><ul><li>StringBuffer is a final class. </li></ul><ul><li>They can be created empty, from a string or with a capacity. An empty StringBuffer is created with 16-character capacity. </li></ul><ul><li>Can grow dynamically in size without bounds. </li></ul>www.shareittips.com
  98. 98. Methods in String Buffer <ul><li>length() </li></ul><ul><li>capacity() </li></ul><ul><li>ensureCapacity() </li></ul><ul><li>setLength() </li></ul><ul><li>charAt() </li></ul><ul><li>Append() </li></ul><ul><li>setCharAt() </li></ul><ul><li>Insert() </li></ul><ul><li>deleteCharAt() </li></ul><ul><li>replace() </li></ul><ul><li>reverse() </li></ul>www.shareittips.com
  99. 99. StringBuilder Class <ul><li>Same like StringBuffer Class </li></ul><ul><li>StringBuilder’s methods are not synchronized. </li></ul><ul><li>StringBuilder methods should run faster than StringBuffer methods. </li></ul>www.shareittips.com
  100. 100. Collections <ul><li>A collection allows a group of objects to be treated as a single unit. </li></ul><ul><li>Arbitrary objects can be stored, retrieved, and manipulated as elements of collections. </li></ul><ul><li>Provided in the java.util package. </li></ul><ul><li>The collections framework comprises three main parts. </li></ul><ul><ul><li>Interfaces => Collection </li></ul></ul><ul><ul><li>Classes => Collections </li></ul></ul><ul><ul><li>Algorithms </li></ul></ul>www.shareittips.com
  101. 101. The Collections Interfaces <ul><li>The root of the hierarchy of the collections interfaces </li></ul><ul><li>is the Collection interface. </li></ul><ul><li>There is another kind of collections called maps, </li></ul><ul><li>which are represented by the super interface Map. </li></ul>Both a Map object and a Set collection cannot contain duplicates data items. while a List collection can contain duplicates. www.shareittips.com
  102. 102. The Collections Interfaces <ul><ul><li>A collection has no special order and does not reject duplicates. ( java.util.Collection ) </li></ul></ul><ul><ul><li>A list is ordered and accept duplicates. ( java.util.List ). </li></ul></ul><ul><ul><li>A set has no special order but rejects duplicates. ( java.util.Set ) </li></ul></ul><ul><ul><li>A map supports searching on a key field, values of which must be unique. ( java.util.Map ) </li></ul></ul>www.shareittips.com
  103. 103. Collection Classes <ul><li>ArrayList, LinkedList , and Vector are the classes that implement the List interface . </li></ul><ul><li>HashMap and HashTable are examples of classes that implement the Map interface . </li></ul><ul><li>HashSet and LinkedHashSet are examples of classes that implement the Set interface . </li></ul>www.shareittips.com
  104. 104. www.shareittips.com
  105. 105. List import java.util.*; class ListExample { public static void main(String[] args) { List list = new ArrayList(); list.add(&quot;one&quot;); list.add(&quot;second&quot;); list.add(&quot;3rd&quot;); list.add(new Integer(4)); list.add(new Float(5.0F)); list.add(&quot;second&quot;); // duplicate, is added list.add(new Integer(4)); // duplicate, is added System.out.println(list); } } www.shareittips.com
  106. 106. Set import java.util.*; class SetExample { public static void main(String[] args) { Set set = new HashSet(); set.add(&quot;one&quot;); set.add(&quot;second&quot;); set.add(&quot;3rd&quot;); set.add(new Integer(4)); set.add(new Float(5.0F)); set.add(&quot;second&quot;); // duplicate, not added set.add(new Integer(4)); // duplicate, not added System.out.println(set); } } www.shareittips.com
  107. 107. Collection API - Storage <ul><li>The storage associated with any one collection can be implemented in many ways, but the Collections API implements the four methods that are most widely used: </li></ul><ul><ul><li>Array : supports insertion, deletion, but growing the store is more difficult. </li></ul></ul><ul><ul><li>ArrayList : grow in number of elements. Search is faster. But not insertion and deletion. Vector(provides synchronization) </li></ul></ul><ul><ul><li>Linked list : supports insertion, deletion, and growing the store, but makes indexed access slower. Use when insertions and deletions happen frequently. </li></ul></ul><ul><ul><li>Tree : supports insertion, deletion, and growing the list. Indexed access is slow, but searching is faster. </li></ul></ul><ul><ul><li>Hash table : supports insertion, deletion, and growing the store. Indexed access is slow, but searching is particularly fast. However, hashing requires the use of unique keys for storing data elements. </li></ul></ul>www.shareittips.com
  108. 108. Set Classes <ul><li>HashSet : </li></ul><ul><ul><li>provides the faster access to a data item. </li></ul></ul><ul><ul><li>no guarantee that the items will be ordered. </li></ul></ul><ul><ul><li>does not offer synchronization. </li></ul></ul><ul><li>Tree Set: </li></ul><ul><ul><li>presents sorted data items. </li></ul></ul><ul><ul><li>performance is not as good as HashSet. </li></ul></ul><ul><ul><li>does not offer synchronization. </li></ul></ul><ul><li>LinkedHashSet: </li></ul><ul><ul><li>Similar to HashSet that maintains a doubly linked list. </li></ul></ul><ul><ul><li>It is an ordered collection, ordered by insertion, but not sorted. </li></ul></ul><ul><ul><li>does not offer synchronization </li></ul></ul>www.shareittips.com
  109. 109. Map Classes <ul><li>HashTable: </li></ul><ul><ul><li>implementation is based on the hashtable data structure. </li></ul></ul><ul><ul><li>No ordering. </li></ul></ul><ul><ul><li>implementation is synchronized </li></ul></ul><ul><li>HashMap: </li></ul><ul><ul><li>based on the hashtable data structure. </li></ul></ul><ul><ul><li>No ordering </li></ul></ul><ul><ul><li>allows null and is unsynchronized </li></ul></ul><ul><li>LinkedHashMap: </li></ul><ul><ul><li>maintains a doubly linked list. </li></ul></ul><ul><li>TreeMap: </li></ul><ul><ul><li>implements the SortedMap interface </li></ul></ul><ul><ul><li>Sorted and unsynchronized. </li></ul></ul>www.shareittips.com
  110. 110. www.shareittips.com Class Interface Duplicates Allowed? Ordered/ Sorted Synchronized ArrayList List Yes Ordered by index Not sorted No LinkedList List Yes Ordered by index Not sorted No Vector List Yes Ordered by index Not sorted Yes HashSet Set No Not ordered Not sorted No LinkedHashSet Set No Ordered by insertion Not sorted No TreeSet Set No Sorted either by natural order or by your comparison rules No
  111. 111. www.shareittips.com Class Interface Duplicates Allowed? Ordered/ Sorted Synchronized HashMap Map No Not ordered Not sorted No LinkedHashMap Map No Ordered No Hashtable Map No Not ordered Not sorted Yes TreeMap Map No Sorted either by natural order or by your comparison rules No
  112. 112. Collection Advantages and Disadvantages <ul><li>Advantages </li></ul><ul><ul><li>Can hold different types of objects. </li></ul></ul><ul><ul><li>Resizable </li></ul></ul><ul><li>Disadvantages </li></ul><ul><ul><li>Must cast to correct type </li></ul></ul><ul><ul><li>Cannot do compile-time type checking. </li></ul></ul>www.shareittips.com
  113. 113. Generics <ul><li>For checking the type of object during the compilation time. </li></ul><ul><li>Enclose the type within angular brackets <>. </li></ul>www.shareittips.com
  114. 114. Date Class <ul><li>The java.text.DateFormat class provides several methods for formatting the date/time for a default or a specific location, and yet you can keep your code completely independent of the locale conventions for months, days of the week, days of the months, and so on. </li></ul><ul><li>You create a locale object by using the Locale class </li></ul>www.shareittips.com
  115. 115. Process and Thread <ul><li>A process is a program that is currently executing. Every process has at least one thread running within it. </li></ul><ul><li>Threads are referred to as lightweight processes. </li></ul><ul><li>A thread is a path of code execution through a program, and each thread has its own local variables, program counter (pointer to the current instruction being executed), and lifetime. </li></ul>www.shareittips.com
  116. 116. Threads <ul><li>A thread is not an object </li></ul><ul><li>A thread is a flow of control </li></ul><ul><li>A thread is a series of executed statements </li></ul><ul><li>A thread is a nested sequence of method calls </li></ul>www.shareittips.com
  117. 117. MultiThreading and MultiTasking <ul><li>Multitasking is a mechanism to run many Heavyweight processes simultaneously in a different address space so context switch or intercommunication between processes is much expensive. </li></ul><ul><li>Multithreading is a mechanism of running various lightweight processes under single process within its own space </li></ul><ul><li>Multiprocessing there will be more than one processor and each thread will be handled by a different processor. </li></ul>www.shareittips.com
  118. 118. Creation of a Thread <ul><li>By extending Thread class </li></ul><ul><li>By implementing Runnable interface . </li></ul><ul><li>Even a non-multithreaded program has one thread of execution, called the main thread. </li></ul><ul><li>Call the start() method to start the thread. </li></ul><ul><li>When a thread is started, it calls the run() method to make our thread to perform useful work. </li></ul>www.shareittips.com
  119. 119. 1st Method: Extending the Thread class <ul><li>class MyThread extends Thread </li></ul><ul><li>{ </li></ul><ul><li> public void run() </li></ul><ul><li> { </li></ul><ul><li> // thread body of execution </li></ul><ul><li> } </li></ul><ul><li>} </li></ul><ul><li>Creating thread: </li></ul><ul><li>MyThread thr1 = new MyThread(); </li></ul><ul><li>Start Execution: </li></ul><ul><li>thr1.start(); </li></ul>www.shareittips.com
  120. 120. 2nd method: Threads by implementing Runnable interface <ul><li>class ClassName implements Runnable{ </li></ul><ul><li>public void run() </li></ul><ul><li>{ </li></ul><ul><li> // thread body of execution </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Creating Object: </li></ul><ul><li>ClassName myObject = new ClassName(); </li></ul><ul><li>Creating Thread Object: </li></ul><ul><li>Thread thr1 = new Thread( myObject ); </li></ul><ul><li>Start Execution: </li></ul><ul><li>thr1.start(); </li></ul>www.shareittips.com
  121. 121. Thread scheduling <ul><li>Thread scheduling is implementation dependent and cannot be relied on to act in the same way on every JVM </li></ul><ul><li>The two approaches to scheduling are </li></ul><ul><ul><li>Preemptive - will be applied for thread with highest and lowest priority </li></ul></ul><ul><ul><li>Time-Sliced (Round-Robin) Scheduling – will be applied when more than one thread has the same priority. </li></ul></ul>www.shareittips.com
  122. 122. Threads within a process <ul><li>All threads are parts of a process hence communication easier and simpler. </li></ul><ul><li>Independent executables </li></ul>THREAD STACK THREAD DATA THREAD TEXT SHARED MEMORY www.shareittips.com
  123. 123. Thread States A thread can in one of several possible states: 1.Running Currently running In control of CPU 2.Ready to run Can run but not yet given the chance 3.Resumed Ready to run after being suspended or block 4.Suspended Voluntarily allowed other threads to run 5.Blocked Waiting for some resource or event to occur www.shareittips.com
  124. 124. Thread Priorities Why priorities? Determine which thread receives CPU control and gets to be executed first Definition: – Integer value ranging from 1 to 10 – Higher the thread priority -> larger chance of being executed first – Example: ● Two threads are ready to run ● First thread: priority of 5, already running ● Second thread = priority of 10, comes in while first thread is running www.shareittips.com
  125. 125. Thread Synchronization <ul><li>Done in two ways </li></ul><ul><ul><li>To method </li></ul></ul><ul><ul><ul><li>public synchronized void method() </li></ul></ul></ul><ul><ul><ul><li>{ } </li></ul></ul></ul><ul><ul><li>To block </li></ul></ul><ul><ul><ul><li>synchronized(this) </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>www.shareittips.com
  126. 126. Wait() and notify() <ul><li>Wait() and notify should be used to restrict the thread before doing an operation without a notification from the other thread. </li></ul><ul><li>Should be used along with the synchronized block </li></ul>www.shareittips.com
  127. 127. wait() <ul><li>When a thread enters a wait state, it does nothing until it is notified by another thread. </li></ul><ul><li>It also gives up it’s lock on the object when wait is called. </li></ul><ul><li>public synchronized blah() { </li></ul><ul><li>wait(); </li></ul><ul><li>… // do something </li></ul><ul><li>} </li></ul>www.shareittips.com
  128. 128. notify() <ul><li>To awaken a thread, a different thread which has a lock on the same object must call notify. </li></ul><ul><li>When notify is called, the block that had the lock on the object continues to have it’s lock it releases it. </li></ul><ul><ul><li>Then a thread is awakened from its wait() and can grab the lock and continue processing. </li></ul></ul><ul><li>There are two versions - notify() and notifyAll(). </li></ul><ul><li>Notify is safe only under 2 conditions: </li></ul><ul><ul><li>When only 1 thread is waiting, and thus guaranteed to be awakened. </li></ul></ul><ul><ul><li>When multiple threads are waiting on the same condition, and it doesn’t matter which one awakens. </li></ul></ul><ul><li>In general, use notifyAll() </li></ul>www.shareittips.com
  129. 129. Thread Group <ul><li>You can include thread in a set of threads by adding it to an instance of ThreadGroup </li></ul><ul><li>ThreadGroups can contain not only threads but also other ThreadGroups. </li></ul>www.shareittips.com
  130. 130. Semaphore <ul><li>Semaphore is a synchronization mechanism, which implements mutual exclusion among processes to avoid race condition to access any shared resource. </li></ul><ul><li>Semaphore maintains a counter to implement locking and unlocking. It avoids busy waiting. If a critical section is in use, the calling process will be removed from a run queue and put into a sleep state. </li></ul><ul><li>Java 5 comes with semaphore implementations in the java.util.concurrent package so you don't have to implement your own semaphores. </li></ul><ul><li>A mutex is really a semaphore with value 1. </li></ul>www.shareittips.com
  131. 131. Semaphores <ul><li>Semaphores have two purposes </li></ul><ul><ul><li>Mutex: Ensure threads don’t access critical section at same time </li></ul></ul><ul><ul><li>Scheduling constraints: Ensure threads execute in specific order </li></ul></ul><ul><li>A semaphore is an IPC mechanism that is implemented conceptually with at least these two components </li></ul><ul><ul><ul><ul><li>a counter (int) variable </li></ul></ul></ul></ul><ul><ul><ul><ul><li>a wait queue of processes </li></ul></ul></ul></ul><ul><li>And has at least these two operation </li></ul><ul><ul><li>wait for the semaphore to be free (p) </li></ul></ul><ul><ul><li>signal that the semaphore is now free (v) </li></ul></ul>www.shareittips.com
  132. 132. Semaphore <ul><li>The semaphore has at least these possible states: </li></ul><ul><ul><li>Free, or available, or not in use </li></ul></ul><ul><ul><li>Not free, or unavailable, or in use </li></ul></ul><ul><li>Interpretation of the counter variable: </li></ul><ul><ul><li>If the counter is positive, then the semaphore is free. </li></ul></ul><ul><ul><li>If the counter is zero (or negative), then the semaphore is in use (not free). </li></ul></ul>www.shareittips.com
  133. 133. Semaphore <ul><li>Cases using a semaphore S </li></ul><ul><ul><li>If a process does a wait (p) on S, and if the semaphore is free, then S is decremented (S.counter = S.counter – 1;) </li></ul></ul><ul><ul><li>If a process does a wait (p) on S and if S is not free, then the process is blocked and put in S’s wait queue. </li></ul></ul><ul><ul><li>If a process does a signal (v) on S and if there is no process in the wait queue for S, then the semaphore is set to free by incrementing its counter (to positive). </li></ul></ul><ul><ul><li>If a signal (v) on S and there is a process in the S queue, then the process at the head of the queue is removed and unblocked (and can continue to execute) </li></ul></ul>www.shareittips.com
  134. 134. IOStreams <ul><li>Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk </li></ul><ul><li>Classes provided by package java.io </li></ul><ul><li>Data is transferred to devices by ‘streams‘ </li></ul>Program Device output - stream Program Device input - stream www.shareittips.com
  135. 135. keyboard monitor terminal console standard input stream standardoutput stream Streams How does information travel across? www.shareittips.com MEM CPU HDD
  136. 136. keyboard monitor terminal console standard input stream standardoutput stream file input stream LOAD READ file output stream SAVE WRITE Streams files How does information travel across? www.shareittips.com MEM CPU HDD
  137. 137. IOStreams <ul><li>JAVA distinguishes between 2 types of streams: </li></ul><ul><li>Text – streams, containing ‘characters‘ </li></ul><ul><li>Binary Streams, containing 8 – bit information </li></ul>I ‘ M A S T R I N G n Program Device 01101001 Program Device 11101101 00000000 www.shareittips.com
  138. 138. IOStreams <ul><li>Streams in JAVA are Objects, having </li></ul><ul><ul><li>2 types of streams (text / binary) and </li></ul></ul><ul><ul><li>2 directions (input / output) </li></ul></ul><ul><li>Results in 4 base-classes dealing with I/O: </li></ul><ul><ul><li>Reader: text-input </li></ul></ul><ul><ul><li>Writer: text-output </li></ul></ul><ul><ul><li>InputStream: byte-input </li></ul></ul><ul><ul><li>OutputStream: byte-output </li></ul></ul>www.shareittips.com
  139. 139. www.shareittips.com
  140. 140. Binary vs. TextFiles www.shareittips.com pro con Binary (input &output stream) Efficient in terms of time and space Preinformation about data needed to understand content Text(reader and writer) Human readable, contains redundant information Not efficient
  141. 141. Binary vs. TextFiles <ul><li>When use Text- / BinaryFiles ? </li></ul><ul><li>ALWAYS use TextFiles for final results </li></ul><ul><li>Binary Files might be used for non-final interchange between programs </li></ul><ul><li>Binary Files are always used for large amount of data (images, videos etc.) </li></ul>www.shareittips.com
  142. 142. Serialization <ul><li>Serialization: process of saving objects to a stream i.e. in-memory object to a byte stream. </li></ul><ul><ul><li>Each object is assigned a serial number on the stream </li></ul></ul><ul><ul><li>If the same object is saved twice, only serial number is written out the second time </li></ul></ul><ul><ul><li>When reading, duplicate serial numbers are restored as references to the same object </li></ul></ul><ul><li>The objects must be read from the stream in the same order in which they were written. </li></ul>www.shareittips.com
  143. 143. Serialization <ul><li>Why isn’t everything serializable? </li></ul><ul><ul><li>Security reasons – may not want contents of objects printed out to disk, then anyone can print out internal structure and analyze it </li></ul></ul><ul><ul><li>Could also have temporary variables that are useless once the program is done running. </li></ul></ul>www.shareittips.com
  144. 144. Serialization basics <ul><li>The requirements for serialization are straightforward: </li></ul><ul><ul><li>Only class instances rather than primitive types can be serialized. </li></ul></ul><ul><ul><li>For an object to be serializable, its class or some ancestor must implement the empty Serializable interface. </li></ul></ul><ul><ul><li>An empty interface is called a marker interface . </li></ul></ul><ul><li>The syntax for serialization is straightforward: </li></ul><ul><ul><li>An object is serialized by writing it to an ObjectOutputStream . </li></ul></ul><ul><ul><li>An object is deserialized by reading it from an ObjectInputStream . </li></ul></ul>www.shareittips.com
  145. 145. Serialization code <ul><li>=> Writing objects to a file </li></ul><ul><li>FileOutputStream out = </li></ul><ul><li>new FileOutputStream( “save.txt” ); </li></ul><ul><li>ObjectOutputStream oos = </li></ul><ul><li>new ObjectOutputStream( out ); </li></ul><ul><li>oos.writeObject( new Date() ); </li></ul><ul><li>oos.close(); </li></ul>www.shareittips.com
  146. 146. Deserialization code <ul><li>=> Reading objects from a file </li></ul><ul><li>FileInputStream in = </li></ul><ul><li>new FileInputStream( “save.txt” ); </li></ul><ul><li>ObjectInputStream ois = </li></ul><ul><li>new ObjectInputStream( in ); </li></ul><ul><li>myObject d = ( myObject_type ) ois.readObject(); </li></ul><ul><li>ois.close(); </li></ul>www.shareittips.com
  147. 147. Conditions for serializability <ul><li>If an object is to be serialized: </li></ul><ul><ul><li>The class must be declared as public </li></ul></ul><ul><ul><li>The class must implement Serializable </li></ul></ul><ul><ul><li>The class must have a no-argument constructor </li></ul></ul><ul><ul><li>All fields of the class must be serializable: either primitive types or serializable objects </li></ul></ul><ul><li>The Serializable interface does not define any methods! </li></ul><ul><ul><li>Question: What possible use is there for an interface that does not declare any methods? </li></ul></ul><ul><ul><li>Answer: Serializable is used as flag to tell Java it needs to do extra work with this class </li></ul></ul>www.shareittips.com
  148. 148. Object Serialization (cont’d) <ul><li>writeObject() will throw an Error if the object passed to it is not Serializable. </li></ul><ul><li>You can control serialization by implementing the Externalizable interface. </li></ul><ul><li>readObject() returns something of type Object, so it needs to be cast. </li></ul>www.shareittips.com
  149. 149. Serialization and primitive types <ul><li>Technically, primitive types cannot be serialized or deserialized. However, the ObjectOutputStream implements the DataOutput interface, which declares methods such as writeInt to write primitive types to streams. </li></ul><ul><li>ObjectInputStream implements DataInput for reading primitive types </li></ul>www.shareittips.com
  150. 150. transient and static fields <ul><li>A field marked as transient is not impacted by serialization. </li></ul><ul><ul><li>During deserialization, transient fields are restored to their default values (e.g., transient numeric fields are restored to zero). </li></ul></ul><ul><li>static fields are not impacted by serialization. </li></ul>www.shareittips.com
  151. 151. JDBC <ul><li>Java DataBase Connectivity </li></ul><ul><li>The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. </li></ul><ul><li>JDBC provides RDBMS access by allowing you to embed SQL inside Java code </li></ul>www.shareittips.com
  152. 152. JDBC Architecture <ul><li>Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change database engines without changing database code. </li></ul><ul><li>import the java.sql package. </li></ul>www.shareittips.com
  153. 153. Steps in JDBC <ul><li>To register the Driver: </li></ul><ul><ul><li>Class.forName(&quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;); </li></ul></ul><ul><li>To Get the connecttion: </li></ul><ul><ul><li>Connection con = DriverManager. getConnection(&quot;jdbc:odbc:Deepi&quot;,&quot;sa&quot;,&quot;pass@123&quot;); </li></ul></ul><ul><li>To create a SQL statement: </li></ul><ul><ul><li>Statement st=con.createStatement(); </li></ul></ul><ul><li>To execute it: </li></ul><ul><ul><li>st. execute (“DDL Query”); </li></ul></ul><ul><ul><li>st. executeUpdate (“DML Query”); </li></ul></ul><ul><ul><li>st. executeQuery (“select query”); </li></ul></ul>www.shareittips.com
  154. 154. Garbage Collector (GC) <ul><li>Provides automated memory management. </li></ul><ul><li>Deletes the unused objects in the memory. </li></ul><ul><li>Only the JVM decides when to run the GC, you can only suggest it. </li></ul><ul><li>An object becomes eligible for Garbage Collection when its last live reference disappears. </li></ul>www.shareittips.com
  155. 155. Garbage collection and Performance <ul><li>How Memory is allocated: </li></ul><ul><ul><li>Object creation Object is constructed either on a memory heap or on a stack. </li></ul></ul><ul><ul><li>Memory heap When new keyword is called memory is allocated in the heap and returned when the reference is made null </li></ul></ul><ul><ul><li>Stack During method calls, objects are created for method arguments and method variables. These objects are created on stack. Such objects are eligible for garbage-collection when they go out of scope. </li></ul></ul>www.shareittips.com
  156. 156. Garbage Collection <ul><li>Advantages of Garbage Collection : </li></ul><ul><ul><li>More productivity </li></ul></ul><ul><ul><li>Program Integrity </li></ul></ul><ul><li>Disadvantages of Garbage Collection : </li></ul><ul><ul><li>program performance </li></ul></ul>www.shareittips.com
  157. 157. Finalize() method <ul><li>Finalize() </li></ul><ul><ul><li>Class Object has a finalize() method. </li></ul></ul><ul><ul><li>Before gc happens the finalize() method is called </li></ul></ul><ul><ul><li>It is called only once </li></ul></ul><ul><ul><li>Finalize method can be overridden by the user. </li></ul></ul><ul><ul><li>Finalize can be used to make an object not to be garbage collected </li></ul></ul>www.shareittips.com
  158. 158. Classical Algorithms <ul><li>Three classical algorithms </li></ul><ul><ul><li>Mark-sweep </li></ul></ul><ul><ul><li>Reference counting </li></ul></ul><ul><ul><li>Semispace </li></ul></ul><ul><li>Tweaks </li></ul><ul><ul><li>Generational garbage collection (JAVA DEFAULT) </li></ul></ul><ul><li>Out of scope </li></ul><ul><ul><li>Parallel –perform GC in parallel </li></ul></ul><ul><ul><li>Concurrent –run GC at same time as app </li></ul></ul><ul><ul><li>Real-time–ensure bounded pause times </li></ul></ul>www.shareittips.com
  159. 159. Mark-Sweep <ul><li>Start with roots </li></ul><ul><ul><li>Global variables, variables on stack& in registers </li></ul></ul><ul><li>Recursively visit every object through pointers </li></ul><ul><ul><li>Markevery object we find (set mark bit) </li></ul></ul><ul><li>Everything not marked = garbage </li></ul><ul><ul><li>Can then sweep heap for unmarked objectsand free them </li></ul></ul>www.shareittips.com
  160. 160. Annotations <ul><li>Annotations in Java is all about adding meta-data facility to the Java Elements like </li></ul><ul><ul><li>package declarations, </li></ul></ul><ul><ul><li>class, </li></ul></ul><ul><ul><li>constructors, </li></ul></ul><ul><ul><li>methods, </li></ul></ul><ul><ul><li>fields, </li></ul></ul><ul><ul><li>variables and etc </li></ul></ul><ul><li>An annotation indicates that the declared element should be processed in some special way by a compiler, development tool, deployment tool, or during runtime. </li></ul><ul><li>Annotations are defined using an @ syntax </li></ul>www.shareittips.com
  161. 161. Structure of Java5 Compiler class C { @NonNull Object field; C( @NonNull Object p) { field = p; } @NonNull Object get() { return field; } } Annotation Checker Plugins Error Error Source File Program with annotations Class File www.shareittips.com Parser Annotation Checker Class File Writer Type Checker
  162. 162. Annotation Types <ul><li>Marker </li></ul><ul><li>Single-Element </li></ul><ul><li>Full-value or multi-value </li></ul>www.shareittips.com
  163. 163. Marker <ul><li>Marker annotations take no parameters. They are used to mark a Java element to be processed in a particular way. </li></ul><ul><li>Example: </li></ul><ul><li> public @interface MyAnnotation { </li></ul><ul><li> } </li></ul><ul><li>Usage: </li></ul><ul><ul><li>@MyAnnotation </li></ul></ul><ul><ul><li>public void mymethod() { </li></ul></ul><ul><ul><li>.... </li></ul></ul><ul><ul><li>} </li></ul></ul>www.shareittips.com
  164. 164. Single-Element <ul><li>Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis. </li></ul><ul><li>Example: </li></ul><ul><ul><ul><li>public @interface MyAnnotation { </li></ul></ul></ul><ul><ul><ul><li>String doSomething(); </li></ul></ul></ul><ul><ul><ul><li> } </li></ul></ul></ul><ul><li>Usage: </li></ul><ul><ul><ul><li>@MyAnnotation (&quot;What to do&quot;) </li></ul></ul></ul><ul><ul><ul><li> public void mymethod() { </li></ul></ul></ul><ul><ul><ul><li>.... </li></ul></ul></ul><ul><ul><ul><li> } </li></ul></ul></ul>www.shareittips.com
  165. 165. Full-value or multi-value <ul><li>Full-value type annotations have multiple data members. </li></ul><ul><li>Example: </li></ul><ul><ul><li>public @interface MyAnnotation { </li></ul></ul><ul><ul><li>String doSomething(); </li></ul></ul><ul><ul><li> int count; </li></ul></ul><ul><ul><li> String date(); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>Usage: </li></ul><ul><li>@MyAnnotation (doSomething= </li></ul><ul><li>&quot;What to do&quot;, </li></ul><ul><li> count=1, </li></ul><ul><li>date=&quot;09-09-2005&quot;) </li></ul><ul><li> public void mymethod() { </li></ul><ul><li>.... </li></ul><ul><li> } </li></ul>www.shareittips.com
  166. 166. The Built-In Annotations <ul><li>Java defines seven built-in annotations. </li></ul><ul><li>Four are imported from java.lang.annotation </li></ul><ul><ul><ul><li>@Retention, </li></ul></ul></ul><ul><ul><ul><li>@Documented, </li></ul></ul></ul><ul><ul><ul><li>@Target, </li></ul></ul></ul><ul><ul><ul><li>and @Inherited. </li></ul></ul></ul><ul><li>Three are included in java.lang. </li></ul><ul><ul><li>@Override, </li></ul></ul><ul><ul><li>@Deprecated, </li></ul></ul><ul><ul><li>and @SuppressWarnings. </li></ul></ul>www.shareittips.com
  167. 167. The Target annotation <ul><li>@Target(ElementType.TYPE) </li></ul><ul><ul><li>can be applied to any element of a class </li></ul></ul><ul><li>@Target(ElementType.FIELD) </li></ul><ul><ul><li>can be applied to a field or property </li></ul></ul><ul><li>@Target(ElementType.METHOD) </li></ul><ul><ul><li>can be applied to a method level annotation </li></ul></ul><ul><li>@Target(ElementType.PARAMETER) </li></ul><ul><ul><li>can be applied to the parameters of a method </li></ul></ul><ul><li>@Target(ElementType.CONSTRUCTOR) </li></ul><ul><ul><li>can be applied to constructors </li></ul></ul><ul><li>@Target(ElementType.LOCAL_VARIABLE) </li></ul><ul><ul><li>can be applied to local variables </li></ul></ul><ul><li>@Target(ElementType.ANNOTATION_TYPE) </li></ul><ul><ul><li>indicates that the declared type itself is a </li></ul></ul>www.shareittips.com
  168. 168. Reflection <ul><li>When we have some Annotations defined in the source code and have a mechanism through which we can say that to what extent the Annotations should be retained. The three possible ways of telling this are, </li></ul><ul><ul><li>Retain the Annotation in the Source Code only </li></ul></ul><ul><ul><li>Retain the Annotation in the Class file also. </li></ul></ul><ul><ul><li>Retain the Annotation Definition during the Run-time so that JVM can make use of it. </li></ul></ul><ul><li>The Annotation that is used to achieve this is @Retention and it takes a possible values of SOURCE, CLASS and RUNTIME defined in RetentionPolicy Enumeration. </li></ul>www.shareittips.com
  169. 169. Need of Annotation <ul><li>Less coding </li></ul><ul><li>Easier to change </li></ul><ul><li>Smarter development. </li></ul><ul><li>Providing information to the Compiler. </li></ul><ul><li>Providing information to the tools. </li></ul><ul><li>Providing information to the Runtime System </li></ul>www.shareittips.com
  170. 170. www.shareittips.com www.bcahub.shareittips.com www.shareittips.com

×