Thursday, February 5, 2015

Information On OOPS, Collections,Exceptions & Threads.

oop:


InheritanceObject-oriented programming allows classes to inherit commonly used state and behavior from other classes. (Extending the super class properties in to sub class)

class MountainBike extends Bicycle {

    // new fields and methods defining
    // a mountain bike would go here

}
Polymorphism:
Over ridding and over loading

  • Over loading will happen at compile time,
int add(int a,int b)
 float add(float a,int b)
 float add(int a ,float b)
  • Over ridding will be choose at run time.(Super class method overridden in sub class)


Abstraction:
Interfaces and abstract classes

Encapsulation:
wrapping data in to single unit called encapsulations. Java beans..all java object are

Collections


1) Sorting on collections:


A List l may be sorted as follows.

Collections.sort(l);
If the List consists of String elements, it will be sorted into alphabetical order. If it consists of Date elements, it will be sorted into chronological order. How does this happen? String and Date both implement the Comparable interface.

If you try to sort a list, the elements of which do not implement Comparable, Collections.sort(list) will throw a ClassCastException.

Comparable example:

public class Name implements Comparable<Name> {
    private final String firstName, lastName;

    public Name(String firstName, String lastName) {
        if (firstName == null || lastName == null)
            throw new NullPointerException();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() { return firstName; }
    public String lastName()  { return lastName;  }

    public boolean equals(Object o) {
        if (!(o instanceof Name))
            return false;
        Name n = (Name) o;
        return n.firstName.equals(firstName) && n.lastName.equals(lastName);
    }

    public int hashCode() {
        return 31*firstName.hashCode() + lastName.hashCode();
    }

    public String toString() {
return firstName + " " + lastName;
    }

    public int compareTo(Name n) {
        int lastCmp = lastName.compareTo(n.lastName);
        return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
    }
}

import java.util.*;

public class NameSort {
    public static void main(String[] args) {
        Name nameArray[] = {
            new Name("John", "Smith"),
            new Name("Karl", "Ng"),
            new Name("Jeff", "Smith"),
            new Name("Tom", "Rich")
        };

        List<Name> names = Arrays.asList(nameArray);
        Collections.sort(names);
        System.out.println(names);
    }
}

Comparator example:


package com.javacodegeeks.java.util.comparator;

import java.util.Comparator;

public class GradeComparator implements Comparator {

@Override
public int compare(Student o1, Student o2) {

// descending order (ascending order would be:
// o1.getGrade()-o2.getGrade())
return o2.getGrade() - o1.getGrade();
}

}
Collections.sort(arrayListObject,new GradeComparator ()); 
Here arrayListObject contains the list of Student objects, when we call Collections.sort method it will sort based on the grade.

or other way of implementaion:

public class EmpSort {
    static final Comparator<Employee> SENIORITY_ORDER =
                                        new Comparator<Employee>() {
            public int compare(Employee e1, Employee e2) {
                return e2.hireDate().compareTo(e1.hireDate());
            }
    };

    // Employee database
    static final Collection<Employee> employees = ... ;

    public static void main(String[] args) {
        List<Employee> e = new ArrayList<Employee>(employees);
        Collections.sort(e, SENIORITY_ORDER);
        System.out.println(e);
    }
}

2)Collection, List,Set,Map.

Two interface trees, one starting with Collection and including Set, SortedSet, List, and Queue, and the other starting with Map and including SortedMap.

Set: is collection interface, which doesn't contain duplicate elements.
List: is an order collection, it allow you to write duplicate objects.In the list each element is inserted and can access elements by their integer index (position)
Deque: can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-out). In a deque all new elements can be inserted, retrieved and removed at both ends
Queue: FIFO
Map:an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.

To get all keys from a Map:
map.keySet(); ->Retrieve all keys from a map.

keySet — the Set of keys contained in the Map.
values — The Collection of values contained in the Map. This Collection is not a Set, because multiple keys can map to the same value.
entrySet — the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry, the type of the elements in this Set.
Set<Map.Entry<K,V>> entrySet()
Returns a Set view of the mappings contained in this map.

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Use Iterator instead of the for-each construct when you need to:

Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
Iterate over multiple collections in parallel.

ConcurrentHashMap<K,V>:
ConcurrentHashMap in Java is introduced as an alternative of Hashtable, which can be safely used in a concurrent and multi-threaded Java program, than, you only have Hashtable or synchronized Map because HashMap is not thread-safe. With ConcurrentHashMap, now you have better choice; because, not only it can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. allows concurred read operations and same time, maintains integrity by synchronizing write operations





3) equals & hashcode methods.

different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.

class Employee {
private Long id;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id=id;
}
}

Employee e= new Employee();
e.setId(100);

Employee e1= new Employee();
e1.setId(100);

Set <Employee> employeeSet = new HashSet<Employee>();
employeeSet.add(e);
employeeSet.add(e1);

When iterate the above set it will display the 2 Objects. But as per Set it wont inset the duplicate object. Here there is no equals and hascode method implemented in Employee class, When you implement equals and hashCode method it will not insert duplicate object.

In the case of HashMap, it replaces the old value with the new one.

In the case of HashSet, the item isn't inserted.




4) String -> why it is immutable how it works!

String is immutable and StringBuffer is mutable. In java all immutable objects are thread safe meaning no 2 threads can access same time, String is stored in the  Constant String Pool, from this we can say String is a thread safe.
StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

String s="Sachin";
   s.concat(" Tendulkar");
   System.out.println(s);

Output = "Sachin"

Heap diagram
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                 
Storage Area | Constant String Pool           Heap                       Heap 
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast
-----------------------------------------------------------------------------------


String str1="Hello";
String str2="Hello";
String str3=new String("Hello") //Using constructor.

If(str1 == str2)
        System.out.println("Equal 1");
Else
        System.out.println("Not Equal 1");

If(str1 == str3)
        System.out.println("Equal 2");
Else
         System.out.println("Not Equal 2");

If( str1.equals(str3) )
        System.out.println("Equal 3");
Else

        System.out.println("Not Equal 3");

The output would be,
Equal 1
Not Equal 2
Equal 3

Note that == compares the references not the actual contents of the String object; Where as equals method compares actual contents of two String objects.

Load Balancing:(Cached information)

An important issue when operating a load-balanced service is how to handle information that must be kept across the multiple requests in a user's session. If this information is stored locally on one backend server, then subsequent requests going to different backend servers would not be able to find it. This might be cached information that can be recomputed, in which case load-balancing a request to a different backend server just introduces a performance issue.

Ideally the cluster of servers behind the load balancer should be session-aware, so that if a client connects to any backend server at any time the user experience is unaffected. This is usually achieved with a shared database or an in-memory session database, for example Memcached.

Threads:

Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}
Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:

public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}

Life cycle of a Thread:

    New
    Runnable
    Running
    Non-Runnable (Blocked)
    Terminated

sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

wait(): until call notify(), notifyAll() from object
sleep(): until at least time expire or call interrupt().

volatile:
The Java volatile keyword is used to mark a Java variable as "being stored in main memory". More precisely that means, that every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.



When two threads are accessing the same shared variable, if any one of the thread updated the shared value it will stored in to CPU cache, this will leads to inconsistency value's . To make sure all way to store in to main memory we will use volatile key word.


Exception handling:

The Throwable class and its most significant subclasses.

The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception
Checked Exception:
SQLException
IOException
DataAccessException
ClassNotFoundException
InvocationTargetException


throw new Exception("Something went wrong!!");
public void sample() throws ArithmeticException{

No comments: