Saturday 24 December 2016

HTML introduction and its basics ?

 Introduction of HTML

      HTML is a hypertext markup language.
      HTML is the most commonly used markup language for creating Web pages.
     A markup language provides a way to describe the structure of text-based information on a Web pages.Hypertext is similar to regular text.
     HTML is designed by w3c (world wide web consortium) is an organization.

  USES OF HTML IN MARKET
                                                    
      In  google
      Online shop ex: flipkart,amazon,.snapdeal,etc...
      Business
      organization 
      Education 
      Research center

Creating and Saving HTML Document 

     We can create a HTML Document using a text editor, like Notepad, adding our html code to the document, and saving it with  filename.html extension.

 The following step to create and save an html document:

  Step1:  Start->All program->Accessories->Notepad.
  Step2: The Notepad window opens with blank document.
  Step3:  Add the html code in the document.
  Step4:  click File->Save As
  Step5:   Save As dialog box appear and saving the document inside folder filename.html and click ok.

Opening the html document in a web Browser

 The following step to open an html document:

Step1:  Open the folder contain our html document.
Step2:  Double click the html document.html document will open in the default web browser in our computer.

 HTML ADVANTAGE

   Don't require additional software to run HTML.
   It can be run in normal web browser. for example: Internet Explorer,Mozilla Firefox,Opera etc...

First Look  at HTML

  In case of HTML is more important of show the text in web browser using basic tags.
  An HTML tag is format of a pair of angle brackets (<tag>) text place in this bracket.
  That angle brackets defines an HTML element .
                    
HTML element have two properties
             1. Attributes(ex: <img align='left'>) : align is the attribute
             2. Content
syntax:    <element-name> content  </element-name>
for example:
                        <strong> hello </strong>
                      In above example hello is a called of content.

Basic structure of an HTML document

 The basic structure  of HTML 
syntax:
          <!DOCTYPE>
           <html>
           <body>
           Content of the web page
            </body>
            </html>

example:
          <!DOCTYPE>
          <html>
           <body>
           welcome
           </body>
           </html>

 Result:
          The result of web page welcome


Title of web page

syntax:
          <!DOCTYPE>
           <html>
           <head>
            <title>
            Title of the web page
           </title>
           </head>
           <body>
           Content of the web page
            </body>
            </html>

example:
          <!DOCTYPE>
          <html>
          <head>
           <title> html </title>
           </head>
           <body>               
           <h1> welcome </h1>
            <p> The <b><i><u> html<u><i><b> is hypertext markup language. It is used to create a web page.A markup language provides a way to describe the structure of text-based information on a web page.</p>
             <hr>
           </body>
           </html>
Result:
 

The preceding example uses some of the most common element found in HTML document:
  •  <!DOCTYPE> indicates the particular version of html being used in the document.but that tag not used mostly.
  • <html>,<body>,<head>tag pair are used to specify the general structure of the document.
  • <title> and </title> tag pair specifies the title of the document.It appear in the title bar of the web browser.
  •  <h1> and </h1> is called header tag pair.It creates a headline to indicate some important information.
  •  <hr> tag is used to only inserts a horizontal rule, or bar,across the screen.
  • <p> and </p> is called paragraph tag.It is used to create a paragraph of text. 
  • <u></u>  is used for underline the text within opening and closing tags.
  • <i></i> is used to italic style for the text within opening and closing tags.
  • <b></b> is used to bold style for the text within opening and closing tags.

<HTML> Tag

        The <html> tag place on the beginning and the end of an HTML document.It is also called the root element.
        The <html> tag, directly contains only the <head> tag, the <body> tag, and <frameset> tag instead of <body>tag.
        The <html>tag's used in a document, as a container for all other elements.

<HTML>ELEMENT

Attributes:

class
  1. dir
  2. id
  3. lang
  4. version
  5. xmlns
1. class Attribute 
       The class attribute is used to indicate the class.  It belongs to id, class is used to associate a tag with a name.
 2. dir Attribute
       Dir is a gives the direction of the text.
       we can set this attribute of text direction
  •  "ltr"-left to right
  •  "rtl"-right to left 

3. id Attribute
         The id attribute is used to set the unique name for the element & used for referring to it.

4.lang Attribute
          The lang attribute is used for base language for the element.

5.version Attribute
          Indicate  the  version of the language used.

6.xmlns Attribute
           It is used for declare a namespace for custom tags in an html document.

The <HEAD> Element    

         The information in the head of an HTML document is very important because it is used to describe or augment the content of the document.
          The information contained with in the <head> tag is information about information of the page, which generally of referred to as meta-information.   

Attributes of the< head> element:

  1. class
  2. id 
  3. dir
  4. lang
  5. profile
  6. style
  7. title 
1. class 
       The class attribute is used to indicate the class.  It belongs to id, class is used to associate a tag with a name.
 2. dir
       Dir is a gives the direction of the text.
       we can set this attribute of text direction
  •  "ltr"-left to right
  •  "rtl"-right to left 

3. id 
         The id attribute is used to set the unique name for the element & used for referring to it.

4. lang
          The lang attribute is used for base language for the element.

5. profile
         Gives the location of one or more white-space separated metadata profile URLs for the current document.

6. style
         The style attribute is used to add style sheet information directly to a tag.

7. title
         The title is used to provide advisory text about an element or its contents.

Elements to be added to the <head> Element:
  1. <base>
  2. <basefont>
  3. <bgsound>
  4. <isindex>
  5. <link>
  6. <meta>
  7. <nextid>
  8. <noscript>
  9. <script>
  10. <style>
  11. <title>         
Description: 
1. <base>
       Base URL for the document.

2. <Basefont>
       Basefont for the document.

3.<bgsound>
       Background sound.

4. <isindex>
        Rudimentary input control.

5. <link>
      Link are use to connect one page to another.

6. <meta>
      It gives the header information.

7. <nextid>
      Hint for the name value to use when creating a new hyperlink element.

8. <noscript>
      Holds text that only appears if the browser does not support the <script> element.

9 .<script>
       Holds programming script statements, like  javascript.

10. <style>
         Includes style information for rendering.

11 .<title>
       The title of the web page that appears in the web browser.  


The <title> Element

        The <title> element contains the title of the HTML document. It will appear in the title bar of the web browser.
         Each <head> element should contain a <title> element.

Attributes of the <title> Element:
  1. class
  2. dir
  3. lang
  4. style     
Description: 

1. class 
       The class attribute is used to indicate the class.  It belongs to id, class is used to associate a tag with a name.
 2. dir
       Dir is a gives the direction of the text.
       we can set this attribute of text direction
  •  "ltr"-left to right
  •  "rtl"-right to left 
3. lang
          The lang attribute is used for base language for the element.

3. style
         The style attribute is used to add style sheet information directly to a tag.

The <BODY> Element  

          The <body> element  contains the body of the HTML document. The element  include the entire content that will appear in the web browser.
          It can include text, images, and multimedia element.

Attributes of the <body> Element: 
  1. alink
  2. background
  3. bgcolor
  4. bgproperties
  5. bottommargin
  6. class
  7. id
  8. dir
  9. lang
  10. language
  11. leftmargin
  12. link
  13. marginheight
  14. marginwidth
  15. rigthmargin
  16. scroll
  17. style 
  18. text
  19. title
  20. topmargin
  21. vlink
Description: 
 1. alink
       It is used to color of the  hyperlinks when you are clicked; 
       You can set this attribute to a predefined color or a color value.
2. background
      The element used to set the background image.
3. bgcolor
     The color of the background of the browser; you can set this attribute to a predefined color or a color value.
4.bgproperties
      Indicate if the background should scroll when the text scrolls;
      If you set this attribute to fixed; It is only allowed value, the background will not scroll when the text scrolls.
5. bottommargin
         It  specifies the bottom margin, which is the empty space at the bottom of the document.
   6. class 
       The class attribute is used to indicate the class.  It belongs to id, class is used to associate a tag with a name.

7. id 
         The id attribute is used to set the unique name for the element & used for referring to it.


 8. dir
       Dir is a gives the direction of the text.
       we can set this attribute of text direction
  •  "ltr"-left to right
  •  "rtl"-right to left 

9. lang
          The lang attribute is used for base language for the element.

10. language
         Scripting language used for the element.

11. leftmargin
         Specifies the leftmargin, which is the empty space to the left of the document.

12. link
         Color of the hyperlinks that have not yet been visited.

13. marginheight
         Gives the height of the top and bottom margins, in pixels.

14. marginwidth
         Gives the width of the left and right margins, in pixels.

15. rightmargin
          Specifies the rightmargin, which is the empty space to right of the document, in pixel.

16. scroll
       Specifies the vertical scroll bar appears to the right of the document.

17. style
        Specifies whether a vertical scrollbar appears to the right of the document. Default value for the attribute "yes" or "no".

18. text
        Set the color of the text in the document.

19. title
        Hold the additional information for the element.

20. topmargin
         Specifies the topmargin, which is the empty space to top of the document, in pixel.

21. vlink
        Color of the hyperlinks that have been visited.
        


       

Thursday 15 December 2016

Why TreeSet does not accept null value ?

In TreeSet, all elements are sorted according to the natural ordering of the element. Also it does not contain duplicate and null value. If you want to modify the natural ordering of the element, you can use your own Comparator at the time initialization, to sort its value based on your own logic.

If you try to store null value , it throws NullPointerExeption .

The reason is, if you look at the internal implementation of the TreeSet, it uses natural ordering, that means TreeSet uses Comparable interface by default to sort its value by comparing other value. 

Just think programmatically, how will you compare the null value to other. Is it make sense to compare the value with other(NULL) which doesn't have any value in it.  That's why java developer made it TreeSet such a way that, it will throw NullPointerExeption when you try to store null value.


And also if you look at the definition of add method in TreeSet

add Method in TreeSet

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

Hope you clear with the explaination.




If you like the above solution . Please share this blog

Tuesday 6 December 2016

Why ConcurrentHashMap does not allow null keys and null values ?

We all know that ConcurrentHashMap (optimized version of  Hashtable) doesn't allow null key or null values. To know the reason behind this implementation, we need to know the internal implementation and its uses.

I am separating the above explanation in two steps.

  1. not allowing null key
  2. not allowing null values
1) Not allowing null key
The reason behind this implementation is due to ambiguity nature of the ConcurrentMap (ConcurrentHashMap & ConcurrentSkipListMaps) when it comes to threading environment. The main reason is that if map.get(key) returns null, we can't detect whether the key explicitly maps to null vs the key isn't mapped. In ConcurrentHashMap, It might be possible that key 'K' might be deleted in between the get(k) and containsKey(k) calls.

For example in below code of ConcurrentHashMap
Line 1: if (concurrentHashMap.containsKey(k)) {     
Line 2:      return concurrentHashMap.get(k);  
Line 3: } else {
Line 4:      throw new KeyNotPresentException();
Line 5: }

The above example i am  explaining with two thread(1 & 2). In Line 2, after checking thread 1 with the key "K" in concurrentHashMap(Line 1 - contains some value for the key "K"),  it will returns null (if thread 2 removed the key 'K' from concurrentHashMap). Instead of throwing KeyNotPresentException , it actually returns null.

The above scenario will not happen in case of non-concurrent map (HashMap), because there is no Concurrent access. So null key are allowed in HashMap by eliminating the ambiguity.

2) Not allowing null values
And also null values are not allowed in the ConcurrentMap (ConcurrentHashMap & ConcurrentSkipListMaps). If you look at the below code in ConcurrentHashMap.

Line 1. public V put(K key, V value) {
Line 2.   if (value == null)
Line 3.     throw new NullPointerException();
Line 4.   int hash = hash(key.hashCode());
Line 5.   return segmentFor(hash).put(key, hash, value, false);
Line 6. }

In line 2 & 3, throws NullPointerException by checking the value, this means, passed value could be used through the ConcurrentHashMap without expecting it to be null. I checked the usage of value in ConcurrentHashMap, there is no evidence or piece of code throwing NullPointerException.  Then i started investigating the internal implementation.

So wrote a simple program with modified ConcurrentHashMap by removing those Line 2 and Line 3 in the above code and created two thread (1 and 2), one take cares of inserting null values and other with reading it. Surprisingly i did not get any error. So i decided to check performance of get and put operation by measuring the time of both modified and unmodified version of ConcurrentHashMap. The get method of modified ConcurrentHashMap takes 5-8 times more time than unmodified one and put method of modified ConcurrentHashMap takes 3-5 times more than unmodified one.

The Reason is segment of ConcurrentHashMap takes a lock if the value of HashEntry becomes null.

GET METHOD
1 get(Object key, int hash) {
2.    if (count != 0) { 
3.      HashEntry e = getFirst(hash);
4.      while (e != null) {
5.        if (e.hash == hash && key.equals(e.key)) {
6.          V v = e.value;
7.            if (v != null)
8.              return v;
9.          return readValueUnderLock(e); //  takes lock if the value is null
10.       }
11.       e = e.next;
12.     }

PUT METHOD
1.  V put(K key, int hash, V value, boolean onlyIfAbsent) {
2.    lock();
3.    try {
4.      int c = count;
5.      if (c++ > threshold) 
6.        rehash();
7.      HashEntry[] tab = table;
8.      int index = hash & (tab.length - 1);
9.      HashEntry first = tab[index];
10.     HashEntry e = first;
11.     while (e != null && (e.hash != hash || !key.equals(e.key)))
12.       e = e.next;
13.     V oldValue;
14.     if (e != null) {
15.       oldValue = e.value;
16.       if (!onlyIfAbsent)
17.         e.value = value;
18.       } else {
19.         oldValue = null;
20.         ++modCount;
21.         tab[index] = new HashEntry(key, hash, first, value);  // New value for HashEntry
22.         count = c;
23.       }
24.     return oldValue;
25.   } finally {
26.   unlock();
27. }
28.  }

Now the questions is, if ConcurrentHashMap  is not allowing null value, then why the null check is implemented for HashEntry value in Line 7 of get method.  Reason is, consider a situation that writer thread is trying to create a new HashEntry in Line 21 of put method but not yet initialized, so actual value is not reflecting in value attribute of HashEntry, in the same time reader thread reads it value as null, so this recheck is done in Line 7 in the get method. 

And extra check in the Line 9 in get method is very costly in terms of performance and it is avoided 
for not null value. so modified ConcurrentHashMap takes long time to read and write null values than unmodified ConcurrentHashMap with non-null values.




If you like the above solution . Please share this blog

Friday 2 December 2016

Explain the JAVA process when you run main class ?


When  you invoke a main class with the command "java MainClass", your application will start executing the main method, then it continue its execution depends on your programming logic. But before start executing the main method, there is a sequence of JAVA process involve to successfully carry its execution.

JAVA PROCESS:-

  1. Creation of  new JVM 
  2. Memory allocation to JVM.
  3. JVM loads MainClass into Memory with the help of class loader.
  4. Execution of Main Method by JVM.


Creation of  new JVM
After invoking the application with the help of command "java MainClass". The first step is java process will create new jvm with unique id to manage the process. This unique id is used to identify your process from other running process.

Memory allocation to JVM
After creating the JVM, java process will allocate the memory to JVM based on the JVM parameter set by the java user, if not it takes default value.  Default values depends on the actual environment (32 bit  or 64 bit operating system). Allocation of memory for heap, stack, class area, native area , etc are done in this step.

JVM loads MainClass into Memory with the help of class loader
Once the memory is allocated, next step is, JVM loads the MainClass into memory with the help of ClassLoader (click to read detailed explaination class loader and its execution life cycle). 

Execution of Main Method by JVM
After loading of MainClass into memory, JVM call the static main method by using class name MainClass.main(args) with the help of parameter passed by the user. JVM construct the String array based on the input given by the user while invoking the java command. In this above case its empty, So JVM calls main method with empty String array argument. After that your execution will continue depends on your business logic.

In case if JVM doesn't find main method , it throws 
"java.lang.NoSuchMethodError: main Exception in thread 'main'"


That's all about Java Process.



If you like the above solution . Please share this blog

   

Thursday 1 December 2016

what is class loader and its execution life cycle ?

Class loader is part of JRE, which is responsible to load all the required classes dynamically in memory , it helps JVM initialize and execute the java application without knowing the files located in the system. With the help of class loader, JVM execute the byte code of .class files which is compiled from .java files by java compiler (javac).

In java, there are 3 types or hierarchy in the class loader.
  1. Bootstrap loader, parent class of all loader.
  2. Extension loader, extends bootstrap loader.
  3. System or Application loader.

1) Bootstrap class loader

Parent class of all loader and core part of JVM, which loads the java core libraries or classes located from <JAVA_HOME>/jre/lib/rt.jar.It is written in native code. 

2) Extension loader

Extension class loader extends bootstrap loader , which loads the java classes from the <JAVA_HOME>/jre/ext directory or any other directory specified by java.ext.dirs system property. Extension loader is implemented by the sun.misc.Launcher$ExtClassLoader class.

3) Sytem or Application class loader

System class loader extends Extension loader and loads all the classes from java.class.path which  is CLASSPATH environment variable,-classpath or -cp option, Class-Path attribute of Manifest inside JAR file.  System loader is implemented by the sun.misc.Launcher$AppClassLoader class.


Life cycle of class loader






When JVM is requesting the object of Employee.class with the help of System class loader, it delegates control to its super class Extension loader and in turn its delegates to its super class Bootstrap class loader. Bootstrap try to looks from <JAVA_HOME>/jre/lib. if present it returns the Employee class definition otherwise, Extension loader take care of the control to load from <JAVA_HOME>/jre/ext directory or any other directory specified by java.ext.dirs system property.if present, it returns the Employee class definition, otherwise its subclass System loader looks from CLASSPATH. If class is not present in any of the class loader, then application throws ClassNotFoundException, otherwise it loads the Employee.class in the memory , which helps JVM to execute the application.  The entire life cycle works in the concept of delegation principle.


That's all about what is class loader and its execution life cycle.




If you like the above solution . Please share this blog






Wednesday 30 November 2016

Print boundary or edge node of tree in anti-clockwise order

This question was asked in amazon interview. we all know that, binary tree is applicable only for numeric values, and each node has left and right node as child node and last node in tree is called leaf node(node doesn't have left and child node). 


Lets look at the below binary tree





Solution:-

Traverse and print all the left-boundary from root node in top-down direction(22,16,8), then leaf node of all the left-sub tree from left to right direction(6,10,21), then left node of the all the right-sub tree from left to right direction(23,31,33) and finally print right boundary from bottom to top direction(32,24). If you see the printed node, it doesn't print the node 20, because it's not a boundary node).

The above solution will break into 4 steps.

  1. Traverse and print all the left-boundary(except leaf node 6) from root node in top-down direction(22,16,8).
  2. Print leaf node of all left-sub tree from left to right direction (6,10,21).
  3. Print lead node of all right-sub tree form left to right direction(23,31,33).
  4. Finally print all right boundary from bottom to top direction(32,24).
Code:-

class Node 

{
    int data;
    Node left, right;
  
    Node(int item) 
    {
        data = item;
        left = right = null;
    }
}
  
class BinaryTreeBoundary 
{
    Node root;
  
    // function to print leaf node of a binary tree
    void printLeaf(Node node) 
    {
        if (node != null) 
        {
        printLeaf(node.left);
  
            // Print if it is a leaf node
            if (node.left == null && node.right == null)
                System.out.print(node.data + " ");
            printLeaf(node.right);
        }
    }
  
    // Print all left boundry nodes, except a leaf node in TOP DOWN manner
    void printLeftBoundary(Node node) 
    {
        if (node != null) 
        {
            if (node.left != null) 
            {
                  
                // to ensure top down order, print the node before calling itself 
                System.out.print(node.data + " ");
                printLeftBoundary(node.left);
            } 
            else if (node.right != null) 
            {
                System.out.print(node.data + " ");
                printLeftBoundary(node.right);
            }
        }
    }
  
    // Print all right boundry nodes, except a leaf node in BOTTOM UP manner
    void printBoundaryRight(Node node) 
    {
        if (node != null) 
        {
            if (node.right != null) 
            {
                // to ensure bottom up order, print the node before calling itself 
                printBoundaryRight(node.right);
                System.out.print(node.data + " ");
            } 
            else if (node.left != null) 
            {
                printBoundaryRight(node.left);
                System.out.print(node.data + " ");
            }
        }
    }
  
    // Function to do boundary traversal in anti-clock wise direction
    void printBoundary(Node node) 
    {
        if (node != null) 
        {
            System.out.print(node.data + " ");
  
            // Step 1:- Print the left boundary in top-down manner.
            printLeftBoundary(node.left);
  
            // Step 2:- Print all leaf nodes of left-subtree from left-right direction
            printLeaf(node.left);
            // Step 3:- Print all leaf nodes of right-subtree from left-right direction            
            printLeaf(node.right);
  
            // Step 4:- Print the right boundary in bottom-up manner
            printBoundaryRight(node.right);
        }
    }
       
    public static void main(String args[]) 
    {
        BinaryTreeBoundary tree = new BinaryTreeBoundary();
        tree.root = new Node(22);
        tree.root.left = new Node(16);
        tree.root.left.left = new Node(8);
        tree.root.left.left.left = new Node(6);
        tree.root.left.left.right = new Node(10);
        tree.root.left.right = new Node(20);
        tree.root.left.right.right = new Node(21);
        
        tree.root.right = new Node(24);
        tree.root.right.left = new Node(23);
        tree.root.right.right = new Node(32);
        tree.root.right.right.left = new Node(31);
        tree.root.right.right.right = new Node(33);
        tree.printBoundary(tree.root);
  
    }
}

output:-
22 16 8 6 10 21 23 31 33 32 24 


Time Complexity: O(n). Traversing all the elements in array





If you like the above solution . Please share this blog

Tuesday 29 November 2016

Amazon question: Calculate total amount of rain water trapped between the towers.

This question was asked by amazon , to calculate the amount of water trapped between the  towers with the help of given array which consists of height of the each tower.

For example: input : int tower = {4,2,3,5,2,3,4,5};


For the above example , the output, i.e.Total amount of the water is the summation of water stored in the tower 2,3,5,6 and tower 7. i.e (2+1+3+2+1=9).

The logic should work for all the scenario, means tallest tower can be located anywhere, it can be first, last or in any position. Lets see the below towers.

Example 2:- input: int tower = {5,0,5,2,5,3,4,5}



Logic :-
  
The logic would be, for every tower calculate the highest height of the tower from left and highest height of tower from the right and then use minimum height of these two tower, to calculate the amount of water. For example:- 

From the above figure 1:- For tower 2, highest height of the tower from left is tower 1(4) and highest height of the tower from right is tower 4(5), then take minimum height of this two tower(4), and subtract the height of tower 2(2) from this minimum tower(4), this will be the amount of water trapped for the tower 2. The output will be (4-2) = 2. Repeat the above step for all the tower and add the output of water trapped for each tower. This will be the total amount of rain trapped between the towers.


Algorithm:-

Step 1: Declare left and right array to store the highest height from left and right side of the each tower and waterAmount to calculate the total amount of water trapped between the towers.
Step 2: Traverse the input array(height of all the towers) and  calculate the maximum height of tower from the left and from the right of each tower and assign to left and right array respectively.
Step 3: Again traverse the input array and calculate the amount of trapped water for all the tower and add the result to waterAmount value.

Code:-

import java.util.Arrays;
public class RainwaterStorage{

public static void main(String[] args) {
int tower[] = {4,2,3,5,2,3,4,5}; // height of all the tower
System.out.println(findWaterAmount(tower, tower.length));
}

public static int findWaterAmount(int tower[], int count)
{
   int left[] = new int[count];
   int right[] = new int[count];
   int waterAmount = 0;   
   // Fill left array (contain maximum height tower value from the left of each tower)
   left[0] = tower[0];
   for (int i = 1; i < count; i++)
      left[i] = Math.max(left[i-1], tower[i]);

   // Fill right array (contain maximum height tower value from the right of each tower)
   right[count-1] = tower[count-1];
   for (int i = count-2; i >= 0; i--)
      right[i] = Math.max(right[i+1], tower[i]);

   // below code is to find the amount of trapped water for all the tower and add the result to waterAmount value. 
   for (int i = 0; i < n; i++) 
       waterAmount+= Math.min(left[i],right[i]) - tower[i];

   return waterAmount;
}
}

Output:-
9

Performance:- 
Time Complexity: O(n). Traversing all the elements in array
Auxiliary Space: O(n). Additional aray to store maximum value of the tower from the left and from right.





If you like the above solution . Please share this blog

Friday 25 November 2016

why java doesn't allow to create object for abstract class and interface ?

In interview, most of the people will explain about abstraction and interface, when interviewer ask why java doesn't allow to create object for abstract class and interface, all got struck. Here i  am gonna explain the reason with real time example.

The abstract class and interface represents the  more generic form or abstract entity, for example animal,vehicle and shape(It doesn't represent real entity). These abstract entity doesn't stand on its own. Because each animal (cat, lion,tiger, elephant, etc) ,vehicle(car, bus, aeroplane, train, etc) , Shape (circle, square, rectangle) which define its own property and behavior.  There's no such thing as a "pure" animal - there are specific types of animals . And you cannot call car as vehicle, does it make any sense in real time.

And also technically in java, abstract method may contain abstract method and implementation method. Just think, if java allowed you to create object, when you are calling the abstract method ,  what result it will deliver ? The same concept applicable for interface also.

Both the concept will be used to make proper design in the application in order to achieve more flexible and expandable.

Also you can use abstract and interface as template, sub class or real time entity can extend and built on it before you can use it.

Also some people say, abstract class and interface are incomplete class, so JVM doesn't know how much memory is required to create object. So it doesn't allow to create objects. This answer also acceptable.  But definitely, this is not a exact answer interviewer will look. So please give some real time example and explain in detail.








If you like the above solution . Please share this blog




Thursday 24 November 2016

Design LRU cache and explain with real time example in java

Least Recently Used Cache - The limited or LRU caching technique is used to stored only the recently used data and expires the one which is least recently used whenever the new entry into the cache.

Cache removes least recently used item while making entry for a new one.

Let's see the below scenario. In a trading system, they want to maintain the 5 recently used product to do future analysis. LRU is used in this case.

For example :  From above scenario, trading system want to store 5 recently executed product from the list of 10 products(A,B,C,D,E,F,G,H,I,J). Trading system execute first five product in the order A,B,C,D and E. The below picture depict the LRU cache
                   E -- D -- C -- B -- A  

Where 'E' is the recently used and 'A' is the least recently used. Now, trading system execute another product 'F', now LRU cache has to remove 'A' and add 'F' to the cache. Now the above cache looks like below
                   F -- E -- D -- C -- B 

What happen if trading system execute the product 'C' which is already in the LRU cache. The cache has to remove the 'C' product and add it to the beginning of the cache
                  D -- F -- E -- C -- B 

if system execute new product 'G', then B is removed.
                  G -- D -- F -- E -- C 

if system execute again product 'D' , then 'D' is removed and added to the beginning of the cache.
                   D -- G-- F -- E -- C 

if system execute new product 'H',  then 'C' is removed. Now the cache looks like below.
                    H -- D -- G-- F -- E    

By repeating the above logic, LRU store recently used 5 product in the cache.





If you like the above solution . Please share this blog

How array is giving better performance while retrieving element based on its index?

The answer is array stores all the element in the Contiguous Memory Allocation. Based on the base memory address (address of first element in the array),  array increase its pointer by adding the index which is passed.  For example: array[4] , index 4 will be added to the pointer and now pointer will be pointing fourth element of array.  Lets see the below explanation.

we all know that, array is a list of  element's of same data type. It can be primitive data type such as int, char, double, float or it can be user defined data type such as Objects.

we can access those elements based on the index(starts with 0 - first element). So each element in a array is sequentially associated with the index of the array.  For example:

     int a[] = {12,13,17,15,18,19}

    12 = index 0
    13 = index 1
    17 = index 2
    15 =    ...    3
    18 =    ...    4
    19 = index 5

  Array size is 6 

In JVM, there are different type of approach is followed while allocating memory based on the data type. Array is based on contiguous memory allocation(one of the oldest memory allocation scheme), memory is allocated sequentially for all the elements in array. Lets see how the memory allocation is done for the above array.

In java, int variable takes 4 byte as size, the above array need 24 bytes (size*4 bytes = 6*4 = 24 bytes) in memory.  The below image depicts the allocation in memory.



In the above chart, memory allocation starts from 1000 and allocating 4 bytes for each elements from the array. Base pointer always store the starting address of the array. While accessing, based on the index, array pointer will take summation of base pointer with (index * size of data type) to fetch the exact value of the array element.

For example:-
      int fourthElement = a[3];


The above code will have below logic in the system code.
            int array_pointer = (index*byte of int) + Base pointer
            int array_pointer = (3*4)+1000 = 1012 (Fourth element address).

The same logic is applicable for all the data types. Because of this logic, array doesn't traverse through all the elements  in the array.  

This implementation gives more performance while retrieving the element based on its index.




If you like the above solution . Please share this blog




              
  




   
   

     
s