OOPS

‡ Object Oriented Programming Structure ‡ Features of OOPS 
Objects / Instance  Classes  Inheritance  Polymorphism
‡ Overloading / Static Polymorphism / Compiletime polymorphism ‡ Overriding / Dynamic polymorphism / Run-time polymorphism 

Encapsulation  Abstraction

OOPS
‡ Objects ± Real time entity ‡ Classes ± Blueprint of an object. It gives structure to the objects ‡ Inheritance ± Deriving base class properties and behaviour to the child class ‡ Polymorphism - One object in different forms ‡ Encapsulation - Hiding the irrelevant details to the irrelevant entity ‡ Abstraction ± Revealing the relevant details to the relevant entity.

History of Java
‡ The original name of Java was Oak, and it was developed as a part of the Green project at Sun Microsystems. ‡ Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridon at Sun Microsystems in 1991. ‡ Sun formally announced the Java SunWorld in 1995.

Features of JAVA ‡ Object Oriented Programming language ‡ Platform Independent ‡ Robust ‡ Portable ‡ Scalable ‡ Multithreaded ‡ Architecturally neutral ‡ Secured .

Java Virtual Machine .Components of Java ‡ JDK ± Java Development Kit ‡ JRE ± Java Run-time Environment ‡ JVM .

Java Virtual Machine The Java Virtual Machine provides a platformindependent way of executing code. JVM's main job is interpreting java byte code and translating this into actions or OS calls.  JVM is OS dependent which makes java source code as machine independent. . JVM forms part of large system JRE. by abstracting the differences between operating systems and CPU architectures. JVM is Write Once-Run Anywhere (WORA) software.

JRE and JVM .

Easier updates. ‡ Inheritance ± Reusability. Do not break what is already working. ‡ Polymorphism ± one method will behave differently.Classification ‡ Encapsulation . flexibility and extensibility.Purpose of Features of OOPS ‡ Classes .maintainability. .

‡ Import statements ‡ Class declaration { Variable declaration/ definition. } .Structure of JAVA Program ‡ Package declaration. method declaration / definition.

} } .Main method ‡ class <classname> { public static void main(String[] args) { // Object instantiation <classname> m = new <classname>().

CamelCase Convention ‡ Variables ‡ Method ‡ Class ‡ Package ‡ Constants myVariable myMethod() MyClass mypackage MYCONSTANT .

. ‡ Instance variables are initialized automatically.Types of Variable ‡ Local variable (variable inside method or block) ‡ Class Variable (Static Variable) ‡ Instance Variable ( variable inside the class) Note: ‡ Local variables require explicit initialization.

Variable Initialization Variable ‡ byte ‡ short ‡ int ‡ long ‡ float ‡ double ‡ char ‡ boolean ‡ All reference types Value 0 0 0 0L 0.0F 0.0D '\u0000' false null .

of object created . Method ‡ Purpose: To initialize the class members ‡ Features:  Same name as that of the class name  No return type including VOID  Can have access specifier  Can be overloaded  Constructors are NOT inherited  Invoked automatically whenever the object is created.  The no. of time of invocation depends on no.Constructor ‡ It is a Spl.

‡ You can use the same reference variable to refer to an entirely new array. ‡ Can be declared as a primitive type or Class type. it is created with new. ‡ Array index starts with 0. in a contiguous block of memory.Arrays ‡ Group data objects of the same type. . ‡ An array is an object. ‡ You cannot resize an array.

‡ Constructing an array <array name> = new <element type> [<array size>].Array Declaration and Instantiation ‡ Array declaration <element type>[] <array name>. myArray = new int[5]. int[] myArray. .

<element type>[] <array name> = { <array initialize list> }. 4 . 2 . null }. . Reference Array: ******************** Object[] objArr = { new Pizza().Initializing an Array ‡ Explicit initialization in one line. 5 } . 3 . new Pizza(). Primitive array: ***************** int[] myArray = { 1 .

Initializing an Array ‡ Explicit initialization can also be done using array subscripts. myArray [0] = 10. int[] myArray = new int[3]. myArray [2] = 30. . myArray [1] = 20.

Inheritance
‡ Deriving the parent class properties and methods to the child class. ‡ Types of inheritance: 
Single level inheritance - one super and one sub class  Multilevel inheritance - The sub class of one level forms the super class of another level  Multiple inheritance [ not supported by java]
- many super and one sub class 

Hierarchical inheritance
- one super and many sub classes 

Hybrid inheritance - multiple and multi level combined.

Inheritance
‡ Two important concepts 
Generalization - Up the hierarchy  Specialization - Down the hierarchy

‡ Purpose : Reusability (without changing its identity) ‡ Syntax: <modifier> class <name> extends <superclass> { <declaration>* }

IS-A & HAS-A relationship
‡ When you want to know if one thing should extend another, use the IS-A test. Eg : Triangle IS-A Shape ‡ Do not apply inheritance if the subclass and super class do not pass the IS-A test. ‡ Is-a relationship can be described in Java keyword extends. ‡ The IS-A relationship ± Unidirectional

IS-A & HAS-A relationship ‡ When two classes are related. ‡ Has-a relationship can be described in Java code as member fields. Note: ‡ Code reuse is also best achieved by aggregation when there is no is-a relationship . but not through inheritance. one class has a reference to another class) then you say that the two classes are joined by HAS-A relationship. (for example.

IS-A & HAS-A relationship ‡ class Car { } class BMW extends Car { boolean auto_gear = ³true´ => Has-A R/S } => IS-A R/S .

Same method name with same set of parameters.Polymorphism ‡ Polymorphism (from Greek.Same method name with different set of parameters.Late Binding . ‡ Types:  Overloading => Ad-Hoc Polymorphism .Early Binding  Overriding => True polymorphism . . . 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.

Types of Overloading ‡ Function Overloading ‡ Constructor Overloading ‡ NO operator Overloading in Java ‡ Rules :  No. . of parameter should change  Datatype of the parameter should change  Sequence of passing the paramter should change.

. but it can hide them. ‡ Super keyword is used to invoke an overridden method in the superclass. ‡ A subclass cannot override fields of the superclass. ‡ Works only with inheritance.e. ‡ Constructors cant be Overridden.  Overridden Methods Cannot Be Less Accessible. and the new method in the subclass must uphold the following rules of method overriding:  The new method definition must have the same method signature (i.Overriding ‡ The overridden method in the superclass is NOT inherited by the subclass. . method name and parameters) and the same return type.

‡ 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.this() and super() call for constructor ‡ this() construct is used to implement local chaining of constructors in the class when an instance of the class is created. . ‡ this() and super() call must occur as the first statement in a constructor. ‡ The this() call invokes the constructor with the corresponding parameter list.

} } .a=a.c=c. GParent() { System. } GParent(int a.int b) { //this(a.println("From gparent"). this.out. this().b=b. } GParent(int a.b.int b.Example : this() and super() class GParent { int a.out.int c) { this. System.b. this.c.out.println("a= "+a+" b = "+ b).println("a= "+a+" b = "+ b + " c= " +c).100). System.

y = y. this.println("From parent").y).y. this. System.println("x= "+x+" y = "+ y).x=x.int y) { super(x. } Parent(int x.Example : this() and super() class Parent extends GParent { int x.out. Parent() { System. } } .out.

23).out.Example : this() and super() class Child extends Parent { Child() { super(23. } } .343). } } class SuperEx { public static void main(String[] a) { //Parent p = new Parent(12. System.println("From child"). Child d = new Child().

} // rest of operation } .instanceof operator ‡ Use instanceof to test the type of an object. ‡ Restore full functionality of an object by casting. ‡ Example: public void doSomething(Employee e) { if ( e instanceof Manager ) { Manager m = (Manager) e.

and nested classes. . ‡ The static keyword declares the attribute or method is associated with the class as a whole rather than any particular instance of that class. ‡ Thus static members are often called class members. methods. such as class attributes or class methods.Static Keyword ‡ It¶s a Access Modifier ‡ The static keyword is used as a modifier on variables.

.Static Keyword ‡ A static method can access only the static variable. ‡ Static members are subjected to change common for all the instance. But the normal variable can access both static and normal variable. ‡ Static members will get loaded into the memory only once. ‡ NO NEED FOR OBJECT to access the static member.

} public static void main(String arg[]) { StatEx s1 = new StatEx().Static Variable Example class StatEx { int i=10. StatEx s2 = new StatEx().normalMethod(). s2. static int j = 20.out. public void normalMethod() { System.println("Static var = " + j++).out. s1. } } .normalMethod().println("Instance var = " + i++). System.

public static void staticMethod() { //System. } public static void main(String arg[]) { staticMethod(). staticMethod().out. static int j = 20.Static Method Example class StatEx { int i=10.out.println("Static var = " + j++). } } . //illegal System.println("Instance var = " + i++).

out. } public static void sMethod() { System.Static Initializer Example class StatEx1 { static int counter. //static initializer static { counter=10. System. } } .out.println("Static method" + counter++).println("Static block invoked "+counter).

sMethod(). StatEx1. } } .sMethod().out. StatEx1.Static Initializer Example class StatEx { public static void main(String arg[]) { System.println("from main").

Final Keyword ‡ Variable become Constant ‡ Method cant be Overridden ‡ Class cant be inherited ‡ Note:  All final variable need Explicit initialization .

‡ Wrapper class are present in java. ‡ Allow objects to be created from primitive types. . you need to create another object. To wrap another value.Wrapper Class ‡ Conversion of primitive types to the object equivalent done through wrapper classes. ‡ Wrapped values are immutable (Cant modify) .lang package ‡ All the wrapper classes are declared final.

.Primitive Data Types and Corresponding Wrapper Classes Primitive Data Type Wrapper Class Constructor Arguments boolean byte char short int long float double Boolean Byte Character Short Integer Long Float Double boolean or String byte or String char short or String int or String long or String double or float or String double or String 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.

Boxing and Unboxing ‡ Converting a value type to a reference type is known as Boxing. Integer n = new Integer(x). int y = n. //Boxing //UnBoxing .intValue(). int x=10. ‡ Converting a reference type to a value type is known as UnBoxing.

AutoBoxing and AutoUnboxing Example: int x=10. //AutoBoxing //AutoUnBoxing . int y = n. Integer n = x.

Double . Short. Long. Short. Short.Methods to Extract the Wrapped Values Method public boolean booleanValue() public char charValue() public byte byteValue() public short shortValue() public int intValue() public long longValue() public float floatValue() public double doubleValue() Class Boolean Character Byte. Long. Float. Double Byte. Short. Long. Short. Integer. Float. Integer. Short. Long. Float. Double Byte. Integer. Integer. Double Byte. Double Byte. Integer. Double Byte. Long. Integer. Float. Long. Float. Float.

or String and radix String.) static int parseInt(«) static long parseLong(«) static float parseFloat(«) static double parseDouble(«) String. or String and radix String.Methods to Convert Strings to Primitive Types Wrapper Class Boolean Character Byte Short Integer Long Float Double Method Signature static boolean parseBoolean(«) Not available static byte parseByte(«) static short parseShort(.. or String and radix String double or String Method Arguments String . or String and radix String.

Wrapper Conversion methods ‡ Primitive xxxValue()  To convert Wrapper to primitive ‡ Primitive parseXxx(String)  To convert a String to a primitive ‡ Wrapper valueOf(String)  To convert a String to a Wrapper .

lang package.Object Class ‡ Root class of Java => Object ‡ equals() method = > Check only values ‡ toString() method =>Check value & reference ‡ hashCode() => return the address of the object ‡ Object Class is in java. .

‡ NEED RELATIONSHIP between classes . ‡ Use abstract keyword to declare a class as abstract. ‡ Can have normal method and variable ‡ Cant be instantiated ‡ Methods may or may not be implemented by the child class. ‡ Abstract method cannot be private or final ‡ A class can inherit only one abstract class.Abstract Class ‡ Class which have a abstract method (method without definition) is abstract class.

‡ All the methods should be implemented by the child class.NO Variables. ‡ Interface contain only constants.Interface ‡ Interface is to support multiple inheritance in Java. ‡ Interfaces cant be instantiated ‡ A class can implement many interfaces. ‡ Interfaces should be implemented by the child class ‡ Can have only abstract method. ‡ NO NEED FOR RELATIONSHIP . ‡ All the fields are public static final in nature.

enum
‡ Assigning a integral constant to a symbolic name => enum ‡ Use enum when you want a variable to hold only a predetermined set of values. ‡ You use the keyword enum and not class to declare an enum. ‡ Just like a class, an enum can have constructors, methods, and fields. ‡ An enum cannot be declared within a method. ‡ You cannot instantiate an enum with the new operator.

enum
‡ The enums do not participate in class hierarchy: they cannot extend and they cannot be extended. ‡ You cannot directly call an enum constructor. ‡ An enum may have a main() method and therefore can be executed by name from the command line like an application.

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

println(i).TOP. System.LEFT.ordinal(). System. } } .println(e).BOTTOM.out. public static void main(String[] a) { Edge e = Edge. int i = e.Enum Example2 enum Edge { TOP.RIGHT.out.

SUNDAY(0.false). private int hours. SATURDAY(4. WEDNESDAY(8.true). .Enum Example3 public enum Day { MONDAY(8.true).false). TUESDAY(8. private boolean weekday.true).true). THURSDAY(8.true). FRIDAY(8.

} .Enum Example3 Day(int whours. wday=weekday. } public boolean isWeekDay() { return weekday. } public int getHours() { return hours.boolean wday) { hours=whours.

getHours() +" hours working hours").println(d +" is a not weekday and has "+ d.println(d +" is a weekday and has "+ d. } } .isWeekDay()) { System.out.getHours() +" hours working hours").Enum Example3 public static void showDay(Day d) { if(d. } else { System.out.

} } . day = Day.SUNDAY. showDay(day).Enum Example3 public static void main(String[] ar) { Day day.

‡ There are four categories of nested classes  Regular class .Inner Class ‡ A class that is declared within another class or interface.inner classes marked with the static modifier (top-level nested class)  Anonymous class .part of a method argument.class within the class  Method-local class ± class within the method of the outer class  Static nested class . but not all nested classes are inner classes. is called a nested class. ‡ All inner classes are nested classes. .

} } public void OuterMethod() { MyInner inn = new MyInner().out.println("x == " + x).Example for Regular InnerClass class MyOuter { int x =7.InnerMethod(). class MyInner { public void InnerMethod() { System. inn. } .

mo. //mi.MyInner mi = mo.InnerMethod().OuterMethod(). illegal //mo.OuterMethod().InnerMethod().Example for Regular InnerClass public static void main(String[] a) { MyOuter mo = new MyOuter(). mi. illegal } } . MyOuter.new MyInner().

Method-local inner class ‡ A method-local inner class can be instantiated only within the method where the inner class is defined. ‡ CANT access the variable inside the method in which the inner class is created except a final variable. ‡ method-local inner class can't use any access specifiers. . ‡ Can access the outer class level variable. ‡ Method-local inner class can be declared abstract and final.

Method-local inner class
class MouterClass { int x =10; public void OuterMethod() { final int j=90; class MinnerClass { public void minnerMethod() { System.out.println("Hello ..." + x + j); } } MinnerClass mic = new MinnerClass(); mic.minnerMethod(); } public static void main(String[] a) { MouterClass moc = new MouterClass(); moc.OuterMethod(); } }

Static nested class
‡ Static nested classes are inner classes marked with the static modifier. ‡ A static nested class is not an inner class, it's a top-level nested class. ‡ A static nested class cannot access non-static members of the outer class.

Static nested class
class OuterClass { static int i =10; public void method() { System.out.println("i == " + ++i); } static class InnerClass { public void display() { System.out.println("i == " + i); } }

ic.display().InnerClass().method(). OuterClass oc = new OuterClass(). oc. } } .Static nested class public static void main(String[] a) { OuterClass.InnerClass ic = new OuterClass.

Anonymous Inner Classes ‡ Anonymous inner classes have no name. ‡ Anonymous inner classes cannot have constructor. .

blue). f. public FrameExample() { f = new Frame("Hello .awt. f. } public void launchFrame() { f.. .setVisible(true).. import java.setSize(170.!").setBackground(Color..170).Anonymous Inner Classes import java.. class FrameExample { private Frame f.*.event.awt.*.

exit(0).Anonymous Inner Classes // Add a window listener f. } }). //Anonymous Inner Classes } public static void main(String args[]) { FrameExample f = new FrameExample().launchFrame().addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent evt) { System. } } . f.

‡ Error Types:  happens due to problems originating from the execution environment.Exception Handling ‡ An exception in Java is a signal that indicates the occurrence of some important or unexpected condition during execution. (Error Class)  happens due to problems originating inside the application itself. (Exception Class) ‡ Exception Should be Handled or Thrown to the exception handler. .

‡ Types:  Checked Exception  Unchecked Exception . on the other hand.Exceptions ‡ Errors (represented by subclasses of Error) occur in the Java virtual machine (JVM) and not in the application itself. ‡ The exceptions (represented by subclasses of Exception). generally originate from within the application.

The compiler checks that such code exists.Checked Exception ‡ Checked exceptions are generally related to how the program interacts with its environment. ‡ The programmer is required to write code to deal with checked exceptions. ‡ 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. ‡ It MUST be thrown programmatically or Handled. .

.Unchecked Exception ‡ Occur due to program bugs. ‡ Runtime exceptions are not checked by the compiler. ‡ Runtime exceptions and errors combined are also called unchecked exceptions and they are mostly thrown by the JVM. ‡ Write the correct code to avoid the runtime exceptions than write the code to catch them but it is not illegal to catch them.

The Exception Class Hierarchy Object Throwable Exception Error Others« RuntimeException Others« Others« .

catch ± throw .cleanup your code goes here } } .Exception handler block code throw Exception_Instance //Ducking it } finally{ -.throws ± finally Method throws ExceptionName{ try{ --risky code goes here }catch(ExceptionClassName ObjectName){ -.Exception-handling mechanism ‡ Contains five keywords:  try .

‡ You may also write an optional ³finally´ block. ‡ Can have one or more catch block. either after the ³try´ block code.About try-catch-finally ‡ A try block should be followed by at least one catch block. This block contains code that is ALWAYS executed. make sure that the last catch block contain the super most class in the hierarchy. or after the ³catch´ block code. ‡ The code inside try block is called as protected code. . ‡ If you have multiple catch block. ‡ The catch block may or may not contain throw keyword. ‡ The try block can also be nested.

} } } . } catch(ArithmeticException obj) { System. obj.printStackTrace().println("Exception"+obj).Example 1 class PrintStack { public static void main(String args[]) { int Num1= 30 .out. try { int Num3=Num1/Num2. Num2 = 0.

‡ You do not need to declare runtime exceptions or errors.Rules in Exception ‡ The Declare or Handle Rule  Handle the exception by using the try-catch-finally block. . ‡ Declare that the code causes an exception by using the throws clause. ‡ You can choose to handle runtime exceptions.

and thus avoid handling the exception yourself  Example ‡ public void myMethod throws IOException { « normal code with some I/O } . you may declare the method as ³throws´ that exception.Passing the exception  In any method that might throw an exception.

} } .out.show(). } public static void main(String[] arg) { new UncheckedThrows().Throws clause class UncheckedThrows { public void show() throws ArithmeticException { System.println("Hai I am not handled").

 Super classes of the exceptions thrown by the overridden method .Method Overriding and Exceptions The overriding method can throw:  No exceptions  One or more of the exceptions thrown by the overridden method.  The overriding method cannot throw:  Additional exceptions not thrown by the overridden method.  One or more subclasses of the exceptions thrown by the overridden method.

User Defined Exception ‡ Create User-Defined Exception as a Class that EXTENDS Exception Class. ‡ Instantiate the created Exception and use it in the catch block as a handler. .

io. class MyException extends Exception { MyException() { System.*.out.Example 2 import java. } public String toString() { return "MyException thrown".println("UserDefined Error occured"). } } .

readLine(). System. str2=br.str2.out.in)).println("Hai welcome"). str1=br.println("Enter Login id"). } .Example 2 cont class UserExceptions { public void valid() { try { String str1. if(str1.println("Enter password").out.readLine().out. BufferedReader br=new BufferedReader(new InputStreamReader(System. else throw new MyException(). System.equals(str2)) System.

println("Sorry U r not a valid user" + e).out.Example 2 cont catch(MyException e) { System. e1. } } .valid(). } catch(IOException ioe){} } public static void main(String[] arg) throws IOException { UserExceptions e1=new UserExceptions(). valid().

.String Class Facts ‡ An object of the String class represents a string of characters. + and += (used for concatenation). ‡ Like other classes. ‡ String class is declare final . String has constructors and methods.lang package. which does not require an import statement. ‡ Unlike other classes. String has two operators. therefore immutable. ‡ The String class belongs to the java.

‡ have methods you can call.Literal Strings ‡ are anonymous objects of the String class ‡ are defined by enclosing text in double quotes. ‡ can be passed to methods and constructors as parameters. ³This is a literal String´ ‡ don¶t have to be constructed. . ‡ can be assigned to String variables.

//calling a method on a literal String char Initial = ³Priya´.Literal String Example //assign a literal to a String variable String name = ³Priya´.charAt(0).charAt(0). . //calling a method on a String variable char Initial = name.

.Immutability ‡ Once created. ‡ Such objects are called immutable. ‡ 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. a string cannot be changed: none of its methods changes the string.

Advantages Of Immutability ‡ Uses less memory String word1 = "Java". String word2 = word1. word1 word1 ³Java" ³Java" ³Java" word2 word2 OK Less efficient: wastes memory . String word2 = new String(word1). String word1 = ³Java".

Disadvantages of Immutability ‡ Less efficient ² you need to create a new string and throw away the old one even for small changes. word ³java" ³Java" . String word = ³Java´. word = ch + word. char ch = Character.toUpperCase(word.charAt (0)).substring (1).

private String errorMsg. Empty strings ‡ Not the same as an uninitialized String. String word1 = "". It¶s length is 0. errorMsg is null .Empty Strings ‡ An empty String has no characters. String word2 = new String().

Copy Constructors ‡ Copy constructor creates a copy of an existing String. word1 word2 ³Java" . ‡ Not the same as an assignment. String word2 = word. String word1 = new String(³Java´). Also rarely used. String word2 = new String(word). Copy Constructor: Each variable points to a different copy of the String. word1 word2 ³Java" ³Java" Assignment: Both variables point to the same String. String word1 = ³Java´.

//´Java´ ‡ String index starts with 0 like arrays. char[] letters = {µJ¶. . µa¶}. µa¶. String word = new String(letters). µv¶.Other Constructors ‡ Most other constructors take an array as a parameter to create a String.

‡ int length().substring (2.5).substring (2). => Returns the number of characters in the string. ‡ String substring() => Returns a substring object ‡ substring(i. television television i k i . ³television".Methods in String Class ‡ char charAt(i) => Returns the char at position i.k) substring(i) ³television".

Methods in String Clas ‡ indexOf() => returns the index position of the character. ‡ equals() ‡ equalsIgnoreCase() ‡ compareTo() ‡ compareToIgnoreCase() ‡ trim() ‡ replace() ‡ toUpperCase() ‡ toLowerCase() .

StringBuffer Class ‡ String Buffers are mutable strings. ‡ StringBuffer is a final class. ‡ Can grow dynamically in size without bounds. An empty StringBuffer is created with 16-character capacity. from a string or with a capacity. . ‡ They can be created empty.

Methods in String Buffer ‡ length() ‡ capacity() ‡ ensureCapacity() ‡ setLength() ‡ charAt() ‡ Append() ‡ setCharAt() ‡ Insert() ‡ deleteCharAt() ‡ replace() ‡ reverse() .

‡ StringBuilder methods should run faster than StringBuffer methods. .StringBuilder Class ‡ Same like StringBuffer Class ‡ StringBuilder¶s methods are not synchronized.

 Interfaces  Classes  Algorithms => Collection => Collections . ‡ Provided in the java.Collections ‡ A collection allows a group of objects to be treated as a single unit. ‡ The collections framework comprises three main parts. retrieved. ‡ Arbitrary objects can be stored. and manipulated as elements of collections.util package.

The Collections Interfaces The root of the hierarchy of the collections interfaces is the Collection interface. Both a Map object and a Set collection cannot contain duplicates data items. which are represented by the super interface Map. while a List collection can contain duplicates. .  There is another kind of collections called maps.

Map) .util.util. values of which must be unique. (java.util.Set)  A map supports searching on a key field. (java.The Collections Interfaces  A collection has no special order and does not reject duplicates.Collection)  A list is ordered and accept duplicates. (java.  A set has no special order but rejects duplicates. (java.util.List).

‡ HashSet and LinkedHashSet are examples of classes that implement the Set interface. and Vector are the classes that implement the List interface.Collection Classes ‡ ArrayList. . LinkedList. ‡ HashMap and HashTable are examples of classes that implement the Map interface.

.

} } .0F)).add(new Float(5. list.out. list. // duplicate. is added list.add("second").add("one"). // duplicate. is added System. list.add("second").println(list).List import java.add(new Integer(4)).*. class ListExample { public static void main(String[] args) { List list = new ArrayList().add("3rd"). list. list. list.add(new Integer(4)).util.

add("3rd"). class SetExample { public static void main(String[] args) { Set set = new HashSet(). } } . // duplicate. not added set.add(new Float(5. set. not added System.add("one").out.0F)).add(new Integer(4)). set.add("second"). // duplicate.*.util. set. set.println(set).add("second"). set.Set import java. set.add(new Integer(4)).

but searching is faster. Indexed access is slow. But not insertion and deletion. but the Collections API implements the four methods that are most widely used:  Array: supports insertion. . hashing requires the use of unique keys for storing data elements. but growing the store is more difficult.  Tree: supports insertion. deletion. and growing the list. However.  Hash table: supports insertion. Vector(provides synchronization)  Linked list: supports insertion. Use when insertions and deletions happen frequently. deletion. deletion. but searching is particularly fast. Indexed access is slow.  ArrayList: grow in number of elements. Search is faster. and growing the store.Collection API .Storage ‡ The storage associated with any one collection can be implemented in many ways. and growing the store. but makes indexed access slower. deletion.

Set Classes ‡ HashSet :  provides the faster access to a data item.  performance is not as good as HashSet. ordered by insertion.  no guarantee that the items will be ordered. but not sorted. ‡ Tree Set:  presents sorted data items.  does not offer synchronization .  It is an ordered collection.  does not offer synchronization. ‡ LinkedHashSet:  Similar to HashSet that maintains a doubly linked list.  does not offer synchronization.

 implementation is synchronized ‡ HashMap:  based on the hashtable data structure. ‡ TreeMap:  implements the SortedMap interface  Sorted and unsynchronized. .  No ordering  allows null and is unsynchronized ‡ LinkedHashMap:  maintains a doubly linked list.  No ordering.Map Classes ‡ HashTable:  implementation is based on the hashtable data structure.

Class Interface Duplicates Allowed? Ordered/ Sorted Synchronized ArrayList LinkedList Vector HashSet LinkedHashSet List List List Set Set Yes Yes Yes No No Ordered by index Not sorted Ordered by index Not sorted Ordered by index Not sorted Not ordered Not sorted Ordered by insertion Not sorted No No Yes No No TreeSet Set No Sorted either by No natural order or by your comparison rules .

Class Interface Duplicates Allowed? Ordered/ Sorted Synchronized HashMap Map No No No No Not ordered Not sorted Ordered Not ordered Not sorted No No Yes LinkedHashMap Map Hashtable TreeMap Map Map Sorted either by No natural order or by your comparison rules .

.Collection Advantages and Disadvantages ‡ Advantages  Can hold different types of objects.  Resizable ‡ Disadvantages  Must cast to correct type  Cannot do compile-time type checking.

.Generics ‡ For checking the type of object during the compilation time. ‡ Enclose the type within angular brackets <>.

and yet you can keep your code completely independent of the locale conventions for months.text.Date Class ‡ The java. ‡ You create a locale object by using the Locale class . days of the months. and so on. days of the week.DateFormat class provides several methods for formatting the date/time for a default or a specific location.

program counter (pointer to the current instruction being executed). ‡ A thread is a path of code execution through a program. and each thread has its own local variables. Every process has at least one thread running within it.Process and Thread ‡ A process is a program that is currently executing. and lifetime. ‡ Threads are referred to as lightweight processes. .

Threads ‡ A thread is not an object ‡ A thread is a flow of control ‡ A thread is a series of executed statements ‡ A thread is a nested sequence of method calls .

. ‡ Multithreading is a mechanism of running various lightweight processes under single process within its own space ‡ Multiprocessing there will be more than one processor and each thread will be handled by a different processor.MultiThreading and MultiTasking ‡ 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.

called the main thread. . ‡ Even a non-multithreaded program has one thread of execution. it calls the run() method to make our thread to perform useful work. ‡ When a thread is started. ‡ Call the start() method to start the thread.Creation of a Thread ‡ By extending Thread class ‡ By implementing Runnable interface.

1st Method: Extending the Thread class class MyThread extends Thread { public void run() { // thread body of execution } } ‡ Creating thread: MyThread thr1 = new MyThread(). . ‡ Start Execution: thr1.start().

2nd method: Threads by implementing Runnable interface class ClassName implements Runnable{ public void run() { // thread body of execution } } ‡ Creating Object: ClassName myObject = new ClassName(). ‡ Start Execution: thr1.start(). . ‡ Creating Thread Object: Thread thr1 = new Thread( myObject ).

Thread scheduling ‡ Thread scheduling is implementation dependent and cannot be relied on to act in the same way on every JVM ‡ The two approaches to scheduling are  Preemptive . .will be applied for thread with highest and lowest priority  Time-Sliced (Round-Robin) Scheduling ± will be applied when more than one thread has the same priority.

 Independent executables .Threads within a process THREAD STACK SHARED MEMORY THREAD DATA THREAD TEXT  All threads are parts of a process hence communication easier and simpler.

Suspended Voluntarily allowed other threads to run 5.Blocked Waiting for some resource or event to occur .Running Currently running In control of CPU 2.Ready to run Can run but not yet given the chance 3.Thread States A thread can in one of several possible states: 1.Resumed Ready to run after being suspended or block 4.

comes in while first thread is running .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.

Thread Synchronization ‡ Done in two ways  To method public synchronized void method() { }  To block synchronized(this) { } .

‡ Should be used along with the synchronized block .Wait() and notify() ‡ Wait() and notify should be used to restrict the thread before doing an operation without a notification from the other thread.

‡ It also gives up it¶s lock on the object when wait is called.wait() ‡ When a thread enters a wait state. « // do something } . it does nothing until it is notified by another thread. public synchronized blah() { wait().

a different thread which has a lock on the same object must call notify. ‡ In general. use notifyAll() . ‡ When notify is called. and thus guaranteed to be awakened.notify() and notifyAll(). ‡ There are two versions .  When multiple threads are waiting on the same condition. the block that had the lock on the object continues to have it¶s lock it releases it. ‡ Notify is safe only under 2 conditions:  When only 1 thread is waiting.notify() ‡ To awaken a thread. and it doesn¶t matter which one awakens.  Then a thread is awakened from its wait() and can grab the lock and continue processing.

.Thread Group ‡ You can include thread in a set of threads by adding it to an instance of ThreadGroup ‡ ThreadGroups can contain not only threads but also other ThreadGroups.

If a critical section is in use.concurrent package so you don't have to implement your own semaphores. ‡ A mutex is really a semaphore with value 1. which implements mutual exclusion among processes to avoid race condition to access any shared resource. the calling process will be removed from a run queue and put into a sleep state.Semaphore ‡ Semaphore is a synchronization mechanism.util. ‡ Semaphore maintains a counter to implement locking and unlocking. . It avoids busy waiting. ‡ Java 5 comes with semaphore implementations in the java.

Semaphores ‡ Semaphores have two purposes  Mutex: Ensure threads don¶t access critical section at same time  Scheduling constraints: Ensure threads execute in specific order ‡ A semaphore is an IPC mechanism that is implemented conceptually with at least these two components ± a counter (int) variable ± a wait queue of processes ‡ And has at least these two operation ± wait for the semaphore to be free (p) ± signal that the semaphore is now free (v) .

then the semaphore is free. or available. or not in use  Not free.  If the counter is zero (or negative). or unavailable.Semaphore ‡ The semaphore has at least these possible states:  Free. . then the semaphore is in use (not free). or in use ‡ Interpretation of the counter variable:  If the counter is positive.

4. then S is decremented (S.counter ± 1.counter = S. If a process does a wait (p) on S. then the process is blocked and put in S¶s wait queue.) If a process does a wait (p) on S and if S is not free.Semaphore ‡ Cases using a semaphore S 1. then the process at the head of the queue is removed and unblocked (and can continue to execute) 2. 3. and if the semaphore is free. 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). If a signal (v) on S and there is a process in the S queue.

io ‡ Data is transferred to devices by µstreamsµ output .IOStreams ‡ Usual Purpose: storing data to µnonvolatileµ devices. e.stream Program Device Device .g. harddisk ‡ Classes provided by package java.stream Program input .

keyboard standard input stream CPU standard output stream MEM monitor terminal console HDD How does information travel across? Streams .

keyboard standard input stream CPU standard output stream file input stream LOAD READ MEM monitor terminal console How does information travel across? HDD file output stream SAVE WRITE Streams files .

containing 8 ± bit information Program 01101001 11101101 00000000 Device .IOStreams ‡ ‡ Program JAVA distinguishes between 2 types of streams: Text ± streams. containing µcharactersµ I µ M A S T R I N G \n Device ‡ Binary Streams.

4. having   2 types of streams (text / binary) and 2 directions (input / output) ‡ Results in 4 base-classes dealing with I/O: 1. 3. Reader: text-input Writer: text-output InputStream: byte-input OutputStream: byte-output . 2.IOStreams ‡ Streams in JAVA are Objects.

.

TextFiles pro con Binary (input &output stream) Text(reader and writer) Efficient in terms Preinformation of time and space about data needed to understand content Human readable.Binary vs. contains redundant information Not efficient .

videos etc.) ./ BinaryFiles ? ALWAYS use TextFiles for final results Binary Files might be used for non-final interchange between programs Binary Files are always used for large amount of data (images.Binary vs. TextFiles ‡ ‡ ‡ ‡ When use Text.

in-memory object to a byte stream. only serial number is written out the second time  When reading. duplicate serial numbers are restored as references to the same object ‡ The objects must be read from the stream in the same order in which they were written.e.  Each object is assigned a serial number on the stream  If the same object is saved twice. .Serialization ‡ Serialization: process of saving objects to a stream i.

. then anyone can print out internal structure and analyze it  Could also have temporary variables that are useless once the program is done running.Serialization ‡ Why isn¶t everything serializable?  Security reasons ± may not want contents of objects printed out to disk.

 An empty interface is called a marker interface. .  For an object to be serializable.  An object is deserialized by reading it from an ObjectInputStream. its class or some ancestor must implement the empty Serializable interface. ‡ The syntax for serialization is straightforward:  An object is serialized by writing it to an ObjectOutputStream.Serialization basics ‡ The requirements for serialization are straightforward:  Only class instances rather than primitive types can be serialized.

Serialization code => Writing objects to a file FileOutputStream out = new FileOutputStream( ³save. ObjectOutputStream oos = new ObjectOutputStream( out ). oos. .close().writeObject( new Date() ).txt´ ). oos.

readObject(). ois. .txt´ ). ObjectInputStream ois = new ObjectInputStream( in ).close(). myObject d = (myObject_type) ois.Deserialization code => Reading objects from a file FileInputStream in = new FileInputStream( ³save.

Conditions for serializability ‡ If an object is to be serialized:  The class must be declared as public  The class must implement Serializable  The class must have a no-argument constructor  All fields of the class must be serializable: either primitive types or serializable objects ‡ The Serializable interface does not define any methods!  Question: What possible use is there for an interface that does not declare any methods?  Answer: Serializable is used as flag to tell Java it needs to do extra work with this class .

‡ You can control serialization by implementing the Externalizable interface.Object Serialization (cont d) ‡ writeObject() will throw an Error if the object passed to it is not Serializable. so it needs to be cast. ‡ readObject() returns something of type Object. .

However.Serialization and primitive types ‡ Technically. ‡ ObjectInputStream implements DataInput for reading primitive types . the ObjectOutputStream implements the DataOutput interface. primitive types cannot be serialized or deserialized. which declares methods such as writeInt to write primitive types to streams.

g.. ‡ static fields are not impacted by serialization.  During deserialization.transient and static fields ‡ A field marked as transient is not impacted by serialization. . transient numeric fields are restored to zero). transient fields are restored to their default values (e.

‡ JDBC provides RDBMS access by allowing you to embed SQL inside Java code .JDBC ‡ Java DataBase Connectivity ‡ The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections.

. import the java. We can change database engines without changing database code.JDBC Architecture Java application calls the JDBC library.sql package. JDBC loads a driver which talks to the database.

jdbc.execute(³DDL Query´)."pass@123"). getConnection("jdbc:odbc:Deepi". .executeUpdate(³DML Query´). ‡ To execute it:  st. ‡ To Get the connecttion:  Connection con = DriverManager. ‡ To create a SQL statement:  Statement st=con.JdbcOdbcDriver").  st.  st.Steps in JDBC ‡ To register the Driver:  Class.createStatement()."sa".executeQuery(³select query´).forName("sun.odbc.

you can only suggest it. . ‡ Only the JVM decides when to run the GC.Garbage Collector (GC) ‡ Provides automated memory management. ‡ Deletes the unused objects in the memory. ‡ An object becomes eligible for Garbage Collection when its last live reference disappears.

These objects are created on stack.Garbage collection and Performance How Memory is allocated:  Object creation Object is constructed either on a memory heap or on a stack. objects are created for method arguments and method variables. Such objects are eligible for garbage-collection when they go out of scope.  Memory heap When new keyword is called memory is allocated in the heap and returned when the reference is made null  Stack During method calls. .

Garbage Collection ‡ Advantages of Garbage Collection :  More productivity  Program Integrity ‡ Disadvantages of Garbage Collection :  program performance .

    Before gc happens the finalize() method is called It is called only once Finalize method can be overridden by the user. Finalize can be used to make an object not to be garbage collected .Finalize() method ‡ Finalize()  Class Object has a finalize() method.

Classical Algorithms ‡ Three classical algorithms  Mark-sweep  Reference counting  Semispace ‡ Tweaks  Generational garbage collection (JAVA DEFAULT) ‡ Out of scope  Parallel ±perform GC in parallel  Concurrent ±run GC at same time as app  Real-time±ensure bounded pause times .

variables on stack& in registers ‡ Recursively visit every object through pointers  Markevery object we find (set mark bit) ‡ Everything not marked = garbage  Can then sweep heap for unmarked objectsand free them .Mark-Sweep ‡ Start with roots  Global variables.

‡ Annotations are defined using an @ syntax .  constructors. development tool.Annotations ‡ Annotations in Java is all about adding metadata facility to the Java Elements like  package declarations. or during runtime. deployment tool.  fields.  class.  variables and etc ‡ An annotation indicates that the declared element should be processed in some special way by a compiler.  methods.

} @NonNull Object get() { return field.Structure of Java Compiler Source File class C { NonNull Object field. C(@NonNull Object p) { field = p. } } Parser Type Checker Class File Writer Class File   Comments Error .

} @NonNull Object get() { return field. C(@NonNull Object p) { field = p.Structure of Java5 Compiler Source File class C { @NonNull Object field. } } Parser Type Annotation Class File Checker Checker Writer Class File Program with annotations Error Error Annotation Checker Plugins .

Annotation Types
‡ Marker ‡ Single-Element ‡ Full-value or multi-value

Marker
‡ Marker annotations take no parameters. They are used to mark a Java element to be processed in a particular way. ‡ Example: public @interface MyAnnotation { } ‡ Usage: @MyAnnotation public void mymethod() { .... }

Single-Element
‡ 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. Example: public @interface MyAnnotation { String doSomething(); } Usage: @MyAnnotation ("What to do") public void mymethod() { .... }

‡

‡

String date(). } . ‡ Example: public @interface MyAnnotation { String doSomething(). count=1.Full-value or multi-value ‡ Full-value type annotations have multiple data members.. } ‡ Usage: @MyAnnotation (doSomething= "What to do". date="09-09-2005") public void mymethod() { . int count...

 and @SuppressWarnings. ‡ Four are imported from java.lang.  @Override. ‡ Three are included in java.annotation ‡ ‡ ‡ ‡ @Retention.lang.The Built-In Annotations ‡ Java defines seven built-in annotations.  @Deprecated. and @Inherited. . @Target. @Documented.

CONSTRUCTOR)  can be applied to constructors ‡ @Target(ElementType.TYPE)  can be applied to any element of a class ‡ @Target(ElementType.FIELD)  can be applied to a field or property ‡ @Target(ElementType.METHOD)  can be applied to a method level annotation ‡ @Target(ElementType.ANNOTATION_TYPE)  indicates that the declared type itself is a .PARAMETER)  can be applied to the parameters of a method ‡ @Target(ElementType.LOCAL_VARIABLE)  can be applied to local variables ‡ @Target(ElementType.The Target annotation ‡ @Target(ElementType.

CLASS and RUNTIME defined in RetentionPolicy Enumeration. The three possible ways of telling this are. .  Retain the Annotation Definition during the Runtime so that JVM can make use of it. ‡ The Annotation that is used to achieve this is @Retention and it takes a possible values of SOURCE.  Retain the Annotation in the Source Code only  Retain the Annotation in the Class file also.Reflection ‡ 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.

Need of Annotation ‡ Less coding ‡ Easier to change ‡ Smarter development. ‡ Providing information to the Runtime System . ‡ Providing information to the tools. ‡ Providing information to the Compiler.

Sign up to vote on this title
UsefulNot useful