Category Archives: Programming Reference

Collection Framework

Collections (DurgaSoft Notes)

Arrays and ArrayList (Strengths and Limitations)

  • Arrays –> Homogeneous data elements (Resolve by using Object.arrays)
Object[] o = new Object[1000]; //FIXED SIZE!!
  • Arrays are not implemented on any standard data structure and hence no readymade method support

9 Interfaces (6 in Collection, 3 in Map).
Screen Shot 2015-01-24 at 4.15.39 PM
Maps are not the Part of Collection Framework

Screen Shot 2015-01-24 at 4.16.11 PM

  1. Collection (Interface) : Most Common method
    • Collections is a utility Class
    • Collection is an interface
    • An interface give high level view of all the methods (no implementation).
  2. List
    • Child Interface if Collection
    • Duplicate values are allowed
    • Insertion Order is preserved
    • Screen Shot 2015-01-24 at 3.37.19 PM
    • Vectors and Stack are called Legacy Classes as they are from older version
  3. Set
    • Duplicates are not allowed
    • Insertion Order not Preserved
    • Set →HashSet →LinkedHashSet
  4. SortedSet (I)
    • Collection →Set →SortedSet → NavigableSet (TreeSet class is the implementation) (v 1.2)
    •  Elements are inserted in sorted order
  5. NavigableSet (I)
    • Child Interface of Sorted Set
    • TreeSet Class Provides the Implementation
  6. Queue (I)
      • Screen Shot 2015-01-24 at 3.57.26 PM

    All Above keeps groups of objects. For Key value pairs, Maps(I) is used. (Not in Collection Framework)

  7. Map (I), not in Collection
    • key –> Duplicate not Allowed
    • Value –> Duplicates allowed
    • Screen Shot 2015-01-24 at 4.07.33 PM
  8. SortedMap(I)
    • Map(I) →SortedMap
  9. NavigableMap
    • Map(I) →SortedMap → NavigableMap(I) (TreeMap is the Implementation Class)
    • Screen Shot 2015-01-24 at 4.13.07 PM

Cursors in Java

  1. Enumeration
  2. Iterator
  3. List Iterators

Sorting

  1. Comparable(I) : Default natural sorting order
  2. Comparator(I) : Customized Sorting

Utility Classes

  1. Collections
  2. Arrays

Collection(I)

  • Collection(I) is the root interface of Collection Framework.
  • Collection(I) defines the most common methods which are applicable for any collection object.
    • boolean add(Object o) , addAll(Collection c)
    • boolean remove(Object o) , removeAll(Collection c)
    • void clear()
    • boolean retainAll(Collection c) To remove all objects except those present in c
    • boolean contains(Object o), containsAll(Collection c)
    • boolean isEmpty()
    • int size(); be careful..not length()
    • Object[] toArray(); Object is the return type
    • Iterator iterator(); it take one by one
    • Since Collections are meant to be transfered over network, thus each collection implements Serializable & Cloneable Interface
  • Collection Interface DOES NOT contain any method to retrieve objects. There is no concrete class which implements collection class directly.

1. List(I)

  • All the methods of Collection(I) are available
  • addAll(int index, Collection c) //Add a list from index i onwards
  • indexOf(Object o); first occurrence (Just like Arrays)
  • get(int index)
  • ListIterator listIterator()
  • set(int index, Object o)

A. ArrayList(Implementation Class of List)

  • Underlying Data Structure : Resizable Array ()
  • Heterogeneous Objects are allowed
  • Only TreeSet and TreeMap does not allow heterogeneous objects as the Objects are in sorted order which is achieved after COMPARING homogeneous objects

Constructors

  • ArrayList al = new ArrayList();
    //Creates an empty arraylist with initial capacity of 10 elements. after that

new capacity = current capacity * (3/2) + 10

  • ArrayList al = new ArrayList(int initial_capacity)
  • ArrayList al = new ArrayList(Collection c)
  • sop(i) == sop(l.toString) ==> o/p [A, 10, A, null]

Only ArrayList and Vector classes implements RandomAccess Interface (java.util) (so that any random element can be accessed in same time/speed). RandomAccess doesn’t contain any method. Its a Marker Interface

Thus if frequent operation is RETRIEVAL, ArrayList is the best choice. For add, remove, its worst(lost of shifting if addition is done in the middle of ArrayList)


Difference between ArrayList and Vector

ArrayList Vector
all methods are non-synchronized most of the methods are synchronized
Not thread safe Thread safe (Only one thread can access)
Performance is relatively high Relatively Low Performance

Synchronized version of ArrayList Obj.

ArrayList al = new ArrayList();//non Synchronized
List l = Collections.synchronizedList(al);

public static List synchronizedList(List l)
public static Set synchronizedSet(Set s)
public static MAp synchronizedMap(Map m)


B. LinkedList (Detailed)

  • Underlying Data Structure : Doubly Linked List
  • frequent insertion or deletion [O(1)] //Best Choice
  • Worst for retrieval (due to linear probing of the list)
  • Implements Serializable and Cloneable but not RandomAccess Interface

Methods (Only for Linked List)

  • addFirst, removeFirst(), getFirst()
  • addLast(), removeLast(), getLast()
  • These methods can be used for Implementing Stack or Queue using Linked List

C. Vector

vector specific methods (long method name, the burden of Legacy class)

  • addElement(Object o)
  • removeElementAt(), removeAllElements
  • int capacity
  • initialized with 10 element, and then new capa = cc*2

D. Stack

  • Child of Vector
  • LIFO
  • Only one Constructor Stack s = new Stack();
  • Methods
    • push(Object o);
    • pop();
    • peek();
    • empty() [doe to Legacy, isEmpty() is not available]
    • boolean search(Object 0);//returns offset (return the no. from top), -1 for not found

Three cursors of JAVA

  1. Enumeration (Interface)
  2. Iterator (I)
  3. ListIterator (I)

1. Enumeration

Enumeration e = v.elements
**(v is vector, Only for Legacy Class)
**Has only two methods—boolean hasMoreElements(); & Object nextElement();(type casting is required)

  • Remove is not possible

2. Iterator

  • Universal Cursor (Applicable to any Collection Class)
  • read and remove both are possible

Iterator itr = c.iterator();
Where c is any collection object

Methods: 

  1. public boolean hasNext();
  2. public Object next();
  3. public void remove(); //not in Vector

Example : Program to remove odd elements from an ArrayList

ArrayList l =new ArrayList();
for (int i = 0; i < 10; i++){
     l.add(i);
}
Iterator itr = l.iterator();
while (itr.hasNext()){
   Integer n = (Integer)itr.next();//type casting is required as next() returns an Object type
   if(n%2 != 0)
    itr.remove();
}//end While

Limitation of Iterator

  • Only forward direction cursor
  • no replace and no addition of new object.

3. ListIterator (Child of Iterator, most powerful)

  • Bidirectional cursor
  • read, remove, replacement, addition of new operation
  • ListIterator itr = l.listIterator(); l is any List Obj (AR, LL, Vector or Stack

Methods:(9 in total)

  • boolean hasNext(), Object next(), int nextIndex() //FORWARD DIRn
  • boolean hasPrevious, Object previous(), int previousIndex() //BACKWARD DIRn
  • public void remove()
  • public void set(Object new)
  • public void add(Object new)

ONLY APPLICABLE FOR LIST OBJECTS


Implementation class for the three cursors

Enumeration e = v.elements();

System.out.println(e.getClass().getName());//Vector $1 -> $ = inner class, 1 anonymous inner class


2. Set(I)

  • Duplicates are not allowed
  • Set Interface doesn’t contain any new methods. So Only Collection interface methods are to be used.

A. HashSet (Implementation Class)

  • Underlying DS – HashSet
  • No Duplicates allowed (No exception thrown, but add() method returns false)
  • Insertion order is not preserved. Saved based on Hash code.
  • Best Choice for Search operation

Constructor

  • HashSet h = new HashSet(); initial capa: 16 and field ratio/load factor 75%
  • Field Ratio (after filling 75% new HashSet will be created), can be set through a constructor

B. LinkedHashSet (Implementation Class)

  • Child class of HashSet.
  • Underlying Data Structure : Linked List + Hash Table
  • To preserve Insertion order
  • Cache based Application

 

C. SortedSet (Implementation Class)

Specific methods

  • first(), last() –> not in the normal set
  • headSet(Object o), elements lessthan 0
  • tailSet(Obj o)
  • subset(o1, o2))
  • Comparator comparator()

D. TreeSet

  • Underlying DS : balanced Tree
  • Sorting order
  • NULL Acceptance only once (as its a set)

Constructor

  1. TreeSet t = new TreeSet(); //Default Natural Sorting Order
  2. TreeSet t = new TreeSet(Comparator c)//Customized sorted order
  • To insert NULL in a non empty TreeSet –> NullPointerException (conparison fails)
  • Heterogeneous elements are not allowed because they can’t be compared.
  • Null Acceptance :
    • After adding some elements, null pointer exception (no comparison)
    • In the beginning (empty tree set), it can be, but other elements gives null pointer exception.

TreeSet Details

  • StringBuffer Objects are not comparable because it does not implements Comparable Interface. Thus cannot be used to insert elements into TreeSet with Default Natural sorting order.
  • String Class and all other Wrapper Classes implements comparable Interface.
  • Comparable Interface, present in lang Package, has only one method compareTo()
  • public int compareTo(Object obj)
    • obj1.compareTo(obj2)
      • -ve, iff obj1 comes before obj2 (Default Natural Sorting Order)
      • +ve, iff obj1 comes afterobj2
      • 0, iff both onjects are equal.
    • Example: sop(‘A’.compareTo(‘B’));//-25
  • JVM calls compareTo() method before inserting into TreeSet.
  • Comparator Interface is meant for CUSTOMIZED sorting order, while Comparable(I) id for DNSO

Comparator (I) :

  • Customized Sorting Oder
  • java.util Package
  • two methods compare() and equals()[Dummy method, present in Object Class, access through inheritance.
  • public int compare(Object obj1, Object obj2);
    • -ve, iff obj comes before obj2, 0 for equal, +ve otherwise
  • Example code for Implementing Comparator (Add ints in Decreasing order)
 
    class testComparator implements Comparator{
         public int compare(Object obj1, Object obj2){ //provide
             Integer i1 = (Integer) obj1;//type casting to be sure of int
             Integer i2 = (Integer) obj2;
             //For Strings
           /*String s1 = (String) obj1;//Type casting
             String s2 = obj1.toString();
             return -s1.compareTo(s2);//Reverse alphabetical order
             return s2.compareTo(s1);//Also Reverse sorted
           */
     //For decreasing order, return -ve when obj1 > obj2
             if (i1 > i2) 
                  return -1;
             else if (i1 < i2)
                  return 1;
             else
                 return 0;
         }
    // Tweek
    return i1.compatrTo(i2);// Ascending order
    return i2.compareTo(i1);// Decreasing order
    return -i1.compareTo(i2);// Decreasing Order
    return 1; // Insertion order
    return -1; //reverse insertion order
    return 0; //only first element is inserted and all other are considered as duplicates
    }

    TreeSet t = new TreeSet(new testComparator);
    t.add(100); t.add(20); 

  • For StringBuffer Class (not comparable), a Comparator has to be defined.
  • For predefined comparable Classes, DNSO is already available. (Comparators can be used to custom sorting order)
  • For predefined non comparable Classes (like StringBuffer), compulsorily compactors to be used.
  • For our own classes, Developer is responsible for DNSO. For the users of the class, they can use compactor for customized sorting order.

Comparable Compartator
 java.lang (for DNSO)  java.util (Customised)
 one method compareTo()  two mwthods compare() and equals()
 All Wrapper + String Implements it  Collator and RuleBasedCollator (only two classes)

  • Generics included in Java 1.5 to provide safety and type casting problems.
  • Arrays are type safe by default but Collections object are not. No compile time errors if inserting int in  String arraylist defined without using Generics.
  • if Generics are not used, type casting is mandatory at the time of retrieval
ArrayList l = new ArrayList();
l.add("Nitin");
//String s = l.get(0);// incompatible type found exception
String s = (String) l.get(0);

Method Reference

int[] nums => nums.length;
String str => str.length();
ArrayList<Integer> a => a.size();

Boolean Logic (if statement, switch)

return (a > b && (a-b) >= 2);
         is equivalent to 
if (a > b && (a-b) >= 2){         
    return true; 
}

For Loop Traps

  • for (int i = 0; i < arr.length; i = i+2){ …} // if lenght = 9, loop will run 0,2,4,6.. 8 is never included.
  • for (int i = 1; i < num.length; i++) if (num[i-1] == num[i]) return true;
  • for (int i = 0; i < num.length – 1; i++) if (num[i] == num[i+1]) return true;
  • for (char i = ‘a’; i <= ‘z’; i++){ sout(i); //Prints alphabets from ‘a’ to ‘z’ }

Arrays

  1. int[] a; 
    a = new int[3]; //notice []. NOT () to be used
  2. int[] a = new int[3]; //single line declaration
  3. a.length ; //Length is a "field" in Array, while a method in Strings
  4. int[] a = new int[] {1,2,3};
  5. int[] b = {1,2,3};
  6. sysout(Arrays.toString(num));

The Arrays Class

Import java.util.ArrayList;

  • ArrayList<Integer> b = new ArrayList<Integer>;
  • Arrays.toString(a);//o/p [1,2,3]
  • Arrays.asList(a);
  • Arrays.asList.contains("a");//boolean true/false

String Functions (Most Important)

  1. + ⇒ concatenation
  2. str.chatAt(i);
  3. str.length(); //Method in String, Field in Arrays;
  4. str.substring(i,j);//j not included
  5. str.substring(i);//from i till end str.substring(i,str.length());String Index begins from ZERO, thus lenght = max Index + 1
  6. For Equality str.equals();//DO NOT USE == (will compare objects)
  7. str.indexOf("er");//2 if "er" begins from index 1, -1 if not Found
  8. str.indexOf("er", 2); //start the search from index 2
  9. str.lastIndexOf("ew");//searches right to left
  10. str.lastIndexOf("ew", 5);//right to left, from index 5
  11. str.toLowerCase() / str.toUpperCase()
  12. str.compareTo("");
  13. str.replace("old","new");
  14. String[] ransomWords = ransom.split(" ");//Cut the Strings from spaces into a words

Java Input

Key Board Input

import java.util.Scanner;
Scanner in = new Scanner(System.in);
 int n = in.nextLine();
 in.nextLine(); //To avoid INPUT Problem
 String str = in.nextLine();
/* Input Problem occurs when a mix of int and strings are given
 The extra invocation is done to get rid of previous \n 

16\n 1000\n Joe\n
/n Extra in.nextLine()
 in.nextInt; //reads next integer
 in.nextDouble();
 in.nextLine();//reads entire line of in
 in.next();//next character upto but not including space
/* NO METHOD TO READ A SINGLE CHARACTER */
 char a = in.nextLine.charAt(0);

File Input

//Open the File
File myFile = new File("/nitin/a.txt");
 Scanner in = new Scanner(myFile; //Instead of System.in, take the file to read
//Read from the File
 String str = in.nextLine();
//OR
 while (in.hasNext());
 System.out.println(in.nextLine());
 //Close the File
 in.close();

Output File Handling

Writing text to File
import java.io.PrintWriter;
 final String FILENAME = "nitin.txt";
//Surrounding with try catch!! OR
 PrintWriter output = new PrintWriter(FILENAME); 
 PrintWriter output = new PrintWriter("nitin.txt");
output.println("Nitin"); output.println("Chaurasia");
//To avoid erasing files that already exist
 PrintWriter pw = new PrintWriter(new FileWriter("nitin.txt", true));
Appending Text to file
FileWriter fw = new FileWriter("Names.txt", true);
PrintWriter pw = new PrintWriter(fw);

OR

PrintWriter pw = new PrintWriter(new FileWriter("Names.txt, true"));
Reading Data from a file
File myFile = new File("customer.txt");
Scanner ipFile = new Scanner(myFile); //instead of System.in

Reading, Parsing and Type Checking Command Line Inputs.

/*Assuming 2 command line arguments <Nitin 29>*/

if (args.length == 0 || args.length > 2) {
     System.err.println("Incorrect Number of arguments passed");
     System.exit(-1);
  }
String name = args[0];
  int age = Integer.parseInt(args[1]);

Running time of a method

System.currentTimeMillis();//type long , from Jan 1 1970 
System.nanoTime();

Random

import java.util.Random

  • Random generator = new Random(); //or new Random(123), 123 being the seed
  • generator.nextInt(5);//range 0 to 5, add 1 to get range 1 to 6 (dices)
  • generator.nextInt(); // 2^31 to 2^31 -1
  • generator.nextDouble();//Range: 0.0 to 1.1

Eg: int throw = generator.nextInt(6) + 1;

Array and Linked List

Capture
 
 for (int i = 0; i < arr.length; i++){
      System.out.prinln(arr[i]);
 }
 for (ListNode runner = head; runner != null; runner = runner.next){
      System.out.println(runner.data);
 }

Linked List

 LinkNode runner = front;//head
 while (runner.next != null){//Runner stops at the last node, else runner will end up pointing null!!
 runner = runner.next;

Add in the List

    1. Add in the front

front = new ListNode(value, front);

    1. Add at ‘index’
if (index == 0)
front = new ListNode(value, front);
else{
ListNode runner = front;
for (int i = 0; i < index - 1; i++)//Stop at an index one before the desired
current = current.next;
}
current.next = new ListNode(value, current.next); //old current.next is assigned to the new node which in turn is assigned to current.next
    1. Add in the end

if (front == null)
  front = new ListNode(value, front);
else{
  ListNode runner = front;
  while (runner.next != null) // Go till the last node
      runner = runner.next;
  runner.next = new ListNode(value); //this constructor has .next as null  
}

For Each Loop (Read Only Loop)

for (type name : collection){
 }
Eg: Set<Double> grades = new HashSet<Double>();
for (double g: grades){
   System.out.println(g);
 

Iterator itr (for some collection)

Iterator itr = c.iterator();
 itr.remove(i);
 itr.hasNext();
 itr.next();

The XOR Trick

  • Same variables cancels the effect of each other if the bitwise XOR is used.


a = a^b;
b = a^b; //a^b^b yields a
a = a^b;//a^b^a = b(b is recently converted to a)
(Works only with integer, in its native form, for others change it into its equivalent binary representation)
The logic is used for finding a unique element among duplicates (Stolen Drone problem (21) in Interview cake)

  • Use of XOR (both flags are boolean)


if (flag2 ^ flag4)
is equivalent to
(flag2 && !flag4) || (!flag2 && flag4);

HashMap

Map<String, Integer> ret = new HashMap<String, Integer>();
for (int key : map.keySet()){
ret.put(map.get(key),key);
}

ArrayList

  • Declaration (Child of List Interface)

ArrayList<Integer> list = new ArrayList<Integer>();
List<Integer> list = new ArrayList<Integer>();

  • Insert element

for (int i = 0; i < list.size(); i++){
list.add(i);
list.get(i);
}

  • Common methods

add(value), add(index, value)
set(index. value)
clear()
indexOf(value)
lastIndexOf()
toString(), toArray();

HASHMAP (IMPLEMENTATION OF HASHTABLE)

Map<String, Integer> ret = new HashMap<String, Integer>();
for (int key : map.keySet()){
ret.put(map.get(key),key);

Server Virtualization

Understanding Networking and Server Visualization

Introduction to Virtualization
Virtualization and Cloud Computing are not same. Its a component of Cloud Computing.

In virtualization there is a separation of OS with the underlying H/W where as in Cloud Computing (CC), there is a separation of Application from the underlying hardware.

  • Earlier, OS’s are installed directly on the hardware.
  • Virtualization gives a layer of hypervisor, on which an “instances” of OS runs.
  • install a hypervisor layer and then install the “Guest OS”
  • Can literally move (copy an image and paste) one instance of OS from one server to another without any installation!!
  • Also, multiple instances of OS can be installed on hypervisor

Type 1 Hypervisor (Native or Bare Metal) : A physical machine, and hypervisor on it.

Type 2 Hosted hypervisor : Comp. with an OS, and onto that hypervisor is installed eg :VMWare (installed according to the OS). Onto it guest OS are installed

Hosted solutions (Proprietary ones) on Amazon Cloud etc.


you need a management console to interact with hypervisor(once the physical server has an IP address). With the management console, you can move the instances of OS’s among different physical servers.

Also, according to resource needs, management console can migrate (or turn on and off) based on loads (balances the electricity consumption)

If the physical hardware running the hypervisor fails, management console can quickly migrate the OS to another hardware.

Over Allocation :  static (RAM is split between all the OS instances) and
dynamic (logical allocation more than the physical)

Most of the hypervisor software are free (most of them based on XEN) but they charge for the management console software.

Careful with type 2 Hypervisor : Be careful of the resource allocation. if 4 GB’s of RAM is allocated, the type 2 virtualization hypervisor will take all 4 GB and allocate to the VM even if its not needed. Can crash host OS by overallocating its hardware resources.

Java interview Questions

  1. final
    • constant –> modifier (can’t be changed once declared)
    • a method –> no over riding in child class
    • a class –> no extend (inheritance), no child class
  2. finally (Associated with try catch block)
    • try {keep risky code}
    • catch (Exception e) {Handling Code}
    • finally {Clean up code}
  3. finalize() : Method in Object Class
    • Always invoked by Garbage Collector just before destroying the object
    • to perform cleanup activities (like database connection close, socket close)
  4. *** finally cleanup activities for try catch, finalize() cleanup activities for related to objects.

  1. String objects are immutable (every equality with string object creates a new object)
    • String a = “Nitin”; a.concate(Chaurasia);
    • sop(a);// Nitin
    • 2 strings are created (Nitin and Nitin Chaurasia). NC not referenced
  2. StringBuffer objects are mutable
    • StringBuffer sb = new StringBuffer(“Nitin”);
    • sb.append(“Chaurasia”)
    • sop(sb);//nitin chaurasia
  3. StringBuffer (since java 1.0)
    • Synchronized, thus thread safe, thus low performance (only one thread operates on the object at a time, others has to wait)
  4. StringBuilder (from 1.5)
    • same as StringBuffer (constructors and methods) except…
    • non-synchronized, thus no thread safety, thus Relatively high performance.
  5. Conclusion :
    • String : fixed content (wont change frequently)
    • StringBuffer : content not fixed and thread safety is required.
    • StringBuilder : content not fixed and thread safety is NOT required.

  1. == reference comparison (address comparison)
  2.  .equals() is used for content comparison (in general). Can be overridden to comp. ref. if needed
  3. All Wrapper Classes + String Classes, .equals() is overridden for content comparison

Modifiers in java : https://www.youtube.com/watch?v=1MmietzIteA&list=PLYPjPMiw3_YsVockWfuuhoP86YPDUXp4f&index=4

Anything can be declared inside anything!!

  • Access Specifiers (public, private, protected and <default>) vs Access Modifiers
  • Old language constructs… In java there is no terminology. All (12) are considered and modifiers

Interface vs Abstract vs Concrete class

  1. Interface (100% abstraction): No idea of implementation, just requirement spoecification, eg. Servlet
    • All methods must be public abstract
  2. Abstract : Partial implementation
    • concrete classes can be written
  3. Concrete Class : Ready to use service

Capture


Class MySystem{
static string out = “nitin”;
}
MySystem.out.length(); //Compare it to
System.out.println(out);

  • System is a Class
  • out is a static variable of type PrintStream in System class
  • println() is a method present in PrintStream.

  • Main method name can be set to a desired name by configuring JVM [JVM Customization]

JVM {
public static void nitin(String[] a)
}

  • public : to be called by JVM from anywhere
  • static : even without existing Object, JVM can call the main method. Also main method is not related to any object.
  • void : no return to JVM.
  • main : configured JVM
  • String[] args : command line argument.
  • overloading is possible (PSVM (int b)), but JVM will only call string args method (method hiding)
  • Inheritance is also applicable. the JVM first search main in child class or else it will execute the main method from the parent class.
  • If both Parent and child methods are same and “static”, this is method hiding… not overriding (only child class method is executed). Appears that overriding is applicable, but because of the static nature, its method hiding.
    • Inheritance and overloading is applicable
    • overriding is not, instead method hiding.
  • Java 1.7 enhancements
    • earlier “NoSuchMethodError : main”, now a more meaningful error
    • main method is mendatory, even though class has static block. Before, static block will be executed (and if System.exit(0), the program will terminate as well), and then NoSuchMethodError will be flashed.
    • if both static block followed by main method is present, then everything works as normal in both cases
    • Thus without even writing main, until Java 1.6, something can be printed on the console. from 1.7 onwards, main in compulsory.

  • Overloading
    • methods same name but different argument.
    • Compile time polymorphism, static polymorphism, early binding.
    • Method resolution is done by compiler based on reference type
  • Overriding :
    • When child class redefinition different than parent class (eg: marriage() method in example)
    • Runtime polymorphism, dynamic polymorphism, late binding
    • Method resolution is done by JVM based on runtime onject
    • co-varient return types are allowed (return can be same as Parent’s method, after Java 1.5)

*** In overloading check only method name (same) and argument type (different, at least order). Return types, access modifiers are not required.

**** In overriding: EVERYTHING should be same.

  • Parent p = new Child();
    • can invoke only parents methods
    • can use parent reference to hold any child class object.
    • polymorphism call
  • Child c = new Child();
    • can invoke both parent and child methods
    • can hold only child type of object
    • non polymorphic call

  • Control Flow in try catch block
    • (after jumping from try, rest of statements of try wont be executed. Thus keep the length of try block be be as small as possible)
    • there may be chances of exception in catch or finally block as well, and it will then be an abnormal termination.
    • if no exception, try and finally will execute
    • if abnornal termination due to exception in try or catch block, then also finally will execute.
  • Throwable (Class) has two child classes
    • Exception
      • Programming faults
      • Recoverable (file not found, catch {use local file and continue..})
    • Error
      • lack of system resources (out of memory etc)
      • system admin or server admin is responsible to increase heap memory
      • Non recoverable
  • Checked Exception :
    • Checked by compiler for smooth execution of the program at runtime (Menmonics : HallTicketMissingException, PenNotWorkingException, FileNotFoundException)
    • if programmer doesn’t handle checked exceptions, compile time error.
    • Mush be caught (try catch) or thrown (throws clause in the method definition)
    • Throwable -> Exception ->)Runtime exception and its child classes, (Throwable->)Error and its child classes are unchecked exceptions. Rest all are checked.
    • Further classified as fully checked or partially checked
  • Unchecked Exception
    • not checked by Compiler (bonmBlast exception, arithmatic, nullpointer)
    • Compiler won’t check if the programmer handled the exception.

*** Both occur at runtime.

  • FullyChecked exception
    • iff all the child classes are checked
  • PrtiallyChecked exception
    • if some of child classes are Unchecked
    • Only possible partially checked in Java
      1. Exception
      2. Throwable

Java Multithreading

  • Multitasking
    1. Process based multitasking (typing program while listening to music from the same system) Eack task is separate independent process(OS level)
    2. Thread based multitasking Separate independent task of same program (Programmer based)
  • Java Threading
    • strong API Support
    • 2 ways of defining
      1. By extending Thread class
        • override run() method;
        • everything within run() is called a job.
        • after instantiating t.start(), job from run() begins
        • both main thread and child thread runs simultaneously
        • no fixed flow of execution between main and child
        • Thread scheduler is part of JVM
      2. By implementing Runnable Interface (in java.lang and only method is run()) (Best approach)
        • class A implements Runnable{ public void run(){ … }
        • after instantiating, Thread t = new Thread(target Runnable object) and t.start();
  • Thread Life cycle

New Doc 1_1

Essential WordPress Plugins

For Free portfolio pictures : https://unsplash.com
Online Photo Editing  : http://www.picmonkey.com
Online Logo Editing : http://logomakr.com
The Logo/icons site : http://thenounproject.com/

Theme : Vantage

Plugins :

  1. Page Builder, for visual addition of html elements.
  2. LightBox Plus ColorBox : Lightbox Plus Colorbox permits users to view larger versions of images without having to leave the current page.
  3.  Black Studio Tiny MCE : For feature rich text editor
  4. Contact Form 7 :

Widget:

  1. Social Media Widget

Themify Builder : Stumbled upon themify builder as a part of Theme customization for wordpress 2013 theme. The tool is great to define a layout by drag and drop feature. Also Theme customization  and why child theme is created was understood with theses videos.

https://www.youtube.com/watch?v=giawHh0RztI

Themify Builder

https://www.youtube.com/watch?v=_AsoMMYqf_g

Programming Nirvana (Journey From Novice to Expert)

  • Inspired by 5 stages of Dreyfus Model of Skill Acquisition.
  • Novices, Advanced Beginner, Competent, Proficient, Expert
  • Step 1 : Learning to write codes less than 10 lines, but inclusive good logic. Gave me a good practice to set my hands on Java without using Google or any IDE. Writing logic of a method without bothering about the execution of a fully functional program. Also Test cases teaches the faults in the logic. The site takes away the burden of setting/installing Java or any other IDE’s. In short :

It teaches Thinking in Java

Taking Baby Steps CodingBat.

  • Step 2 : Learning to write fully functional programs (with 3 to 4 classes), with object creation, keeping in mind when to use static etc. JAVA 101 type assignments, which gives a clue of how the language is used to solve problems. A brief overview on OOP.
    • Assignment 1 :(Based on) Class String, Keyboard input, Console output
    • Assignment 2 : Defining Classes and methods, Encapsulation, boolean if & switch
    • Assignment 3 : Loops and Math. Random(), Objects and References (equals, toString())
    • Assignment 4 : Constructors, Static variables & methods, Overloading
    • Assignment 5 : Aggregation, exceptions
    • Assignment 6 : File Handling and Arrays
  • Step 3 : Learning Object Oriented Concepts (Later)
  • Step 4: Practice of elementary concepts of Collections from BJP

Strings, Arrays uses for loop as cursor

Arralylist, LinkedList, Vector and Stack uses ListIterator (most powerful Cursor)

All Collections use Iterator as Cursor