Learn Java


Object Oriented Programming Structure Features of OOPS Objects / Instance Classes Inheritance Polymorphism

Overloading / Static Polymorphism / Compile-time 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.

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

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

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 .

JVM is Write Once-Run Anywhere (WORA) software. JVM's main job is interpreting java byte code and translating this into actions or OS calls.Java Virtual Machine Ø The Java Virtual Machine provides a platformindependent way of executing code. 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.

JRE and JVM .

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

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

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

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

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. Instance variables are initialized automatically. .

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

It is a Spl. 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. of object created

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

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

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

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

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

Down the hierarchy Purpose : Reusability (without changing its identity) Syntax: <modifier> class <name> extends <superclass> { <declaration>* } .Inheritance Two important concepts Generalization .Up the hierarchy Specialization .

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

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

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

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

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

super() method is used to invoke the IMMEDIATE base class constructor. this() and super() call must occur as the first statement in a constructor. The this() call invokes the constructor with the corresponding parameter list. 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.println("a= "+a+" b = "+ b + " c= " .a=a.c=c.int c) { this.int b. GParent() { System. System.b=b.c.println("From gparent").int b) { //this(a. System.out.b.println("a= "+a+" b = "+ b).100). } GParent(int a.out. this(). this. } GParent(int a.Example : this() and super() class GParent { int a.out.b.

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

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

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

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

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

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

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

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

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

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

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

Primitive Data Types and Corresponding Wrapper Primitive Data Classes Constructor Wrapper
byte char short int long float double


byte or String char short or String int or String long or String



boolean or String

Character Short Integer Long Float Double

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

AutoBoxing and AutoUnboxing
Example: int x=10; Integer n = x; int y = n;

//AutoBoxing //AutoUnBoxing

Methods to Extract the Wrapped Values
public boolean booleanValue() public char charValue() public byte byteValue() public short shortValue() public int intValue() public long longValue() public float floatValue() public double doubleValue()

Boolean Character Byte, Short, Integer, Long, Float, Double Byte, Short, Integer, Long, Float, Double Byte, Short, Integer, Long, Float, Double Byte, Short, Integer, Long, Float, Double Byte, Short, Integer, Long, Float, Double Byte, Short, Integer, Long, Float, Double

or String and radix String.. or String and radix String.) static int parseInt(…) static long parseLong(…) static float parseFloat(…) static double parseDouble(…) 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 . 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. 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 contain only constants. All the methods should be implemented by the child class.NO Variables.Interface Interface is to support multiple inheritance in Java. Interfaces should be implemented by the child class Can have only abstract method. All the fields are public static final in nature. Interfaces cant be instantiated A class can implement many interfaces. NO NEED FOR RELATIONSHIP .

an enum can have constructors. An enum cannot be declared within a method. You use the keyword enum and not class to declare an enum. You cannot instantiate an enum with the new operator. . methods.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. and fields. Just like a class.

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

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

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

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

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

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

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

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

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

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

Can access the outer class level variable. . method-local inner class can't use any access specifiers. CANT access the variable inside the method in which the inner class is created except a final variable.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 can be declared abstract and final.

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

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

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

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

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

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

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

Error Types: happens due to problems originating from the execution environment. (Exception Class) • Exception Should be Handled or Thrown to the exception handler.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. .

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. generally originate from within the application. The exceptions (represented by subclasses of Exception).

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

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

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

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

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

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

You do not need to declare runtime exceptions or errors. You can choose to handle runtime exceptions. .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.

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

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

v One or more subclasses of the exceptions thrown by the overridden method. v The overriding method cannot throw: v Additional exceptions not thrown by the overridden method.Method Overriding and Exceptions v The overriding method can throw: v No exceptions v One or more of the exceptions thrown by the overridden method. v Super classes 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.

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

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

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

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

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

//calling a method on a literal String char Initial = “Priya”.charAt(0). . //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”.

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

word 1 word 2 word 1 “Java" “Java" OK “Java" word 2 Less efficient: wastes memory . String word1 = “Java". String word2 = new String(word1). String word2 = word1.Advantages Of Immutability Uses less memory String word1 = "Java".

word = ch + word.charAt (0)).substring (1).toUpperCase(word. String word = “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" . char ch = Character.

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

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

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

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

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

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

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

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

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

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


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

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

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

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

implementation is synchronized HashMap: based on the hashtable data structure. 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. TreeMap: implements the SortedMap interface Sorted and unsynchronized. .

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

Class Interface Duplicates Allowed? Ordered/ Sorted Synchronized HashMap LinkedHashMap Hashtable TreeMap Map Map Map Map No No No No Not ordered Not sorted Ordered Not ordered Not sorted No No Yes 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.

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

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

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

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.

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

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

Start Execution: thr1. Creating Thread Object: Thread thr1 = new Thread( myObject ). .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().

.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 l .Threads within a process THREAD STACK SHARED MEMOR Y THREAD DATA THREAD TEXT l All threads are parts of a process hence communication easier and simpler.

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

Thread Priorities Why priorities? Determine which thread receives CPU control and gets to be executed first Definition: – Integer value ranging from 1 to 10 – Higher the thread priority → larger chance of being executed first – Example: ● Two threads are ready to run ● First thread: priority of 5. already running ● Second thread = priority of 10. comes in while first thread is running .

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

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.

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

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. There are two versions . In general.notify() and notifyAll(). use notifyAll() .notify() To awaken a thread. a different thread which has a lock on the same object must call notify. and thus guaranteed to be awakened. Notify is safe only under 2 conditions: When only 1 thread is waiting. When notify is called. Then a thread is awakened from its wait() and can grab the lock and continue processing. and it doesn’t matter which one awakens.

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

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

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

or not in use Not free. then the semaphore is 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 unavailable. If the counter is zero (or negative). . or available. then the semaphore is free.

counter – 1. then the process is blocked and put in S’s wait queue. 2.counter = S. 3. If a process does a wait (p) on S.) If a process does a wait (p) on S and if S is not free. If a process does a signal (v) on S and if there is no process in the wait queue for S. 4. then S is decremented (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. and if the semaphore is 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) .

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

keyboa rd standard input stream standar doutput stream CP U MEM monit or termin al consol e How does information travel across? Streams HDD .

keyboard standard input stream standar doutput stream file input strea m LOAD READ CPU MEM monitor terminal console How does information travel across? HDD files file outpu t strea m SAVE Streams .

containing 8 – bit information I ‘ M A S T R I N G \ n Devic e Progra m 0110100 1 1110110 1 0000000 0 Devic e .IOStreams JAVA distinguishes between 2 types of streams: Text – streams. containing ‘characters‘ Progra m Binary Streams.

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


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

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

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.Serialization Serialization: process of saving objects to a stream i. in-memory object to a byte stream. 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.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.

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. For an object to be serializable. its class or some ancestor must implement the empty Serializable interface. An object is deserialized by reading it from an ObjectInputStream. The syntax for serialization is straightforward: An object is serialized by writing it to an ObjectOutputStream.

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

ois.close().readObject(). myObject d = (myObject_type) ois. ObjectInputStream ois = new ObjectInputStream( in ). .txt” ).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 .

readObject() returns something of type Object. so it needs to be cast. 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.

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

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

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.

JDBC loads a driver which talks to the database.JDBC Architecture Java application calls the JDBC library. Ø Click to edit Master text styles Second level ● Third level ● Fourth level ● Fifth level Ø import the java.sql package. . We can change database engines without changing database code.

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

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

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. objects are created for method arguments and method variables. Such objects are eligible for garbage-collection when they go out of scope. 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.

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

Start with roots Global variables, 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

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

Structure of Java5 Compiler Source File class C { @NonNull Object field. C(@NonNull Object p) { field = p. } @NonNull Object get() { return 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() { .. } ..

. } @MyAnnotation ("What to do") public void mymethod() { . or single-value type. annotations provide a single piece of data only. Example: ● ● ● public @interface MyAnnotation { String doSomething(). This can be represented with a data=value pair or. within parenthesis. } Usage: ● ● ● ● . simply with the value (a shortcut syntax) only.Single-Element Single-element...

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

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

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

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

com www.bcahub.shareittips.com .www.shareittips.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.