Tuesday, 1 January 2013

Abstraction, Encapsulation and Polymorphism


  1. Encapsulation - puts related data and functionality in one place. We can get this through classes
  2. Polymorphism - Allows values of different data types to be handled using a uniform interface.
Polymorphism can be achieved by inheriting base classes (with virtual functions) and/or by implementing interfaces.
These techniques (and others) give us abstraction, which really applies to any of the processes we use to break a problem up into smaller components.
Eg:
A highly contrived example:
public class Person {
  private int age;

  public boolean canBuyBeer() {
    return age >= 21;
  }

}
you might later change this to:
public class Person {
  private int age;
  private boolean isInUSA


  public boolean canBuyBeer() {
    if( isInUSA )
        return age >= 21;
    else
         return age >= 18;
  }

}
Encapsulation:- The rules regarding age and origin can change but the caller doesn't need to know.
Interfaces can be used to abstract out different types. Consider this:
public interface Beverage {
  public boolean containsAlchohol;
}

public class Soda implements Beverage {
  public boolean containsAlchohol {  
      return false;
  }
}
public class Beer implements Beverage {
  public boolean containsAlchohol {
       return true;
  }
}
You might update Person like:
public class Person {
  private int age;
  private boolean isInUSA


  public boolean canBuyBeverage(Beverage b) {
    if( b.containsAlchohol() ) {
       if( isInUSA )
           return age >= 21;
       else
           return age >= 18;
    }
    else {
        return true;
    }
  }

}
Now we are implementing the Polumorphism in case of Beverages.
or 
public void doSomething( List list )  
{     System.out.println( list.size() );
     list.add("Hello"); 
 } 
You might call doSomething with an ArrayList or a LinkedList. By ignoring the detail of the exact type I can focus on the big picture of what I want to do with the list.
So, by implementing these two concepts, we can achieve Abstraction.
Regards
Rajan Bansal

Thursday, 13 December 2012

Iterate through HashMap


Iterate through the entrySet like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}


If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;
for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():
for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

Source;- stackoverflow

Example Code:-

MapIteration.java
package collection.iteration;

import java.util.*;
import java.util.Map.Entry;

public class MapIteration {

public static void main(String[] args) {
Map <String,Employee> map= new HashMap<String,Employee>();
Employee emp1= new Employee(25, "Hitesh");
Employee emp2= new Employee(26, "Rajan");
Employee emp3= new Employee(27, "Dinesh");
Employee emp4= new Employee(24, "Neha");

map.put("e1",emp1);
map.put("e2",emp2);
map.put("e3",emp3);
map.put("e4",emp4);
System.out.println(map.keySet()); // Displaying all keys
System.out.println(map.values()); // Displaying all values
for(Map.Entry<String, Employee> entry : map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}

}
And
 Employee.java


package collection.iteration;

public class Employee implements Comparable<Employee> {
int age;
String name;

Employee(int age, String name){
this.age=age;
this.name=name;
}
Employee(){

}
public String toString(){
return("The age is "+age+" and the name is "+name);
}

public int compareTo(Employee e){
return name.compareTo(e.name);
}
}


 Output:

[e3, e4, e1, e2]
[The age is 27 and the name is Dinesh, The age is 24 and the name is Neha, The age is 25 and the name is Hitesh, The age is 26 and the name is Rajan]
e3
The age is 27 and the name is Dinesh
e4
The age is 24 and the name is Neha
e1
The age is 25 and the name is Hitesh
e2
The age is 26 and the name is Rajan




Regards
Rajan Bansal

When hashSet and equals methods executes

class Person
{
    String name;

    Person(String n)
    {
        name=n; 
    }
    public String getName()
    {
        return name;   
    }

    @Override
    public boolean equals(Object arg0) {

        System.out.println("in equals");

        Person obj=(Person)arg0;

        System.out.println("1st "+getName());
        System.out.println("2nd "+obj.getName());

        if(this.getName().equals(obj.getName()))
        {
                return true;
        }
        return false;
    }


    @Override
    public int hashCode() {

        System.out.println("in hash code");
        System.out.println(" value is "+Integer.valueOf(name.charAt(0)));
        return Integer.valueOf(name.charAt(0));
    }
}

In main I have the following code

Person obj1=new Person("bcd");

Person obj2=new Person("cde");

Person obj3=new Person("abc");

Person obj4=new Person("abc");

Now if I add these objects to hashset

Set<Person> sset=new HashSet<Person>();

sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj3);

I am getting this output

in hash code                                                                      
value is 98    
in hash code   
value is 97    
in hash code    
value is 99    
in hash code    
value is 97  
in equals  
1st abc     
2nd abc

Question 1 : why equals() function is called only once for checking obj3 and obj4 ? Why its not checked for rest of the objects ?

Question 2 : If the answer is because they both have same hash code,only then equals will be called, then why its not called for below code

sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj4);
output is :

in hash code  
value is 98  
in hash code   
value is 97   
in hash code   
value is 99   
in hash code  
value is 97 
It's not going inside equals() method even though two same objects are added to hash set which has same hash code.

Question 4 :I iterated the above value and printed the contents but neither hashcode nor equals were called. when its really useful to override hashcode and equals method ?

Question 3 : when hash code and equals will be called ?


Answers:

1.There's no need to call equals if hashCode differs
2.There's no need to call hashCode if (obj1 == obj2)
3.There's no need for hashCode and/or equals just to iterate - you're not comparing objects
4. When needed to distinguish in between objects.


Source: stackoverflow

Regards
Rajan Bansal

Tuesday, 11 December 2012

What is MVC framework using Spring


The MVC is a standard software architecture that aims to separate business logic from presentation logic, enabling the development, testing and maintenance of both isolated .

The picture below depicts the flow of information in the MVC pattern :


(1) The user triggers an event through the UI (click a button on the page or something).
(2) The controller receives the event and coordinates how things will happen on the server side, i.e. the flow goes to the objects required to perform the business rule.
(3) The model is used to represent the business information so it is called by the controller to perform the business rule that should be done. The model can also be used to send data to the view layer.
(4) After the controller performs business rule using the model it renders a new view and sends it to the user. Create an application using the MVC pattern is nothing more than to separate the logic in “packages” and make that information follow a certain path.

Information flow diagram of Spring Web MVC :


(1) A request from the user always arrives in a single servlet Dispatcher Servlet. This is a very common pattern in MVC frameworks called front controller (front controller) where a single servlet is responsible for receiving the request, delegate processing to other components of the application and return a response to the user.
(2) Once the Dispatcher servlet gets the request it must find out which controller the request will be sent. So it asks for help in the Handler Mapping. Based on the request URL Handler Mapping finds the controller.
(3) The request is then sent to the controller that will take care of the data contained therein. Once the controller receives the request it processes the data and performs some business rules of the application.
(4) Often rendered by the logic controller results in some information that should be taken back to the user (the model). Only sending information back is not enough, it must be formatted in a way that the user can understand, for that controller send it to the view. For this model and the view are encapsulated in a ModelAndView object and returned to the Dispatcher.
(5) As the controller is not stuck to just one view it sends a hint in the ModelAndView object to the Dispatcher to know which view should send the data. The Dispatcher passes this hint to viewResolver that returns the view which should be called.
(6) Finally, the Dispatcher sends the information (model) to the view (JSP page) who has just discovered. The page renders the information received and is returned to the user.
Here the original version: Original Version


Wednesday, 10 October 2012

what is the difference between declarative and imperative programming

In other words, Non-Procedural (declarative) and Procedural (imperitive):


Declarative programming is where you say what you want without having to say how to do it. For example, SQL is more declarative than procedural, because the queries don't specify steps to produce the result. Eg: SQL, XSLT, HTML etc
 With procedural programming, you have to specify exact steps to get the result. Eg; C, C++, Java, .net and many other.

With imperative programming, you tell the compiler what you want to happen, step by step.
For example, let's start with this collection, and choose the odd numbers:
List<int> collection = new List<int> { 1, 2, 3, 4, 5 };
With imperative programming, we'd step through this, and decide what we want:
List<int> results = new List<int>();
foreach(var num in collection)
{
    if (num % 2 != 0)
          results.Add(num);
}
Here, we're saying:
  1. Create a result collection
  2. Step through each number in the collection
  3. Check the number, if it's odd, add it to the results
With declarative programming, on the other hand, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step):
var results = collection.Where( num => num % 2 != 0);
Here, we're saying "Give us everything where it's odd", not "Step through the collection. Check this item, if it's odd, add it to a result collection." 


Differences between SQL and PL-SQL

SQL is a query language that allows you to issue a single query or execute a single insert/update/delete.
PL-SQL is Oracle's "Programming Langugage" SQL, which allows you to write a full program (loops, variables, etc.) to accomplish multiple selects/inserts/updates/deletes.

Regards
Rajan Bansal

Saturday, 6 October 2012

What is DELIMITER //


Hi,
It changes the statement delimiter from ; to //. This is so you can write ; in your trigger definition without the MySQL client misinterpreting that as meaning you're done with it.
Note that when changing back, it's DELIMITER ;, not DELIMITER; as I've seen people try to do.
source: stackoverflow.com