Showing posts with label Java interview Question. Show all posts
Showing posts with label Java interview Question. Show all posts

Java interview question for Apache ofbiz developer in vinculum solution pvt ltd on dated 02.05.2013

Following below java interview question that has asked by vinculum solution pvt ltd , noida for Apache ofbiz developer

Date 02.05.2013

1. Tell about your role and responsibility in your project

2. Tell how you integrate Apache ofbiz to Magento e-commerce.

3. How to validate XML file

4.  Can we use Hibernate in Apache ofbiz for ORM instead for Entity model.

5. What is serialization and exterlization in java

6. How to override equals method and what importance of Hashcode .

7. About Hibernate HQL and Criteria.

8. About Struts flow.

9. How can you count number of active session in your application.

10. Forward and sendRedirect method

Java interview question related Session listner, web services in MNC software company

Below Few Java interview question asked at MNC software company

1. How can you count active sessions by using listeners in JAVA.

we can do it by using HttpSessionListener for that you can create a session count class implementing HttpSessionListener interface. Our listener object will be called every time a session is created or destroyed by the server. You can find more information about HttpSessionListener at When do I use HttpSessionListener?.
 
Code  example,
 we have MySessionCounter.java that implements HttpSessionListener interface. We implement sessionCreated() and sessionDestroyed() methods, the sessionCreated() method will be called by the server every time a session is created and the sessionDestroyed() method will be called every time a session is invalidated or destroyed.


package com.xyzws.web.utils;

import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;

public class MySessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}

public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}

public static int getActiveSessions() {
return activeSessions;
}


To receive notification events, the implementation class MySessionCounter must be configured in the deployment descriptor for the web application. add <listener> section into our /WEB-INF/web.xml file:

   <!-- Listeners -->  <listener>    <listener-class>com.xyzws.web.utils.MySessionCounter</listener-class>  </listener>

For show in JSP
 the following JSP code shows the total active session:
 <%@ page import="com.xyzws.utils.MySessionCounter"%><html>...  Active Sessions : <%= MySessionCounter.getActiveSessions() %>...</html>

2) what is XML schema and it tags??
 
Definition
An XML Schema defines and describes certain types of XML data by using the XML Schema definition language (XSD). XML Schema elements (elements, attributes, types, and groups) are used to define the valid structure, valid data content, and relationships of certain types of XML data. XML Schemas can also provide default values for attributes, and elements.


XML Schema has contains below :

  • The first statement, <?xml version="1.0" encoding="utf-8"?>, specifies the version of XML in use.

  • The second statement consists of several parts:

The xs:schema declaration indicates that this is a schema and that the xs: prefix will be used before schema items.

The xmlns:xs="http://www.w3.org/2001/XMLSchema" declaration indicates that all tags in this schema should be interpreted according to the default namespace of the World Wide Web Consortium (W3C), which was created in 2001.

The targetnamespace declaration names this schema as XMLSchema1.xsd and indicates its default location, which will be in a default URI (universal resource identifier) on your development server called tempuri.org.

When you create a schema with the XML Designer, the version and namespace statements are automatically added for you. You might modify the contents of these two declarations in some cases. For example, if you want to use a tag prefix other than "XS," you would need to define the default namespace for that tag in addition to the XS tag prefix.

A complex type called "addressType" is defined that will contain five elements of various data types. Note that each of the elements it contains is a simple, named type.


Example

How to write XML schema of below requirments
The final element in the purchaseOrder, Item, contains a facet called maxOccurs. Facets set limits on the type of content a simple type can contain. maxOccurs is used to constrain how many times an element can occur in the documents created from this schema. By default, maxOccurs is equal to one. In this case, setting it to unbounded indicates that the Item element can reoccur as many times as needed.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="addressType">
   <xs:sequence>
      <xs:element name="street1" type="xs:string"/>
      <xs:element name="street2" type="xs:string"/>
      <xs:element name="city" type="xs:string"/>
      <xs:element name="state" type="xs:string"/>
      <xs:element name="zip" type="xs:integer"/>
   </xs:sequence>
</xs:complexType>

<xs:element name="purchaseOrder">
      <xs:complexType>
         <xs:sequence>
            <xs:element name="shipTo" type="addressType" />
            <xs:element name="billTo" type="addressType" />
            <xs:element name="shipDate" type="xs:date" />
            <xs:element name="item" maxOccurs="unbounded"/>
         </xs:sequence>
      </xs:complexType>
   </xs:element>
</xs:schema>

HashMap working concept in Java | how hashMap internally working

How HashMap works in Java or sometime how get method work in HashMap is common interview questions now days. Almost everybody who worked in Java knows what hashMap is, where to use hashMap or difference between hashtable and HashMap then why this interview question becomes so special? Because of the breadth and depth this question offers. It has become very popular java interview question in almost any senior or mid-senior level java interviews.

Questions start with simple statement

"Have you used HashMap before" or "What is HashMap? Why do we use it “

Almost everybody answers this with yes and then interviewee keep talking about common facts about hashMap like hashMap accpt 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.
This shows that person has used hashMap and quite familiar with the functionality HashMap offers but interview takes a sharp turn from here and next set of follow up questions gets more detailed about fundamentals involved in hashmap. Interview here you and come back with questions like

"Do you Know how hashMap works in Java” or
"How does get () method of HashMap works in Java"

And then you get answers like I don't bother its standard Java API, you better look code on java; I can find it out in Google at any time etc.
But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls
hashcode() method hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java.
But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap e.g

"What will happen if two different objects have same hashcode?”

Now from here confusion starts some time interviewer will say that since Hashcode is equal objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them about equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say "Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list." great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap does follow this.
But story does not end here and final questions interviewer ask like

"How will you retreive if two different objects have same hashcode?”
 Hmmmmmmmmmmmmm
Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retrieves object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify value object because you don't value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won't be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashcode () and equals () and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap.
Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.

Now if you clear all this java hashmap interview question you will be surprised by this very interesting question "What happens On HashMap in Java if the size of the Hashmap exceeds a given threshold defined by load factor ?". Until you know how hashmap works exactly you won't be able to answer this question.
if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location.

If you manage to answer this question on hashmap in java you will be greeted by "do you see any problem with resizing of hashmap in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java.

So the answer is Yes there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java hashmap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. if race condition happens then you will end up with an infinite loop. though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer :)

I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap questions has verified
Concept of hashing
Collision resolution in HashMap
Use of equals () and hashCode () method and there importance?
Benefit of immutable object?
race condition on hashmap in Java
Resizing of Java HashMap

Just to summarize here are the answers which does makes sense for above questions

How HashMAp works in Java
HashMap works on principle of hashing, we have put () and get () method for storing and retrieving object form hashMap.When we pass an both key and value to put() method to store on HashMap, it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object.
While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap uses linked list in case of collision and object will be stored in next node of linked list.
Also hashMap stores both key+value tuple in every node of linked list.

What will happen if two different HashMap key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.

In terms of usage HashMap is very versatile and I have mostly used hashMap as cache in electronic trading application I have worked . Since finance domain used Java heavily and due to performance reason we need caching a lot HashMap comes as very handy there.






Explains Classloaders in Java | How the Class-loading mechanism work in Java?

At Many Java interview question for Senior developer requirement . i faced question related to classloader in java . below important listed interview question i faced most times.

Classloaders in Java

Classloaders are the Java program(s) i.e., Java classes that are responsible for loading classes into the underlying JVM. Any class before being used, should first be available and accessible to the classloader, which will load the class into the memory and then only the JVM can perform any task on it. Having said that we see that all the classes in Java are first loaded into the memory by a classloader (normally the default classloader) and then only the class can be used in any possible way. Right? We just said that classloaders are also Java classes only. Now, who loads this classloader classes then? Good pick, if you really picked it :-) The answer to this question is - the bootstrap classloader. Ohh... again a classloader. Yeah, it is, but different from what we discussed above. It's a native classloader and not written in Java. This bootstrap classloader is platform dependent (of course, that's why we called it native) and it's normally written in C.

How the Class-loading mechanism work in Java?

Whenever you try to execute a Java program by invoking the 'java' command then a native Java launcher program is first invoked. This launcher program is 'native' and hence platform dependent. Well... quite obvious, isn't it? Now, on a successful invokation of this launcher program, it calls the bootstrap classloader program. This bootstrap loader program then loads the Core Java classes (classes belonging to the packages starting with 'java.') and then loads two other classloaders - extension classloader and application classloader. That's it. The job of the bootstrap classloader is done once it completes these three tasks - One, loading Core Java classes; Two, loading extension classloader; Three, loading application classloader.

The bootstrap classloader transfer the control to the extension classloader, which then loads the extension classes into the memory. What are extension classes in Java? They are classes belonging to all the packages starting with 'javax.' OR the classes present in the 'ext' directory of the underlying JRE. You may like to go through the post Extension Mechanism in Java for more details.

Finally the control is transferred to the application classloader, which loads the classes of the current application.

Explains delegation model working in classloading

One interesting point to note here is that all the three classloaders follow the delegation model i.e., if the application classloader requires to load a class, it'll first delegate a request for the same class to the extension classloader, which will in turn send a request to the bootstrap classloader for the same class. Now, the bootstrap classloader will check if that class is a Core Java class or not. If yes, then it'll make that available to the extension classloader in response to its request and finally the extension classloader will make that available to application classloader. If the bootstrap classloader discovers that the requested class if not a Core Java class, it notifies the same to the extension classloader. Now the extension classloader checks if this class is an extension class or not. If it discoveres that it's an extension class, it makes that available to the application classloader otherwise it notifies the application classloader that the requested class is not even an extension class. The application classloader itself loads a class in this case (when it has got notifications that the requested class is neither a Core Java class nor an extension class).