Thursday, 28 November 2013

NoClassDefFoundError vs ClassNotFoundException

Difference between ClassNotFoundException vs NoClassDefFoundErrorBefore seeing the differences between ClassNotFoundException and NoClassDefFoundError let's see some similarities which are main reason of confusion between these two errors:

1) Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
2) Both ClassNotFoundException and NoClassDefFoundError are related to java classpath.

Now let's see the difference between NoClassDefFoundError and ClassNotFoundException:

1) ClassNotFoundException comes in java if we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass() or ClassLoader.findSystemClass() method and requested class is not available in Java. the most of the time it looks like that we have the class in classpath but eventually it turns out to be issue related to classpath and application may not be using classpath what we think it was using e.g. classpath defined in jar's manifest file will take precedence over CLASSPATH or -cp option, for more details see How classpath works in java. On the other hand NoClassDefFoundError is little different than ClassNotFoundException, in this case culprit class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason.

2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it while NoClassDefFoundError is an Error derived from LinkageError.

3) If you are using classloaders in Java and have two classloaders then if a classloader tries to access a class which is loaded by another classloader will result in ClassNoFoundException.

4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass, Class.forName while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.

SAX VS DOM

DOM Stands for Document Object Model and it represent an XML Document into tree format which each element representing tree branches.
SAX Stands for Simple API for XML Parsing. This is an event based XML Parsing and it parse XML file step by step so much suitable for large XML Files.

Here are few high level differences between DOM parser and SAX Parser in Java:

1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.

2) DOM parser is faster than SAX because it access whole XML document in memory.

3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much memory.

4) DOM parser works on Document Object Model while SAX is an event based xml parser.
I suggests use DOM parser over SAX parser if XML file is small enough and go with SAX parser if you don’t know size of xml files to be processed or they are large.

Java class loaders

Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So, how is the very first class loaded? The very first class is especially loaded with the help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader.

Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.



Bootstrap (primordial) :

Loads JDK internal classes,


java.*

packages. (as defined in the sun.boot.class.pathsystem property, typically loads rt.jar and i18n.jar)

Extensions :

Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system
property – usually lib/ext directory of the JRE)



System :

Loads classes from system classpath (as defined by the java.class.path property,which
is set by the CLASSPATH environment variable or -classpath or -cp command line options)
Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded

Which one returns the value when try return and finally returns are there

This is some tricky question

Lets say below code

public int getValue()
{
try
{
return 2;
}
finally
{
return 3;
}
}

when called the above method System.out.println(getValue()) what is the output

It always returns thr finally return , i.e the answer is 3

How Hash Map works internally

General answer :HashMap accept null while Hashtable doesn't,
HashMap is not synchronized,
HashMap is fast and so on along with basics like its stores key and value pairs etc.

Experts answer :
------------ ---- ---------------- ----------------
| |.................| | .................| |....................| Bucket1 | |Node1 | | |
------------- --- ---------------- ----------------
:
:
------------ ---- ---------------- ----------------
| |.................| | .................| |........................
| Bucket2 | |Node1 | | |
------------- --- ---------------- ----------------
:
:
------------ ---- ---------------- ----------------
| |.................| | .................| |...........................
| BucketN | |Node1 | | |
------------- --- ---------------- ----------------

HashMap works on principle of hashing,
we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap.
When we pass Key and Value object to put() method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, here important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket , not only value
What happens when two different objects have same hashcode :

Basically hascode implementation says below rules:
rule 1: If obj1 and obj2 are same it must give same hashcode ,
rule 2: If obj1 and obj2 have same hashcode then they are not need to be equals

Basically Map uses the linkedlist to store Map.Entry object Entry would be having key and value pair
If the different object is also having same hash code then Map will store the Entry object in the same bucket but in the linked list next consequent node
How it retrieves :
When retriving first it gets hash code by calling hashcode() then it identify the target bucket , but when retrieving it calls equals method to get exact object ,if it calls equals method on key object it gives the desired object even if the two different objects having hash code

Which is best practice to implement hashcode and equals ()?

User immutable objects i.e final object with proper equals() and hashcode()
Generally Immutability also allows caching there hashcode of different keys which makes overal process very fast
User wrapper classes like String,Integer...
If used custom objects make it immutable

what happens when resizing HashMap in multithreding scenarios:

Hash map uses the default initial capacity is 16 and load factor is 0.75f
since it is not synchronized it is not suggestable to use in multithreading scenario
if it is really required make it synchronize:
Map map = Collections.synchronizedMap(new HashMap(...))

whcih data structure you use for mobile contact list

which data structure will be used for storing mobile contact list and If enter "ma" it should show all contacts in sorted list starting with ma letters.


Many people give answers we can use Hashtable or Array list but those are suitable but that is wrong answers , try with Binary search tree.

A hash table can insert and retrieve elements in O(1) .
A BST can insert and retrieve elements in O(log(n)), which is quite a bit slower than the hash table which can do it in O(1).

Try using Hash table :

When designing a cell phone, we need to think much about memory. A hash table is an unordered data structure – which means that it does not keep its elements in any particular order. So, if you use a hash table for a cell phone address book, then you would need additional memory to sort the values when user enters input So, by using a hash table you have to set aside memory to sort elements . i.e it requires more memory.

Try with BST(Binary Search tree)

Because a binary search tree is already sorted, there will be no need to waste memory or processing time sorting records in a cell phone. As mentioned earlier, making a lookup or an insert on a binary tree is slower than doing it with a hash table, but a cell phone address book will almost never have more than 5,000 entries. With such a small number of entries, a binary search tree’s O(log(n)) will definitely be fast enough. So, given all that information, a binary search tree is the data structure that you should use in this scenario, since it is a better choice than a hash table or Array list

How you update two columns in a table

How you update two columns in a table ? write a query to update two columns in a table ?

It is simple if we want to update a single column in a table we can use the below query

UPDATE TABLE "table-name" SET "column-name" = [new value] WHERE {condition}

e.g:
UPDATE TABLE employee SET ename="madhava" WHERE eid='1';

but the query to update multiple columns is as below

UPDATE TABLE "table-name" SET ("column1" , "column2") = ([new value1],[new value2])
WHERE ={condition }.

How to find top 5 process which are using more memory in linux

One of my friend asked this question in a company

use below command to find top n process which are using more process



ps -eo pmem,pcpu,vsize,pid,cmd | sort -k 1 -nr | head -5


here e --- means every process i.e all process
o --- optional format
k --- memory in killo bytes
n --- sorting on number
r --- revert the sort i.e descending order

The power of find command in linux

This is power full command in linux , which can be used for multiple purpose find some

1. find the files which modified less than one day or exactly one day or more than one day


command: find . -mtime 1 ---> to find exactly one day

command: find . -mtime +1 ---> to find more than one day

command: find . -mtime -1 ---> to find less than one day


2. find the files which have only read permissions

command : find . -mperm 444

How to preven accessing cookies from client side scripting

Using HttpOnly flag in side the cookie we can prevent cookie information from client side scripting

In side java code , write the code as below:

Cookie cookie = getMyCookie("myCookieName");
cookie.setHttpOnly(true);

The same effect can be configured inside the  WEB-INF/web.xml in your application
<session-config>
<cookie-config>
  <http-only>true</http-only>
</cookie-config>
<session-config>

For more information check this link :

https://www.owasp.org/index.php/HttpOnly