‡ 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

‡ 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. JVM is Write Once-Run Anywhere (WORA) software. . by abstracting the differences between operating systems and CPU architectures.

JRE and JVM .

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

} .Structure of JAVA Program ‡ Package declaration. ‡ Import statements ‡ Class declaration { Variable declaration/ definition. 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.

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

of time of invocation depends on no.  The no. 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.Constructor ‡ It is a Spl.

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

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

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

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

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

‡ 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

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. Note: ‡ Code reuse is also best achieved by aggregation when there is no is-a relationship .IS-A & HAS-A relationship ‡ When two classes are related. ‡ Has-a relationship can be described in Java code as member fields.

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 different set of parameters.Late Binding .Same method name with same set of parameters.Polymorphism ‡ Polymorphism (from Greek. . ‡ 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.

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

but it can hide them.Overriding ‡ The overridden method in the superclass is NOT inherited by the subclass. method name and parameters) and the same return type. ‡ Super keyword is used to invoke an overridden method in the superclass. .  Overridden Methods Cannot Be Less Accessible.. ‡ A subclass cannot override fields of the superclass. ‡ Constructors cant be Overridden. 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. ‡ Works only with inheritance.e.

. This allows the subclass to influence the initialization of its inherited state when an object of the subclass is created. ‡ The this() call invokes the constructor with the corresponding parameter list. ‡ this() and super() call must occur as the first statement in a constructor.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. ‡ super() method is used to invoke the IMMEDIATE base class constructor.

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

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

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

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

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

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

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

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

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

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

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

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

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 //UnBoxing . Integer n = new Integer(x). int y = n. ‡ Converting a reference type to a value type is known as UnBoxing.Boxing and Unboxing ‡ Converting a value type to a reference type is known as Boxing. int x=10.intValue().

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

Long. Integer. Short. Double Byte. Float. Long. Double Byte. Integer. Double Byte.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. Short. Float. Integer. Short. Long. Short. Integer. Float. Double Byte. Short. Short. Float. Float. Integer. Integer. Double Byte. Long. Long. Double . Float. Long.

) static int parseInt(«) static long parseLong(«) static float parseFloat(«) static double parseDouble(«) String. or String and radix String.. or String and radix 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 .

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

‡ Abstract method cannot be private or final ‡ A class can inherit only one abstract class. ‡ NEED RELATIONSHIP between classes .Abstract Class ‡ Class which have a abstract method (method without definition) is abstract class. ‡ 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.

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

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

‡ 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(e).RIGHT. int i = e.out.Enum Example2 enum Edge { TOP.out.ordinal().TOP. public static void main(String[] a) { Edge e = Edge. System. System.println(i). } } .BOTTOM.LEFT.

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

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

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

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

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

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

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

‡ Can access the outer class level variable. ‡ 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. ‡ Method-local inner class can be declared abstract and final.Method-local inner class ‡ A method-local inner class can be instantiated only within the method where the inner class is defined. .

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

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

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

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

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

. (Exception Class) ‡ Exception Should be Handled or Thrown to the exception handler. (Error Class)  happens due to problems originating inside the application itself. ‡ 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.

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). ‡ Types:  Checked Exception  Unchecked Exception . generally originate from within the application. on the other hand.

. ‡ It MUST be thrown programmatically or Handled. 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.

Unchecked Exception ‡ Occur due to program bugs. . ‡ Write the correct code to avoid the runtime exceptions than write the code to catch them but it is not illegal to catch them. ‡ 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.

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

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

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

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

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

Passing the exception  In any method that might throw an exception. 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.

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

 Super classes of the exceptions thrown by the overridden method .  One or more subclasses 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.

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

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

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

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

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

‡ have methods you can call. ‡ can be assigned to String variables.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.

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

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

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

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

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

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

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

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

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

‡ Can grow dynamically in size without bounds. An empty StringBuffer is created with 16-character capacity.StringBuffer Class ‡ String Buffers are mutable strings. from a string or with a capacity. ‡ StringBuffer is a final class. ‡ 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. .

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

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

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

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


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

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

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

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

‡ TreeMap:  implements the SortedMap interface  Sorted and unsynchronized.  No ordering  allows null and is unsynchronized ‡ LinkedHashMap:  maintains a doubly linked list.Map Classes ‡ HashTable:  implementation is based on the hashtable data structure. .  No ordering.  implementation is synchronized ‡ HashMap:  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. ‡ You create a locale object by using the Locale class . days of the week.DateFormat class provides several methods for formatting the date/time for a default or a specific location.Date Class ‡ The java. and so on. days of the months.

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

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

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

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

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

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

 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.

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

already running Second thread = priority of 10.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. comes in while first thread is running .

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. it does nothing until it is notified by another thread.wait() ‡ When a thread enters a wait state. « // do something } . public synchronized blah() { wait().

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

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

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

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

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

.counter ± 1. 3. If a process does a signal (v) on S and if there is no process in the wait queue for S.Semaphore ‡ Cases using a semaphore S 1.counter = S. If a signal (v) on S and there is a process in the S queue. then the process is blocked and put in S¶s wait queue. and if the semaphore is free. 4. then the semaphore is set to free by incrementing its counter (to positive). If a process does a wait (p) on S. then S is decremented (S. then the process at the head of the queue is removed and unblocked (and can continue to execute) 2.) If a process does a wait (p) on S and if S is not free.

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

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 . containing µcharactersµ I µ M A S T R I N G \n Device ‡ Binary Streams.IOStreams ‡ ‡ Program JAVA distinguishes between 2 types of streams: Text ± streams.

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


Binary vs. 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. contains redundant information Not efficient .

Binary vs.) . TextFiles ‡ ‡ ‡ ‡ When use Text./ 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. videos etc.

Serialization ‡ Serialization: process of saving objects to a stream i. 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.  Each object is assigned a serial number on the stream  If the same object is saved twice. . only serial number is written out the second time  When reading. in-memory object to a byte stream.e.

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

 For an object to be serializable.  An object is deserialized by reading it from an ObjectInputStream. .  An empty interface is called a marker interface.Serialization basics ‡ The requirements for serialization are straightforward:  Only class instances rather than primitive types can be serialized. 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.

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

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

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 .

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

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

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

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

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

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

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

objects are created for method arguments and method variables. .  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. These objects are created on stack. Such objects are eligible for garbage-collection when they go out of scope.Garbage collection and Performance How Memory is allocated:  Object creation Object is constructed either on a memory heap or on a stack.

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.

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

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

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

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

‡ 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, 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() { .... }



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

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

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

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

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

Sign up to vote on this title
UsefulNot useful