Scjp
Inheritance
HAS A relationship:
Instance of operator:
Polymorphism
Interface
Abstract class
Final
Finalize method
Finally
Garbage collection
Static methods
Access modifiers: (public, private,protected, default)
Static variables
Instance variables
Local variable
Serialization
Tokenizing
Wrapper class
Exceptions hierarchy
Checked exceptions:
Unchecked exceptions:
Interprocess communication in Java
String
String buffer/ string builder
Hash code
Collections
collection
Collection
Lists
Comparator
Comparable
Enumeration
Iterator
Listiterator
Threads (java threads from orielly)
Multithreading
Methods
Defining thread
Thread life cycle
States
Synchronization and locks
Aggregation
Composition
Overloading
Overriding
1) Encapsulation
- mechanism that binds together code and data it manipulates
Advantages:
- modify our code without breaking the code of others.
- it gives maintainability, flexibility and extensibility to our code.
- The fields of a class can be made read-only or write-only.
- A class can have total control over what is stored in its fields.
- The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.
2) Inheritance
- is defined as process where one object acquires properties of another.
- information is made manageable in hierarchical order.
- allows code defined in one class to be used in another class
- IS A relationship in java is represented through keywords extends for class inheritance and implements for interface implementation
- Java supports single inheritance which means class cannot extend more than one class.
- java does not support multiple inheritance.
Public class dog extends mammal, animal{}
3) HAS A relationship:
- this determine whether certain class HAS -A certain thing.
- this helps to reduce duplication of code as well as bugs.
Public class vehicle {}
public class speed{}
Public class van extends vehicle{
Private speed sp;
}
This shows Van has a speed. By having separate class as speed, we do not have to put entire code of speed into van class, which makes it possible for speed class to be reused in multiple applications.
4) Instance of operator:
It is used to check whether mammal is an animal and dog is an animal
Interface animal{}
Class mammal implements animal{}
public class dog extends mammal{
Public static void main( String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instance of Animal);
System.out.println(d instance of Animal);
System.out.println(d instance of Mammal);
5) Polymorphism
- ability of object to take many forms is polymorphism.
- in java all classes are polymorphic by nature, since object will pass IS-A test for their own type and for class object.
- any java object passing more than one is a relationship
- Dogs sense of smell is polymorphic in nature
Public interface Vegeterian{}
Public class Animal{}
Public class deer extends Animal implements Vegeterian{}
Deer class is considered to be polymorphic since it has multiple inheritance.
Deer IS-A Animal
Deer IS-A Vegeterian
Deer IS-A Deer
Deer IS-A object
Polymorphism supports method overriding. It provides way for multiple inheritance.
6) Interface
- collection of abstract methods.
- 100% abstract superclass that defines the methods subclass must support but not how they must be supported.
- Can have only abstract methods.
- Less flexibility than abstract class as rules are strict
- No implementation code as all methods are abstract.
- Cannot have instance variables, constructors and can have only public and none visibility
- If you prefer to change your design frequently, use interface as opposed to abstract class
- Supports multiple inheritance
- Has only public members
- Interface with no defined methods act like markers
7) Interface different from class in following ways:
- you cannot instantiate an interface.
- interface does not contain any constructors
- All methods in interface are abstract
- interface cannot contain instance fields. Only fields that can appear in interface are static and final.
- interface can extend multiple interfaces.
Public interface Hockey extends sports, events{}
- interface is implemented by class.
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interface.
An interface can extend another interface, similarly to the way that a class can extend another class.
8) Abstract class
- class that is declared abstract
- may or may not include abstract methods
- cannot be instantiated but they can be subclassed.
- has executable methods and abstract methods
- Can only subclass one abstract class.
- Can have instance variables, constructors
- Does not support multiple inheritance
- Can contain private as well as protected members
- when abstract class is subclassed, subclass usually provides implementation for all of the abstract methods in the superclass.
- however if it does not, subclass must also be declared as abstract.
- if abstract class contains only abstract method declarations, it should be declared as interface instead.
Abstract class graphic object{
Int x,y;
Void moveTo(int newX, int newY);
}
abstract void draw();
Abstract void resize();
}
Class circle extends graphic object{
void draw(){}
void resize(){}
}
Class rectangle extends graphic object{
void draw(){}
void resize(){}
}
9) Final
- java class with final modifier is called final class in Java.
- Final class is complete in nature and cannot be subclassed or inherited.
- several classes in java are final. Integer, string and other wrapper classes.
- Is constant declaration.
Final class personal loan{}
10) Finalize method
- defined in java.Lang.object class.
- inside finalize method you specify those actions that must be performed before an object is destroyed.
- Used to save object from deletion.
- helps in garbage collection
- it is called just prior to garbage collection
Protected void finalize(){}
Here keyword protected is a specified that prevents access to finalize() by code defined outside it's class.
11) Finally
- handles exception
- block of code that is always executed after try/catch block has completed.
- will execute whether or not an exception is thrown.
- it can be used to
Close file handles
Freeing up any resources that might have been allocated at beginning of the method.
Finally is optional. However, try statement requires at least one catch or finally clause.
12) Garbage collection
- objects are created on heap in Java irrespective of their scope.
- garbage collection is mechanism provided by JVM to reclaim heap space from objects which are eligible for garbage collection.
- garbage collection in java is carried out by deamon thread called garbage collector.
- before removing object from memory, garbage collection thread invokes finalize() method of that object and gives an opportunity to perform an sort of cleanup that is required.
- it cannot be forced as it will trigger only when JVM thinks it needs a garbage collection based on Java heap size.
- there are methods like system.Gc() and runtime.Gc() which is used to send request of garbage collection to JVM without any guarantee.
- if there is no memory space for creating new object in heap, JVM throws outofmemoryerror or java.lang.outofmemoryerror heap space.
- Object eligible for garbage collection when no live thread can access it
- System.gc to force garbage collection
13) Access modifiers: (public, private,protected, default)
- public all classes from all package can have access to the public class
- private can't be accessed by code in class other than class in which private member was declared
- protected accessed by subclass even if subclass is in different package
- default accessed only if class accessing member belong to the same packag
Constructor has no return type and must match class name
14) Static methods
- scope of variables in static method is limited to that methods body. You cannot refer to the variable in one static method that is declared in another.
-multiple methods: you can define as many static methods as you want in .java file. These methods are independent.
- calling other static methods: any static method defined in .java file can call any other static method in same file or any static method in java lib like math
- overloading: static methods whose signature differs are different static methods. Using one name for two static methods whose signatures differ is known as overloading.
- single return value: like mathematical function, java static method can provide only one return value, of type declared in method signature.
- static method can use void as return type to indicate that it has no return type.
- cannot be overridden
- only one copy of static method for entire class
- cannot be declared as final or abstract
Public static double sqrt(double c)
15) Static variables
- Class variables are static variables. Static variables are used in singleton pattern.
- static variable belongs to java class and non static variable belongs to object class.
- static variables will keep same value for every object while non static variable varies from object to object.
- one static variable is shared between all objects in java.
- in multithreading environment, access to static variable must be synchronized or you will get unexpected behavior.
- it is not suggested to use static variable in multithreaded and concurrent application as it may create subtle bugs hard to find and debug.
16) Instance variables
- declared inside class outside any methods
- instance variables are created when an object is created with use of keyword new and destroyed when object is destroyed.
- recommended to make it private. Usually it are visible for all methods, constructors and block in the class.
- non static variables
- created and goes in heap memory
17) Local variable
- declared inside the method
- visible only within declared method, constructors and block.
- there is on default value for local variables so local variables should be declared and initial value should be assigned before first use.
- created and goes in stack along with primitive variables like int and double
18) Serialization
- object can be serialized on one platform and deserialized on entirely different platform.
- for class to be serialized successfully, two conditions must be met:
- class must implement java.io.serializable interface
- all of fields in class must be serializable. If field is not serializable, it must be marked transient.
Public class employee implements java.io.serializable
{
public string name;
Public string address;
Public int transient SSN;
public int number;
Public void mailCheck()
{
system.out.println("mailing a check to:" + name +""+ address);
}
- let's us save this object and all of it's instance variables
- can exclude field from serialization by using transient
19) Tokenizing
- taking big peices of data, breaking them into little pieces, and storing the little pieces in variables.
20) Wrapper class
- for every primitive in java. For int is Integer, float is Float.
21) Exceptions hierarchy
- Object
- Throwable
- Error, exception
- RuntimeException
22) Checked exceptions:
- beyond control of programs like
I/O exception,
remote exception,
SQLException
DataAccessException
Classnotfoundexception
Invocationtargetexception
- Handled by user during compile time.
- Called when resource we are looking for is not found( file missing or remote server is down)
23) Unchecked exceptions:
- are mostly programming mistakes.
- Runtime exceptions are unchecked exceptions which happens due to programmatic errors, wrong data etc.
- Handled by JVM.
Nullpointerexceptions
Arrayindexoutofboundexception
Illegalargumentexception
Illegalstateexception
24) Interprocess communication in Java
- System.in
- System.out
- System.err classes
25) String
- is immutable.
- Cannot modify string object but replace it by creating new instance.
26) String buffer/ string builder
- is mutable.
- Used to modify contents.
- Stringbuilder is not synchronized making it faster than string buffer.
- Classes used when lot of modification to be made to string of characters.
==
- compares references and equals compares contents
- compares two objects to determine if they are the same object in the memory.
27) Hash code
- increase performance of large collection of data.
- It tells in which bucket we need to look to find name.
- Amy and may has same hash code as they have same letters
- If two objects are equal then calling hash code method on each of the two objects must produce same integer results
28) Collections
- framework in java
- gives lists, sets, maps and queues to satisfy most of coding needs
29) collection
- data structure in which objects are stored and iterated over
30) Collection
- interface from which set, list and queue extend
Lists : list of things
Sets : unique things
Maps : things with unique I'd
Queues: things are arranged by order in which they are to be processed
31) Lists
- Array list :
addelementtospecifiedindexarra ylistexample:
- arraylist.add(1,"inserted element");
Copy elements of arraylist to array example:
- Object[] objArray=arrayList.toArray();
Get size of arraylist example:
- int totalElements=arrayList.size()
Get synchronized list from arraylist example:
- List list=Collections. synchronizedList(arrayList);
Java string array length example:
- int length= strArray.length
Maximum arraylist example:
- Object obj= Collections.max(arrayList);
Minimum arraylist example:
- Object obj= Collections.min(arrayList);
Remove all elements from arraylist example
- arrayList.clear();
Remove element from arraylist example
- Object obj= arrayList.remove(1);
Replace all array list example
- collections.replaceAll( arrayList,"A","Replace All");
Replace an element using list iterator example
- listiterator.next();
- listiterator.set(100);
Replace element at specified index arraylist example
- arrayList.set(1,"replaced element");
Search an element in arraylist example
- boolean blnfound= arraylist.contains("2");
- int index= arrayList.indexOf("4");
If (index==-1)
system.out.println("arraylist does not contain 4")
Else
System.out.println("arraylist contains 4 at index:" +index);
Shuffle elements of arraylist example
- collections.shuffle(arraylist) ;
Simple array list
Sort array list in descending order
- comparator comp=collections.reverseorder( );
System.out.println(" before sorting arraylist in descending order "+ arraylist)
Collections.sort(arraylist, comparator);
System.out.println("after sorting arraylist in descending order" + arraylist)
Sort java arraylist example
- collections.sort(arraylist);
fast iteration and fast random access.
Can grow dynamically.
Has more powerful insertion and search mechanism.
Arrays are very useful when working with sequence of same kind of data.
32) Comparator
ArrayCompare
- boolean[] blnarray1= new boolean[]{true, true, true};
boolean[] blnarray2= new boolean[]{true, false, true};
boolean blnresult= Array.equals(blnArray1, blnArray2);
Comparebytearrayexample
Comparechararrayexample
Comparedoublearrayexample
- defined in java.util package
- utility to sort objects
- public int compare(object o1, object o2)
- compare two object provided to him
33) Comparable
- defined in java.Lang package
- provided by default
- public int compareTo(object o)
- compares this reference with object specified
34) Enumeration
GetEnumerationOverArrayListExa mple
- Enumeration<String> e= Collections.enumeration( arrayList);
System.out.println(" Enumerating through Java ArrayList");
While(e.hasMoreElements())
System.out.println(e. nextElement());
GetenumerationOverVectorExampl e
- Enumeration e= Collections.enumeration(v);
System.out.println(" Enumerating through Java Vector");
While(e.hasMoreElements())
System.out.println(e. nextElement());
GetenumberationHashSetExample
- Enumeration e= Collections.enumeration( hashSet);
System.out.println(" Enumerating through Java HashSet");
While(e.hasMoreElements())
System.out.println(e. nextElement());
- Enumeration<String> e= ht.keys();
System.out.println(" Enumerating through Java Vector");
While(e.hasMoreElements())
System.out.println(e. nextElement())
- used for passing through collection of unknown size
- does not allow for modification of collections, thus iterator are used if this is required.
- has two options: nextElement() which returns next object in collection
HasMoreElements() which returns true until last object has been returned by nextElement()
35) Iterator
Iterate through arraylist using iterator example
- Iterator<string> itr= arraylist.iterator();
System.out.println("iterating through Arraylist elements");
While (itr.hasNext())
System.out.println(itr.next()) ;
Iterate through elements of hashset example
- Iterator<integer> itr= hSet.iterator();
System.out.println("hashset contains ");
While (itr.hasNext())
System.out.println(itr.next()) ;
Iterate through elements of linked hash set example
- Iterator<string> itr= lhashSet.iterator();
System.out.println(" LinkedHashSet contains ");
While (itr.hasNext())
System.out.println(itr.next()) ;
Iterate through elements of tree set example
- Iterator<string> itr= tSet.iterator();
System.out.println("TreeSet contains");
While (itr.hasNext())
System.out.println(itr.next()) ;
Iterate through elements of java linkedlist
- Iterator<string> itr= lList.iterator();
System.out.println("iterating through linkedlist elements");
While (itr.hasNext())
System.out.println(itr.next()) ;
Iterate through vector elements
- Iterator<string> itr= v.iterator();
System.out.println("iterating through vector elements");
While (itr.hasNext())
System.out.println(itr.next()) ;
Iterate values of hash map example
- collection<string> c= hMap.values();
Iterator<string> itr= c.iterator();
System.out.println("iterating through Arraylist elements");
While (itr.hasNext())
System.out.println(itr.next()) ;
Iterate values of hash table example
- enumeration<String> e=ht.elements();
While(e.hasMoreElements())
System.out.println(e. nextElement());
Iterate through linkedhashmap example
- Iterator<string> itr= c .iterator();
System.out.println("iterating through linkedhasmap elements");
While (itr.hasNext())
System.out.println(itr.next()) ;
Iterate values of tree map example
- Iterator<string> itr= c .iterator();
System.out.println("iterating through tree map elements");
While (itr.hasNext())
System.out.println(itr.next()) ;
JavaIteratorExample
- Iterator<string> itr= aList.iterator();
System.out.println("iterating through Arraylist elements");
While (itr.hasNext())
System.out.println(itr.next()) ;
Enables you to cycle through the collection, obtaining or removing elements
- HasNext
- Next
36) Listiterator
Iterate through vector using list iterator example
- ListIterator<String> itr= v.listIterator();
system.out.println("iterating through vector elements in forward direction..");
While(itr.hasNext())
System.out.println("itr.next() );
System.out.println("iterating through elements in backward direction");
While(itr.hasPrevious())
system.out.println("itr. previous());
Extends iterator and allows bidirectional traversal of list and modification of elements
HasNext
Next
Has previous
Previous
37) -Vector:
Add element to specified index vector example
- v.add(1, "INSERTED ELEMENT");
Append all elements of other collection to vector example
- v.addAll(array list);
Copy elements of array list to vector example
- collections.copy(v,arrayList);
Copy elements of vector to array example
- Object[] objArray= new Object[5];
v.copyInto(objArray);
Copy elements of vector to vector example
- collections.copy(v2,v1);
Get size of vector example
- int total elements= v.size();
Get sublist of java vector example
- List<String> lst= v.subList(1,3);
Insert all elements of other collection to vector
- v.addAll(1,arrayList);
Maximum vector example
- object obj = Collections.max(v);
Minimum vector example
- object obj= collections.min(v);
Remove all elements of vector example
- v.clear();
Remove element from vector by index example
- v.removeElementAt(2);
Replace element at specified index vector example
- v.set(1,"replaced element");
Set size of java vector example
- v.setSize(5);
same as array list except vector methods are synchronized for thread safety
Vector is an array with dynamic size
It increases , decreases it's size as you add/remove elements from it
Not as fast as array but is more efficient
38) - Linked list :
Add elements are start end linked list example
- lList .addFirst("0");
lList.addLast("6");
CheckelementLinkedListExample
- Boolean blnElement= lList.contains("4")
If(blnElement)
System.out.println("LinkedList contains 4");
Else
System.out.println("LinkedList does not contain 4");
GetFirst and Last LinkedList example
- system.out.println(" first element of LinkedList is : +lList.getFirst());
- system.out.println("last element of LinkedList is : +lList.getLast());
GetSublistLinkedListJava example
- List<String> lst = lList.subList(1,4);
LinkedList insert element example
- lList.add(2,2.5);
Remove all elements LinkedList example
- lList.clear();
Remove element LinkedListExample
- Boolean isRemoved = lList.remove("2")
- object obj= lList.remove(2);
Remove first last element LinkedList example
- object obj= lList.removeFirst();
- object = lList.removeLast();
Remove range elements LinkedList example
- lList.subList(2,5). Clear();
allows duplicates
ordered by index position like array list except that elements are doubly linked to one another.
Good choice for fast insertion and deletion
39) Sets
Cares about uniqueness and it doesn't allow duplicates
40)- Hash set :
Check element hash set example
- Boolean blnExists= hSet.Contains(new Integer("3));
System.out.println("3 exists in hash set?; " +blnExists);
Copy elements of hash set to array
- Object [] obj= hSet.toArray();
GetSize of Java HashSet example
- system.out.println("size of hash set after addition: " +hSet.size());
Get synchronized set from hash set example
- set<object> set = Collections. SynchronizedSet(hashSet);
Maximum hash set example
- object obj = Collections.max(hashSet);
Minimum hash set example
- object obj = Collections.min(hashSet);
Remove all elements from hash set example
- hSet.clear()
Remove specified element from hashSet example
- boolean blnRemoved= hSet.remove(new integer("2"));
Does not allow duplicates
unsorted, unordered set
Implementation of set interface
Objects in hash set must override equals and hash code method to check for equality
41) - Linked hash set :
Check element linked hash set example
- Boolean blnExists = lHashSet.contains(new integer("3"));
System.out.println("3 exists in LinkedHashSet" +blnExists);
Copy elements of LinkedHashSet to array
- Object[] objArray= lHashSet.toArray();
Get size of LinkedHashSet example
- lHashSet.size());
Remove all elements from LinkedHashSet example
- lHashSet.clear();
Simplelinkedhashset example
does not allow duplicates
maintains doubly linked list across elements.
Use this instead of hash set when you care about iteration order
Iterate in order in which elements are inserted in the set
42) - Treeset :
Check Value of tree set example
- Boolean blnExists= tSet.contains("3");
Copy elements of tree set to array example
- Object[] obj= tSet.toArray();
Get head set from tree set example
- sorted set<string> sortedSet= tSet.headSet("3");
Getlowesthighestvalue tree set example
- tSet.first()
- tSet.last()
Get size of java tSet example
- tSet.size();
Get subset from tree set example
- sorted set<string> sset= tSet.subset("2","5");
Get synchronized set from tree set
- set set= collections.synchronizedSet( treeSet);
Get tail set from tree set
- sortedSet<String> sortedSet= tSet.tailSet("2");
Remove all elements from tree set example
- tSet.clear();
Remove specified element from tree set example
- boolean blnRemoved = tSet.remove(new Integer("2"));
Does not allow duplicates
one of the two sorted collections
Implements sorted set to maintain entries in ascending order
43) Map: unique Ids
Maps unique key to specific value where key and value are objects
44) - Hash map :
Check value of HashMap example
- boolean blnExists= hMap.ContainsKey("3");
Check value of HashMap example
- boolean blnExists= hMap.containsValue("one");
Empty HashMap example
- hMap.clear();
Get set view of keys from HashMap example
- set<string> st= hMap.keySet();
Get size of HashMap example
- hMap.size();
Get synchronized map from HashMap example
- Map map= Collections.synchronizedMap( hashMap);
Remove value from HashMap example
- Object obj = hMap.remove("2");
unsorted unordered map.
Allows one null key and multiple null values
Not synchronized
Does not guarantee order in which entries are placed.
It can change completely when new elements are added
Better performance than the LinkedHashMap as LinkedHashMap needs expense of maintianing the linked list.
45) - Hash table :
Check key of hash table example
- Boolean blnexits = ht.contains key("2");
Check value of hash table example
- boolean blnExists = ht.contains("Two")
Create hash table from HashMap
- ht.putAll(hMap);
Empty hash table example
- ht.clear();
Get collection of values from hash table example
- Collection<String> c= ht.values();
Get size of hash table example
- ht.size();
SimplehashtableExample
key value pairs in descending order
Does not allow duplicates
synchronized version of hash map
Data inserted using put method
Hashing function analyses key and returns index number
46) - LinkedHashMap:
Check key of linked HashMap example
- Boolean blnExists= lhashmap.containsKey("3");
Check value of linked hash map
- boolean blnExists= lHashmap.containsValue("two");
Empty linked hash map
- lhashmap.clear();
Get size of linked hash map
- lHashMap.size();
Remove value from linked HashMap example
- object obj = lHashMap.remove("2")
faster iteration
Iterate in order in which entries were put in the map
47) - Tree map :
Check key of tree map
- boolean blnExists= treeMap.containsKey("1")
Check value of tree map example
- boolean blnExists = treeMap.containsValue("three")
Empty tree Map
- treeMap.clear()
Get head map from tree map example
- sortedMap<string,string> sortedMap= treeMap.headMap("3");
Get lowest highest key tree map
- treeMap.firstKey()
- treeMap.last key()
Getsetview of keys from treeMap
- set<string> st= treeMap.keySet();
Get size of tree map example
- treeMap.size();
Get sub map from treeMap example
- SortedMap<string,string> sortedMap= treeMap.subMap("2","5");
Getsynchronizedmapfrom treeMap
- Map map= Collections.synchronizedMap( treeMap);
Get tail map from treeMap example
- sortedMap<String,String> sortedMap= treeMap.tailMap("2");
Java tree map example
Remove values from treeMap example
- Object obj= treeMap.remove("2");
Implements sorted map which maintains it's entries in ascending order
It extends abstactmap
48) Queue FIFO
- Priority queue
create priority in priority out queue.
Elements are ordered according to natural ordering or according to comparator
Comparable interface
- used by collections.sort method and java.utils.arrays.sort method to sort list array of objects respectively.
- To implement comparable class must implement single method compareTo
49) Threads (java threads from orielly)
Create thread runnable example
Public class createthreadrunnableexample implements Runnable{
public void run() {
for ( int I=0; I<5; I++)
system.out.println("child thread:" +I);
Try {
Thread.sleep(50);
}
Catch(InterruptedException ie){
System.out.println("child thread interrupted" +ie);
}
System.out.println("child thread finished");
Public static void main (string[] args) {
Thread t= new Thread(new CreateThreadRunnableExample, "My Thread");
T.start();
For (int I =0; I<5; I++)
system.out.println("main thread:" +I);
Try {
thread.sleep(100);
}
catch(InterruptedException ie) {
system.out.println("child thread interrupted" +ie);
}
}
system.out.println("main thread finished");
Get current thread example
Public class GetCurrentThreadExample{
public static void main(String[] args){
Thread currentThread = Thread.currentThread();
System.out.println( currentThread);
}
- Better performance
50) Mutlitasking:
- ability of OS to run more than one program or task at a time.
51) Multithreading
- java has built in support for multithreaded programming
- multithreaded program contains two or more parts that can run concurrently.
- each part of such a program is called a thread and each thread defines separate path of execution.
- it enables you to write very efficient programs that make maximum use of CPU, as idle time can be kept to minimum.
While doing multithreading programming, you would need to have following concepts very handy:
- thread synchronization: when two or more threads need access to shared resource, they need some way to ensure that resource will be used by only one thread at time. Process by which this synchronization is achieved is called thread synhronization.
- inter thread communication: it is achieved through wait(), notify and notify all().
- thread deadlock: it occurs when two threads that have circular dependency on pair of synchronized objects.
- thread control: while suspend(), resume(), and stop() methods defined by thread class seem to be perfectly reasonable and convenient approach to managing execution of threads, they must not be used for new java programs.
Key to using multithreading is to think concurrently rather than serially. For ex, if you have two subsystems within a program that can execute concurrently, make them individual threads.
With careful use of mutithreading, you can create very efficient programs. Word of caution is in order. If you create too many threads, you can actually degrade performance of your program than enhancing it.
- it extends idea of multitasking with an application
- multithreading is running more than one
- 20 windows shortcuts?
- 20 unix commands?
Windows 3.1 is single threaded
Wndows 98/xp is multithreaded
We have 10 lines of code
In threading, we create seperate thread
Take some statements out of code and execute in parallel with the normal flow.
52) Thread is :
Flow of control in program
Use threads for isolated tasks
To do more than one tasks as time
Lighweight process
Ex: scrolling page while it is downloading an image or play animation or sound concurrently.
Performing calculations while printing pay checks
Disadvantage:
- Need to make thread safe. Java provides better way to handle this.
- Instance of class java.Lang.thread
- Thread of execution
53) Methods
- Start()
- Yield()
- Sleep()
- Run()
- isalive()
- yield()
- join()
- stop()
- suspend()
- resume()
Action happens in run method
54) Defining thread
- Extend java.Lang.thread class
- Implement runnable interface
Public class thread extends date implements runnable
If we extend thread, we cannot extend anything else
55) Thread life cycle
New
Runnable: thread.start() method is invoked
Blocked
Dead
56) Once thread has been started, it can be in (thread interaction methods)
- Wait()
- Notify()
- Notify all()
57) States
- Runnable: enters runnable state when start method is invoked
- Running: scheduler choose thread from runnable pool
- Waiting/ blocked/ sleeping thread is alive but is currently not eligible to run
- Dead: it is considered dead when it's run method completes
- Yield makes running thread to runnable
- Join let's one thread join on to end of another thread
58) Synchronization and locks
- There is one lock per object.
- If one thread has picked up the lock, no other thread can pick up the lock until first thread releases the lock
- Every object in java has built in lock that comes into play when object has synchronized method code
- Releasing lock means thread holding the lock exits the synchronized method
- Static methods can be synchronized
- Synchronized methods can be acceded by only one thread at a time
59) Thread safe classes
- when classes are carefully synchronized to protect it's data, we say the class is thread safe
- Deadlock occurs when two threads are blocked with each waiting for other lock
60) Advantage of synchronization
- Without synchronization, it is possible for one thread to modify the shared object while another thread is in process of using or updating that objects value
Disadvantage of synchronization
- It can cause deadlocks when two threads are waiting on each other to do something
61) Aggregation
- is part of whole relationship where part can exist without whole
62) Composition
- is part of whole relationship where part cannot exist without whole
63) Overloading
- multiple method in same class same name but different arguments.
- Let's you define same operation in different ways for different data.
64) Overriding
- two methods one in parent class and other in child class with same name and signatures.
- Lets you define same operation in different ways for different object types
65) Vector/ hash table
- are synchronized.
- Any method that touch their contents is thread safe.
Map
- static type of map
- is interface implemented by hash map
66) Hash map
- uses iterator to get information iterator.hasNext()
- permits null value
- dynamic type of map
- class that implements map
67) Hash table
- uses enumeration to get information enumeration.hasMoreElements
- Not permits null values
Array
- stores multiple variables of same type
68) Array list/ hash map
- if you don't need thread safe collection.
- Why pay price of synchronization unnecessary at expense of performance degradation
- As general rule prefer array list/ hash map over vector/hash table
69) Methods of object class
- Clone, to string, equals,hash code,wait, notify
Throw/ throws used to pass an exception to method that called it
70) Throw
- is used to throw user defined exceptions
71) Throws
- is used when we want that exception to be called by calling function
72) Try
- block of code that is tried but may cause an exception
73) Catch
- block of code which handles exception
74) Finally
- block of code that is always executed
75) Process
- is execution of program
- can contain multiple threads
Thread
- is single execution sequence within the process.
- Thread is sometimes called as lightweight process
76) Design patterns
77) - Iterator :
access elements of collection sequentially.
78) - Decorator java.io.* :
attaches responsibilities to objects at runtime
79) - Singleton:
is class instantiated only one time in JVM per class loader.
Use it only when you need single instance of an object required in memory for single point of access
80) - MVC:
separates model from presentation and logic that manages it
Advantages:
- Provides common design vocabulary
- Define the system structure better
- Capture design experience from the past
Inheritance
HAS A relationship:
Instance of operator:
Polymorphism
Interface
Abstract class
Final
Finalize method
Finally
Garbage collection
Static methods
Access modifiers: (public, private,protected, default)
Static variables
Instance variables
Local variable
Serialization
Tokenizing
Wrapper class
Exceptions hierarchy
Checked exceptions:
Unchecked exceptions:
Interprocess communication in Java
String
String buffer/ string builder
Hash code
Collections
collection
Collection
Lists
Comparator
Comparable
Enumeration
Iterator
Listiterator
Threads (java threads from orielly)
Multithreading
Methods
Defining thread
Thread life cycle
States
Synchronization and locks
Aggregation
Composition
Overloading
Overriding
1) Encapsulation
- mechanism that binds together code and data it manipulates
Advantages:
- modify our code without breaking the code of others.
- it gives maintainability, flexibility and extensibility to our code.
- The fields of a class can be made read-only or write-only.
- A class can have total control over what is stored in its fields.
- The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.
2) Inheritance
- is defined as process where one object acquires properties of another.
- information is made manageable in hierarchical order.
- allows code defined in one class to be used in another class
- IS A relationship in java is represented through keywords extends for class inheritance and implements for interface implementation
- Java supports single inheritance which means class cannot extend more than one class.
- java does not support multiple inheritance.
Public class dog extends mammal, animal{}
3) HAS A relationship:
- this determine whether certain class HAS -A certain thing.
- this helps to reduce duplication of code as well as bugs.
Public class vehicle {}
public class speed{}
Public class van extends vehicle{
Private speed sp;
}
This shows Van has a speed. By having separate class as speed, we do not have to put entire code of speed into van class, which makes it possible for speed class to be reused in multiple applications.
4) Instance of operator:
It is used to check whether mammal is an animal and dog is an animal
Interface animal{}
Class mammal implements animal{}
public class dog extends mammal{
Public static void main( String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instance of Animal);
System.out.println(d instance of Animal);
System.out.println(d instance of Mammal);
5) Polymorphism
- ability of object to take many forms is polymorphism.
- in java all classes are polymorphic by nature, since object will pass IS-A test for their own type and for class object.
- any java object passing more than one is a relationship
- Dogs sense of smell is polymorphic in nature
Public interface Vegeterian{}
Public class Animal{}
Public class deer extends Animal implements Vegeterian{}
Deer class is considered to be polymorphic since it has multiple inheritance.
Deer IS-A Animal
Deer IS-A Vegeterian
Deer IS-A Deer
Deer IS-A object
Polymorphism supports method overriding. It provides way for multiple inheritance.
6) Interface
- collection of abstract methods.
- 100% abstract superclass that defines the methods subclass must support but not how they must be supported.
- Can have only abstract methods.
- Less flexibility than abstract class as rules are strict
- No implementation code as all methods are abstract.
- Cannot have instance variables, constructors and can have only public and none visibility
- If you prefer to change your design frequently, use interface as opposed to abstract class
- Supports multiple inheritance
- Has only public members
- Interface with no defined methods act like markers
7) Interface different from class in following ways:
- you cannot instantiate an interface.
- interface does not contain any constructors
- All methods in interface are abstract
- interface cannot contain instance fields. Only fields that can appear in interface are static and final.
- interface can extend multiple interfaces.
Public interface Hockey extends sports, events{}
- interface is implemented by class.
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interface.
An interface can extend another interface, similarly to the way that a class can extend another class.
8) Abstract class
- class that is declared abstract
- may or may not include abstract methods
- cannot be instantiated but they can be subclassed.
- has executable methods and abstract methods
- Can only subclass one abstract class.
- Can have instance variables, constructors
- Does not support multiple inheritance
- Can contain private as well as protected members
- when abstract class is subclassed, subclass usually provides implementation for all of the abstract methods in the superclass.
- however if it does not, subclass must also be declared as abstract.
- if abstract class contains only abstract method declarations, it should be declared as interface instead.
Abstract class graphic object{
Int x,y;
Void moveTo(int newX, int newY);
}
abstract void draw();
Abstract void resize();
}
Class circle extends graphic object{
void draw(){}
void resize(){}
}
Class rectangle extends graphic object{
void draw(){}
void resize(){}
}
9) Final
- java class with final modifier is called final class in Java.
- Final class is complete in nature and cannot be subclassed or inherited.
- several classes in java are final. Integer, string and other wrapper classes.
- Is constant declaration.
Final class personal loan{}
10) Finalize method
- defined in java.Lang.object class.
- inside finalize method you specify those actions that must be performed before an object is destroyed.
- Used to save object from deletion.
- helps in garbage collection
- it is called just prior to garbage collection
Protected void finalize(){}
Here keyword protected is a specified that prevents access to finalize() by code defined outside it's class.
11) Finally
- handles exception
- block of code that is always executed after try/catch block has completed.
- will execute whether or not an exception is thrown.
- it can be used to
Close file handles
Freeing up any resources that might have been allocated at beginning of the method.
Finally is optional. However, try statement requires at least one catch or finally clause.
12) Garbage collection
- objects are created on heap in Java irrespective of their scope.
- garbage collection is mechanism provided by JVM to reclaim heap space from objects which are eligible for garbage collection.
- garbage collection in java is carried out by deamon thread called garbage collector.
- before removing object from memory, garbage collection thread invokes finalize() method of that object and gives an opportunity to perform an sort of cleanup that is required.
- it cannot be forced as it will trigger only when JVM thinks it needs a garbage collection based on Java heap size.
- there are methods like system.Gc() and runtime.Gc() which is used to send request of garbage collection to JVM without any guarantee.
- if there is no memory space for creating new object in heap, JVM throws outofmemoryerror or java.lang.outofmemoryerror heap space.
- Object eligible for garbage collection when no live thread can access it
- System.gc to force garbage collection
13) Access modifiers: (public, private,protected, default)
- public all classes from all package can have access to the public class
- private can't be accessed by code in class other than class in which private member was declared
- protected accessed by subclass even if subclass is in different package
- default accessed only if class accessing member belong to the same packag
Constructor has no return type and must match class name
14) Static methods
- scope of variables in static method is limited to that methods body. You cannot refer to the variable in one static method that is declared in another.
-multiple methods: you can define as many static methods as you want in .java file. These methods are independent.
- calling other static methods: any static method defined in .java file can call any other static method in same file or any static method in java lib like math
- overloading: static methods whose signature differs are different static methods. Using one name for two static methods whose signatures differ is known as overloading.
- single return value: like mathematical function, java static method can provide only one return value, of type declared in method signature.
- static method can use void as return type to indicate that it has no return type.
- cannot be overridden
- only one copy of static method for entire class
- cannot be declared as final or abstract
Public static double sqrt(double c)
15) Static variables
- Class variables are static variables. Static variables are used in singleton pattern.
- static variable belongs to java class and non static variable belongs to object class.
- static variables will keep same value for every object while non static variable varies from object to object.
- one static variable is shared between all objects in java.
- in multithreading environment, access to static variable must be synchronized or you will get unexpected behavior.
- it is not suggested to use static variable in multithreaded and concurrent application as it may create subtle bugs hard to find and debug.
16) Instance variables
- declared inside class outside any methods
- instance variables are created when an object is created with use of keyword new and destroyed when object is destroyed.
- recommended to make it private. Usually it are visible for all methods, constructors and block in the class.
- non static variables
- created and goes in heap memory
17) Local variable
- declared inside the method
- visible only within declared method, constructors and block.
- there is on default value for local variables so local variables should be declared and initial value should be assigned before first use.
- created and goes in stack along with primitive variables like int and double
18) Serialization
- object can be serialized on one platform and deserialized on entirely different platform.
- for class to be serialized successfully, two conditions must be met:
- class must implement java.io.serializable interface
- all of fields in class must be serializable. If field is not serializable, it must be marked transient.
Public class employee implements java.io.serializable
{
public string name;
Public string address;
Public int transient SSN;
public int number;
Public void mailCheck()
{
system.out.println("mailing a check to:" + name +""+ address);
}
- let's us save this object and all of it's instance variables
- can exclude field from serialization by using transient
19) Tokenizing
- taking big peices of data, breaking them into little pieces, and storing the little pieces in variables.
20) Wrapper class
- for every primitive in java. For int is Integer, float is Float.
21) Exceptions hierarchy
- Object
- Throwable
- Error, exception
- RuntimeException
22) Checked exceptions:
- beyond control of programs like
I/O exception,
remote exception,
SQLException
DataAccessException
Classnotfoundexception
Invocationtargetexception
- Handled by user during compile time.
- Called when resource we are looking for is not found( file missing or remote server is down)
23) Unchecked exceptions:
- are mostly programming mistakes.
- Runtime exceptions are unchecked exceptions which happens due to programmatic errors, wrong data etc.
- Handled by JVM.
Nullpointerexceptions
Arrayindexoutofboundexception
Illegalargumentexception
Illegalstateexception
24) Interprocess communication in Java
- System.in
- System.out
- System.err classes
25) String
- is immutable.
- Cannot modify string object but replace it by creating new instance.
26) String buffer/ string builder
- is mutable.
- Used to modify contents.
- Stringbuilder is not synchronized making it faster than string buffer.
- Classes used when lot of modification to be made to string of characters.
==
- compares references and equals compares contents
- compares two objects to determine if they are the same object in the memory.
27) Hash code
- increase performance of large collection of data.
- It tells in which bucket we need to look to find name.
- Amy and may has same hash code as they have same letters
- If two objects are equal then calling hash code method on each of the two objects must produce same integer results
28) Collections
- framework in java
- gives lists, sets, maps and queues to satisfy most of coding needs
29) collection
- data structure in which objects are stored and iterated over
30) Collection
- interface from which set, list and queue extend
Lists : list of things
Sets : unique things
Maps : things with unique I'd
Queues: things are arranged by order in which they are to be processed
31) Lists
- Array list :
- arraylist.add(1,"inserted element");
Copy elements of arraylist to array example:
- Object[] objArray=arrayList.toArray();
Get size of arraylist example:
- int totalElements=arrayList.size()
Get synchronized list from arraylist example:
- List list=Collections.
Java string array length example:
- int length= strArray.length
Maximum arraylist example:
- Object obj= Collections.max(arrayList);
Minimum arraylist example:
- Object obj= Collections.min(arrayList);
Remove all elements from arraylist example
- arrayList.clear();
Remove element from arraylist example
- Object obj= arrayList.remove(1);
Replace all array list example
- collections.replaceAll(
Replace an element using list iterator example
- listiterator.next();
- listiterator.set(100);
Replace element at specified index arraylist example
- arrayList.set(1,"replaced element");
Search an element in arraylist example
- boolean blnfound= arraylist.contains("2");
- int index= arrayList.indexOf("4");
If (index==-1)
system.out.println("arraylist does not contain 4")
Else
System.out.println("arraylist contains 4 at index:" +index);
Shuffle elements of arraylist example
- collections.shuffle(arraylist)
Simple array list
Sort array list in descending order
- comparator comp=collections.reverseorder(
System.out.println(" before sorting arraylist in descending order "+ arraylist)
Collections.sort(arraylist,
System.out.println("after sorting arraylist in descending order" + arraylist)
Sort java arraylist example
- collections.sort(arraylist);
fast iteration and fast random access.
Can grow dynamically.
Has more powerful insertion and search mechanism.
Arrays are very useful when working with sequence of same kind of data.
32) Comparator
ArrayCompare
- boolean[] blnarray1= new boolean[]{true, true, true};
boolean[] blnarray2= new boolean[]{true, false, true};
boolean blnresult= Array.equals(blnArray1,
Comparebytearrayexample
Comparechararrayexample
Comparedoublearrayexample
- defined in java.util package
- utility to sort objects
- public int compare(object o1, object o2)
- compare two object provided to him
33) Comparable
- defined in java.Lang package
- provided by default
- public int compareTo(object o)
- compares this reference with object specified
34) Enumeration
GetEnumerationOverArrayListExa
- Enumeration<String> e= Collections.enumeration(
System.out.println("
While(e.hasMoreElements())
System.out.println(e.
GetenumerationOverVectorExampl
- Enumeration e= Collections.enumeration(v);
System.out.println("
While(e.hasMoreElements())
System.out.println(e.
GetenumberationHashSetExample
- Enumeration e= Collections.enumeration(
System.out.println("
While(e.hasMoreElements())
System.out.println(e.
- Enumeration<String> e= ht.keys();
System.out.println("
While(e.hasMoreElements())
System.out.println(e.
- used for passing through collection of unknown size
- does not allow for modification of collections, thus iterator are used if this is required.
- has two options: nextElement() which returns next object in collection
HasMoreElements() which returns true until last object has been returned by nextElement()
35) Iterator
Iterate through arraylist using iterator example
- Iterator<string> itr= arraylist.iterator();
System.out.println("iterating through Arraylist elements");
While (itr.hasNext())
System.out.println(itr.next())
Iterate through elements of hashset example
- Iterator<integer> itr= hSet.iterator();
System.out.println("hashset contains ");
While (itr.hasNext())
System.out.println(itr.next())
Iterate through elements of linked hash set example
- Iterator<string> itr= lhashSet.iterator();
System.out.println("
While (itr.hasNext())
System.out.println(itr.next())
Iterate through elements of tree set example
- Iterator<string> itr= tSet.iterator();
System.out.println("TreeSet contains");
While (itr.hasNext())
System.out.println(itr.next())
Iterate through elements of java linkedlist
- Iterator<string> itr= lList.iterator();
System.out.println("iterating through linkedlist elements");
While (itr.hasNext())
System.out.println(itr.next())
Iterate through vector elements
- Iterator<string> itr= v.iterator();
System.out.println("iterating through vector elements");
While (itr.hasNext())
System.out.println(itr.next())
Iterate values of hash map example
- collection<string> c= hMap.values();
Iterator<string> itr= c.iterator();
System.out.println("iterating through Arraylist elements");
While (itr.hasNext())
System.out.println(itr.next())
Iterate values of hash table example
- enumeration<String> e=ht.elements();
While(e.hasMoreElements())
System.out.println(e.
Iterate through linkedhashmap example
- Iterator<string> itr= c .iterator();
System.out.println("iterating through linkedhasmap elements");
While (itr.hasNext())
System.out.println(itr.next())
Iterate values of tree map example
- Iterator<string> itr= c .iterator();
System.out.println("iterating through tree map elements");
While (itr.hasNext())
System.out.println(itr.next())
JavaIteratorExample
- Iterator<string> itr= aList.iterator();
System.out.println("iterating through Arraylist elements");
While (itr.hasNext())
System.out.println(itr.next())
Enables you to cycle through the collection, obtaining or removing elements
- HasNext
- Next
36) Listiterator
Iterate through vector using list iterator example
- ListIterator<String> itr= v.listIterator();
system.out.println("iterating through vector elements in forward direction..");
While(itr.hasNext())
System.out.println("itr.next()
System.out.println("iterating through elements in backward direction");
While(itr.hasPrevious())
system.out.println("itr.
Extends iterator and allows bidirectional traversal of list and modification of elements
HasNext
Next
Has previous
Previous
37) -Vector:
Add element to specified index vector example
- v.add(1, "INSERTED ELEMENT");
Append all elements of other collection to vector example
- v.addAll(array list);
Copy elements of array list to vector example
- collections.copy(v,arrayList);
Copy elements of vector to array example
- Object[] objArray= new Object[5];
v.copyInto(objArray);
Copy elements of vector to vector example
- collections.copy(v2,v1);
Get size of vector example
- int total elements= v.size();
Get sublist of java vector example
- List<String> lst= v.subList(1,3);
Insert all elements of other collection to vector
- v.addAll(1,arrayList);
Maximum vector example
- object obj = Collections.max(v);
Minimum vector example
- object obj= collections.min(v);
Remove all elements of vector example
- v.clear();
Remove element from vector by index example
- v.removeElementAt(2);
Replace element at specified index vector example
- v.set(1,"replaced element");
Set size of java vector example
- v.setSize(5);
same as array list except vector methods are synchronized for thread safety
Vector is an array with dynamic size
It increases , decreases it's size as you add/remove elements from it
Not as fast as array but is more efficient
38) - Linked list :
Add elements are start end linked list example
- lList .addFirst("0");
lList.addLast("6");
CheckelementLinkedListExample
- Boolean blnElement= lList.contains("4")
If(blnElement)
System.out.println("LinkedList contains 4");
Else
System.out.println("LinkedList does not contain 4");
GetFirst and Last LinkedList example
- system.out.println(" first element of LinkedList is : +lList.getFirst());
- system.out.println("last element of LinkedList is : +lList.getLast());
GetSublistLinkedListJava example
- List<String> lst = lList.subList(1,4);
LinkedList insert element example
- lList.add(2,2.5);
Remove all elements LinkedList example
- lList.clear();
Remove element LinkedListExample
- Boolean isRemoved = lList.remove("2")
- object obj= lList.remove(2);
Remove first last element LinkedList example
- object obj= lList.removeFirst();
- object = lList.removeLast();
Remove range elements LinkedList example
- lList.subList(2,5). Clear();
allows duplicates
ordered by index position like array list except that elements are doubly linked to one another.
Good choice for fast insertion and deletion
39) Sets
Cares about uniqueness and it doesn't allow duplicates
40)- Hash set :
Check element hash set example
- Boolean blnExists= hSet.Contains(new Integer("3));
System.out.println("3 exists in hash set?; " +blnExists);
Copy elements of hash set to array
- Object [] obj= hSet.toArray();
GetSize of Java HashSet example
- system.out.println("size of hash set after addition: " +hSet.size());
Get synchronized set from hash set example
- set<object> set = Collections. SynchronizedSet(hashSet);
Maximum hash set example
- object obj = Collections.max(hashSet);
Minimum hash set example
- object obj = Collections.min(hashSet);
Remove all elements from hash set example
- hSet.clear()
Remove specified element from hashSet example
- boolean blnRemoved= hSet.remove(new integer("2"));
Does not allow duplicates
unsorted, unordered set
Implementation of set interface
Objects in hash set must override equals and hash code method to check for equality
41) - Linked hash set :
Check element linked hash set example
- Boolean blnExists = lHashSet.contains(new integer("3"));
System.out.println("3 exists in LinkedHashSet" +blnExists);
Copy elements of LinkedHashSet to array
- Object[] objArray= lHashSet.toArray();
Get size of LinkedHashSet example
- lHashSet.size());
Remove all elements from LinkedHashSet example
- lHashSet.clear();
Simplelinkedhashset example
does not allow duplicates
maintains doubly linked list across elements.
Use this instead of hash set when you care about iteration order
Iterate in order in which elements are inserted in the set
42) - Treeset :
Check Value of tree set example
- Boolean blnExists= tSet.contains("3");
Copy elements of tree set to array example
- Object[] obj= tSet.toArray();
Get head set from tree set example
- sorted set<string> sortedSet= tSet.headSet("3");
Getlowesthighestvalue tree set example
- tSet.first()
- tSet.last()
Get size of java tSet example
- tSet.size();
Get subset from tree set example
- sorted set<string> sset= tSet.subset("2","5");
Get synchronized set from tree set
- set set= collections.synchronizedSet(
Get tail set from tree set
- sortedSet<String> sortedSet= tSet.tailSet("2");
Remove all elements from tree set example
- tSet.clear();
Remove specified element from tree set example
- boolean blnRemoved = tSet.remove(new Integer("2"));
Does not allow duplicates
one of the two sorted collections
Implements sorted set to maintain entries in ascending order
43) Map: unique Ids
Maps unique key to specific value where key and value are objects
44) - Hash map :
Check value of HashMap example
- boolean blnExists= hMap.ContainsKey("3");
Check value of HashMap example
- boolean blnExists= hMap.containsValue("one");
Empty HashMap example
- hMap.clear();
Get set view of keys from HashMap example
- set<string> st= hMap.keySet();
Get size of HashMap example
- hMap.size();
Get synchronized map from HashMap example
- Map map= Collections.synchronizedMap(
Remove value from HashMap example
- Object obj = hMap.remove("2");
unsorted unordered map.
Allows one null key and multiple null values
Not synchronized
Does not guarantee order in which entries are placed.
It can change completely when new elements are added
Better performance than the LinkedHashMap as LinkedHashMap needs expense of maintianing the linked list.
45) - Hash table :
Check key of hash table example
- Boolean blnexits = ht.contains key("2");
Check value of hash table example
- boolean blnExists = ht.contains("Two")
Create hash table from HashMap
- ht.putAll(hMap);
Empty hash table example
- ht.clear();
Get collection of values from hash table example
- Collection<String> c= ht.values();
Get size of hash table example
- ht.size();
SimplehashtableExample
key value pairs in descending order
Does not allow duplicates
synchronized version of hash map
Data inserted using put method
Hashing function analyses key and returns index number
46) - LinkedHashMap:
Check key of linked HashMap example
- Boolean blnExists= lhashmap.containsKey("3");
Check value of linked hash map
- boolean blnExists= lHashmap.containsValue("two");
Empty linked hash map
- lhashmap.clear();
Get size of linked hash map
- lHashMap.size();
Remove value from linked HashMap example
- object obj = lHashMap.remove("2")
faster iteration
Iterate in order in which entries were put in the map
47) - Tree map :
Check key of tree map
- boolean blnExists= treeMap.containsKey("1")
Check value of tree map example
- boolean blnExists = treeMap.containsValue("three")
Empty tree Map
- treeMap.clear()
Get head map from tree map example
- sortedMap<string,string> sortedMap= treeMap.headMap("3");
Get lowest highest key tree map
- treeMap.firstKey()
- treeMap.last key()
Getsetview of keys from treeMap
- set<string> st= treeMap.keySet();
Get size of tree map example
- treeMap.size();
Get sub map from treeMap example
- SortedMap<string,string> sortedMap= treeMap.subMap("2","5");
Getsynchronizedmapfrom treeMap
- Map map= Collections.synchronizedMap(
Get tail map from treeMap example
- sortedMap<String,String> sortedMap= treeMap.tailMap("2");
Java tree map example
Remove values from treeMap example
- Object obj= treeMap.remove("2");
Implements sorted map which maintains it's entries in ascending order
It extends abstactmap
48) Queue FIFO
- Priority queue
create priority in priority out queue.
Elements are ordered according to natural ordering or according to comparator
Comparable interface
- used by collections.sort method and java.utils.arrays.sort method to sort list array of objects respectively.
- To implement comparable class must implement single method compareTo
49) Threads (java threads from orielly)
Create thread runnable example
Public class createthreadrunnableexample implements Runnable{
public void run() {
for ( int I=0; I<5; I++)
system.out.println("child thread:" +I);
Try {
Thread.sleep(50);
}
Catch(InterruptedException ie){
System.out.println("child thread interrupted" +ie);
}
System.out.println("child thread finished");
Public static void main (string[] args) {
Thread t= new Thread(new CreateThreadRunnableExample, "My Thread");
T.start();
For (int I =0; I<5; I++)
system.out.println("main thread:" +I);
Try {
thread.sleep(100);
}
catch(InterruptedException ie) {
system.out.println("child thread interrupted" +ie);
}
}
system.out.println("main thread finished");
Get current thread example
Public class GetCurrentThreadExample{
public static void main(String[] args){
Thread currentThread = Thread.currentThread();
System.out.println(
}
- Better performance
50) Mutlitasking:
- ability of OS to run more than one program or task at a time.
51) Multithreading
- java has built in support for multithreaded programming
- multithreaded program contains two or more parts that can run concurrently.
- each part of such a program is called a thread and each thread defines separate path of execution.
- it enables you to write very efficient programs that make maximum use of CPU, as idle time can be kept to minimum.
While doing multithreading programming, you would need to have following concepts very handy:
- thread synchronization: when two or more threads need access to shared resource, they need some way to ensure that resource will be used by only one thread at time. Process by which this synchronization is achieved is called thread synhronization.
- inter thread communication: it is achieved through wait(), notify and notify all().
- thread deadlock: it occurs when two threads that have circular dependency on pair of synchronized objects.
- thread control: while suspend(), resume(), and stop() methods defined by thread class seem to be perfectly reasonable and convenient approach to managing execution of threads, they must not be used for new java programs.
Key to using multithreading is to think concurrently rather than serially. For ex, if you have two subsystems within a program that can execute concurrently, make them individual threads.
With careful use of mutithreading, you can create very efficient programs. Word of caution is in order. If you create too many threads, you can actually degrade performance of your program than enhancing it.
- it extends idea of multitasking with an application
- multithreading is running more than one
- 20 windows shortcuts?
- 20 unix commands?
Windows 3.1 is single threaded
Wndows 98/xp is multithreaded
We have 10 lines of code
In threading, we create seperate thread
Take some statements out of code and execute in parallel with the normal flow.
52) Thread is :
Flow of control in program
Use threads for isolated tasks
To do more than one tasks as time
Lighweight process
Ex: scrolling page while it is downloading an image or play animation or sound concurrently.
Performing calculations while printing pay checks
Disadvantage:
- Need to make thread safe. Java provides better way to handle this.
- Instance of class java.Lang.thread
- Thread of execution
53) Methods
- Start()
- Yield()
- Sleep()
- Run()
- isalive()
- yield()
- join()
- stop()
- suspend()
- resume()
Action happens in run method
54) Defining thread
- Extend java.Lang.thread class
- Implement runnable interface
Public class thread extends date implements runnable
If we extend thread, we cannot extend anything else
55) Thread life cycle
New
Runnable: thread.start() method is invoked
Blocked
Dead
56) Once thread has been started, it can be in (thread interaction methods)
- Wait()
- Notify()
- Notify all()
57) States
- Runnable: enters runnable state when start method is invoked
- Running: scheduler choose thread from runnable pool
- Waiting/ blocked/ sleeping thread is alive but is currently not eligible to run
- Dead: it is considered dead when it's run method completes
- Yield makes running thread to runnable
- Join let's one thread join on to end of another thread
58) Synchronization and locks
- There is one lock per object.
- If one thread has picked up the lock, no other thread can pick up the lock until first thread releases the lock
- Every object in java has built in lock that comes into play when object has synchronized method code
- Releasing lock means thread holding the lock exits the synchronized method
- Static methods can be synchronized
- Synchronized methods can be acceded by only one thread at a time
59) Thread safe classes
- when classes are carefully synchronized to protect it's data, we say the class is thread safe
- Deadlock occurs when two threads are blocked with each waiting for other lock
60) Advantage of synchronization
- Without synchronization, it is possible for one thread to modify the shared object while another thread is in process of using or updating that objects value
Disadvantage of synchronization
- It can cause deadlocks when two threads are waiting on each other to do something
61) Aggregation
- is part of whole relationship where part can exist without whole
62) Composition
- is part of whole relationship where part cannot exist without whole
63) Overloading
- multiple method in same class same name but different arguments.
- Let's you define same operation in different ways for different data.
64) Overriding
- two methods one in parent class and other in child class with same name and signatures.
- Lets you define same operation in different ways for different object types
65) Vector/ hash table
- are synchronized.
- Any method that touch their contents is thread safe.
Map
- static type of map
- is interface implemented by hash map
66) Hash map
- uses iterator to get information iterator.hasNext()
- permits null value
- dynamic type of map
- class that implements map
67) Hash table
- uses enumeration to get information enumeration.hasMoreElements
- Not permits null values
Array
- stores multiple variables of same type
68) Array list/ hash map
- if you don't need thread safe collection.
- Why pay price of synchronization unnecessary at expense of performance degradation
- As general rule prefer array list/ hash map over vector/hash table
69) Methods of object class
- Clone, to string, equals,hash code,wait, notify
Throw/ throws used to pass an exception to method that called it
70) Throw
- is used to throw user defined exceptions
71) Throws
- is used when we want that exception to be called by calling function
72) Try
- block of code that is tried but may cause an exception
73) Catch
- block of code which handles exception
74) Finally
- block of code that is always executed
75) Process
- is execution of program
- can contain multiple threads
Thread
- is single execution sequence within the process.
- Thread is sometimes called as lightweight process
76) Design patterns
77) - Iterator :
access elements of collection sequentially.
78) - Decorator java.io.* :
attaches responsibilities to objects at runtime
79) - Singleton:
is class instantiated only one time in JVM per class loader.
Use it only when you need single instance of an object required in memory for single point of access
80) - MVC:
separates model from presentation and logic that manages it
Advantages:
- Provides common design vocabulary
- Define the system structure better
- Capture design experience from the past
No comments:
Post a Comment