Monday 8 September 2014

JSON vs XML

JSON JavaScript Object Notation
XML Extensive Markup Language

Following are key differences between JSON & XML, which will help to decide which content format one should use in there application :


  • Parsing and Generating JSON data is easier as compared to XML.
  • JSON has simpler structure than XML.
  •  In XML document manipulation is easy as compared to JSON.You can easily find/update nodes.You have XPath/XQuery for XML, Do we have it for JSON ? 
  • You can do lots of thing with XML for example converting XML to HTML using XLST, such tools not available for JSON.
  •  XML is more rich in features and you can have more control over data and do great amount of validation as compared to JSON.You can have DTD's for XML to specify validation in details 
  • Working with JSON is simpler, especially with Javascript, just by giving call to Eval will give you Javascript Object.
  • JSON is not in a document format neither it is markup language but XML is.
  • JSON has great language support as compared to XML.
  • JSON is best for simpler use/scenario, for better security,support and validation XML is better.

  • JSON is faster as compared to XML as it is less rich, there is less overhead of tags & there is simpler validation rules.    

REST vs SOAP

REST stands for REpresentational State Transfer (REST) which enforces a stateless client server design where web services are treated as resource and can be accessed and identified by there URL unlike SOAP web services which were defined by WSDL.
Web services written by applying REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol.

SOAP
SOAP, originally defined as Simple Object Access Protocol, is a protocol specification for exchanging structured information in XML form.SOAP is protocol which relies on XML, that defines what is in the message and how to process it,set of encoding rules for data types, representation for procedure calls and responses.


REST vs SOAP

Before going for differences between two lets first see the differences in request header :

Sample SOAP & REST Request message for Weather Web Service :






 


SOAP vs REST Key Differences
Here are some of Key differences between SOAP and REST web Service :

  •  REST uses HTTP/HTTPS, SOAP can use almost any transport to send the request(for example we can have SOAP Messages over SMTP),  SOAP is a XML based messaging protocol.
  • REST is totally stateless operations where as SOAP supports statefull calls too. 
  • SOAP has more strict contract in the form of WSDL between applications, no such contract exists in case of REST.
  • AS REST APIs can be consumed using simple GET requests, REST response can be cached, this is not possible with SOAP.
  • REST is Lighter, SOAP requires an XML wrapper around every request and response(SOAP Headers, XML tags etc). Thats why REST is preferred choice in mobile devices and PDA's
  •  SOAP message format is restricted to XML only where as REST supports other formats too for example JSON.  
  • REST is simpler in terms of development as compared to SOAP.
  • Browsers can handle REST easily as compared to SOAP as REST is based on HTTP where SOAP is another wrapper over HTTP.

Why to use SOAP ?
SOAP provides some features like Security, Reliable Messaging, Atomic transaction which are not available in REST API.

  • WS-Security  & WS-SecureConversation  Provide support for using security tokens like Kerberos, and X.509.
  • WS-ReliableMessaging   Reliable messages delivery between distributed applications in case of failures.
  • WS-AtomicTransaction, two-phase commit across distributed transactional resources
  • In case where exact specification  of exchange format need to agreed between applications SOAP is better suitable.

Sunday 7 September 2014

Internal implementation of Set/HashSet (How Set Ensures Uniqueness)

Set Implementation Internally in Java

Each and every element in the set is unique .  So that there is no duplicate element in set .

 what happens internally when you pass duplicate elements in the  add() method of the Set object , It will return false and do not add to the HashSet , as the element is already present .So far so good .

But the main problem arises that how it returns false . So here is the answer

When you open the HashSet implementation of the add() method in Java Apis that is rt.jar , you will find the following code in it



public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

{
    private transient HashMap<E,Object> map;
    
    // Dummy value to associate with an Object in the backing Map
    
    private static final Object PRESENT = new Object();
    
    
    
    public HashSet() {
        map = new HashMap<>();
    }
    
    // SOME CODE ,i.e Other methods in Hash Set
    
    
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    
    
    
    // SOME CODE ,i.e Other methods in Hash Set
}


So , we are achieving uniqueness in Set,internally in java  through HashMap . Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .

The main point to notice in above code is that put (key,value) will return

1.  null , if key is unique and added to the map
2.  Old Value of the key , if key is duplicate

So , in HashSet add() method ,  we check the return value of map.put(key,value) method with null value
i.e.

   public boolean add(E e) {
            return map.put(e, PRESENT)==null;
       }

So , if map.put(key,value) returns null ,then
map.put(e, PRESENT)==null      will return true and element is added to the HashSet .



So , if map.put(key,value) returns old value of the key ,then
map.put(e, PRESENT)==null      will return false and element is  not added to the HashSet .

Friday 5 September 2014

instanceOf comparison


class Tree {

}

class Pine extends Tree{

}

class Oak extends Tree{

}

class TestTree{
    public static void main (String args[]){
        Tree t = new Pine();
        System.out.println(t instanceof Pine);  // returns true
        System.out.println(t instanceof Tree);  // returns true
        System.out.println(t instanceof Oak);   // returns false
        System.out.println(t instanceof Object);   // returns true

        Tree tree = new Tree();
        System.out.println(tree instanceof Pine);  // returns false
        System.out.println(tree instanceof Tree);  // returns true
        System.out.println(tree instanceof Oak);   // returns false
        System.out.println(tree instanceof Object);   // returns true
    }
}

Primitive Data Types

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. 


A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:

  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
  • int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use theint data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
  • long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the longdata type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead.Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

    The following chart summarizes the default values for the above data types.
    Data TypeDefault Value (for fields)
    byte0
    short0
    int0
    long0L
    float0.0f
    double0.0d
    char'\u0000'
    String (or any object)  null
    booleanfalse

Common Observations:

       final int i =100;
        byte b = i;
        System.out.println(b);  // valid prints 100


        /*
        final int x =1000;
        byte y = x;   //compile error
        System.out.println(y);  */


        /*
         int x =100;
        byte y = (byte) x;   //valid
        System.out.println(y); */


        /*int x =100;
        byte y =  x;   //compile error. Nee to cast x --  byte y =  (byte) x
        System.out.println(y); */

        char c = 9;   //valid
        char d = 'A';  //valid
        char e = 0x12; //valid

        int j = 0345;  //valid
   
        System.out.println(1+2f+3d); // print 6.0

        /*final long test = 1;
        byte b1 = test; //compile error
        System.out.println(b1);*/
 

OverLoading vs Overriding



Method overloading and method overriding in Java is two important concept in Java which allows Java programmer to declare method with same name but different behaviour. Method overloading and method overriding is based on polymorphism in Java. 

In case of method overloading, method with same name co-exists in same class but they must have different method signature, while in case of method overriding, method with same name is declared in derived class or sub class.Method overloading is resolved using static binding in Java at compile time while method overriding is resolved using dynamic binding in Java at runtime. In short When you overload a method in Java its method signature got changed while in case of overriding method signature remains same but a method can only be overridden in sub class

OverLoad:
If you have two methods with same name in one Java class with different method signature than its called overloaded method in Java. Generally overloaded method in Java has different set of arguments to perform something based on different number of input. You can also overload constructor in Java, which we will see in following example of method overloading in Java. Binding of overloading method occurs during compile time and overloaded calls resolved using static binding. To overload a Java method just changes its signature. Just remember in order to change signature you either need to change number of argument, type of argument or order of argument in Java if they are of different types. Since return type is not part of method signature simply changing return type will result in duplicate method and you will get compile time error in Java.

 Remember you can overload static method in Java, you can also overload private and final method in Java but you can not override them.

You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM.


Override:
In order to override a Java method, you need to create a child class which extends parent. Overridden method in Java also shares same name as original method in Java but can only be overridden in sub class. Original method has to be defined inside interface or base class, which can be abstract as well. When you override a method in Java its signature remains exactly same including return type. JVM resolves correct overridden method based upon object at run-time by using dynamic binding in Java.

Rule of Method Override
  1. Method signature must be same including return type, number of method parameters, type of parameters and order of parameters
  2. Overriding method can not throw higher Exception than original or overridden method. means if original method throws IOException than overriding method can not throw super class of IOException e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.
  3. Overriding method can not reduce accessibility of overridden method , means if original or overridden method is public than overriding method can not make it protected.

Summary
  1. First and most important difference between method overloading and overriding is that, In case of method overloading in Java, Signature of method changes while in case of method overriding it remain same.
  2.  Second major difference between method overloading vs overriding in Java is that You can overload method in one class but overriding can only be done on subclass.
  3. You can not override static, final and private method in Java but you can overload static, final or private method in Java.
  4. Overloaded method in Java is bonded by static binding and overridden methods are subject to dynamic binding.

Wednesday 3 September 2014

Application Server vs Web Server

1. Application Server supports distributed transaction and EJB. While Web Server only supports Servlets and JSP.

2. Application Server can contain web server in them. most of App server e.g. JBoss or WAS has Servlet and JSP container.

3. Though its not limited to Application Server but they used to provide services like Connection pooling, Transaction management, messaging, clustering, load balancing and persistence. Now Apache tomcat also provides connection pooling.

4. In terms of logical difference between web server and application server. web server is supposed to provide http protocol level service while application server provides support to web service and expose business level service e.g. EJB.

5. Application server are more heavy than web server in terms of resource utilization.