Wednesday, January 29, 2014

Core Java Interview Questions

                   

Any java interview be it for fresher or for experienced professional will have an interview round completely focusing on Core Java. For experienced candidates this is usually the first round.
I am enlisting few of the most popular core java questions.

1.Interview questions for freshers.
2.Interview questions for experienced .


1.Interview questions for freshers.


  1. What is Class?
Ans. Class is a template. It specifies the data members and possible operations on its data  members.
  1. What is Object?
Ans. Object is an instance of class.
  1. What is an abstract class?
Ans. Abstract class is a special type of class which cannot be instantiated. The purpose of                                      
        Using abstract classes is to provide the Common functionality to all the subclasses.
  1. What is interface?
Ans. Interface is a way to achieve full abstraction in java. All the methods in  an interface do not have body.
      Any class implementing interface should fulfill the contract to implement all the methods in the interface. This behavior allows us to use Run time polymorphism to fullest.
  1. What is difference between abstract class and interface? when will you use the abstract class?
a.       Abstract classes represent partial abstraction. Interfaces represent full abstraction.
b.      The purpose of using abstract classes is to provided abstraction for a few methods and provide some common default implementation for some methods. Whereas interfaces are used when you want all the subclasses to provide their own implementation to all methods.
c.       It is always preferable to implement an interface then extending an abstract class. As once your class extend an abstract class it cannot extend any other class.

  1. A class may extend maximum of how other many classes?
Ans A class in java can extend at most one class.
  1. Does Java supports multiple inheritance?
Ans. Java does not support multiple CLASS inheritance, as it creates some major problems like Diamond problem in c++.  However Java supports Multiple interface implementation. So your class can implement multiple interfaces.
  1. What are the four main concepts of object oriented languages? Explain all four?
Ans- Four major concepts are
1.      Abstraction
2.      Encapsulation
3.      Inheritance
4.      Polymorphism
  1. What are types of  relationship between objects?
Ans-
a.       Association- Class A uses class B. This relationship is used when one object wants to use other object to perform some service for it. Association also specifies the multiplicity between objects.
Note-  There is no ownership between objects, Both have independent lifecycle.
Example- Teacher and student. A teacher can

b.      Aggregation- Class “A” has an instance of class “B” . So Aggregation is special type of association , it is directional association between object . Direction specifies which object contains other object.

 where instance of Contained class(B) can independently exist even without instance of parent class (A).

c.       Composition- Composition is a stricter form of aggregation. Where a Contained object cannot exist without container object.
Example- A line item cannot exist without Order.

  1. What is inheritance? explain with example.
Ans Inheritance is a feature in java which allows a new class(derived class) to be derived from other class(base class). There by allowing the  derived class to inherit the properties and methods of the base class. This helps improve the code reuse.
       
      11.  What is polymorphism? explain with example.
Ans. Polymorphism means, ability to behave differently in different context. In term of java
Polymorphism  is the ability of calling the  methods based on type of the object  not based on the type of reference.
In java reference of the base class can refer to the object of derived class.
Class a{
Public void fun(){
System.out.println(“ Function of class a called”);
}
}
Class b extends a{
Public void fun(){
System.out.println(“ Function of class b called”);

}
}

   // calling code
        a aobj=new b();
        b.fun();// this will call the fun method of class b
      So the method being called is based on the type of object (class b) not based on the refrence(class a);
  1. What are different types of polymorphism?
a.       Static polymorphism. Example- method  overloading
b.      Dynamic polymorphism example- method overriding.
  1. What is the base class of all the classes?
Object class is base class of all objects.
  1. What is difference between JVM, JRE and JDK?
JDK- Java development kit includes the tools, binaries and java classes  used for  
Developing, compiling and running java programs. JDK includes tools like compiler, visualvm ect.
JVM- Converts the byte codes to machine specific code, and critical functionalities like
 Memory management, garbage collection and security.
JRE- Java runtime environment is implementation of JVM, it is the platform to execute java programs. It contains jvm, java binaries and other custom binaries to execute java program. JRE does not includes development specific tools like compiler.

  1.  How Java  achieves platform independence?
  2. What is stack?
  3. What is heap?
  4. Java is call by reference or call by value?
  5. What is garbage collector?
  6.  How can you call garbage collector?
  7. What is equals function of Object class used for ?
  8. what is difference between == and equals() function?
  9. What is thread?
  10. What is difference between thread and process?
  11. What are different ways to create a thread? which is preferred way?
  12. What are the functions of object class-  wait,notify and notifyall  used for? or how will threads inter communicates?
  13. What is synchronized key word in java?
  14. What is deadlock? 
  15. what is thread starvation?
  16. What are Executor interface?
  17. Write a program to simulate producer consumer problem?
  18. What do you mean by string is immutable? 
  19. What is  String pool?
  20. Write a program to Reverse a string.
  21. Write a program to generate a Fibonacci sequence.
  22. Write a program to check if a string is java palindrome?
  23. Write a program to check if two given strings are same? do not use .equals function?
  24.  What is Collection framework in java?
  25.  What is List, Map, Set interfaces? what are there concrete implementation classes?
  26. What is difference between list and set implementations?
  27. What is difference between a list and a map?
  28.  What is difference between Hashtable and Hashmap?
  29.  What is Exception in java?

Core Java Interview questions for experienced Java developers

 

  Core Java Interview questions for experienced Java developers

 Well the interview questions for experienced java candidates vary based on the experience and the
  JD. Following is the list of  very frequently asked Core Java questions .
  1. What is class loader? 
  2. What is are different types of class loader?
  3. Can you have two instance of a singleton class?
  4. Which class loader is used when you execute main method of the your class, where does it picks searches the file?
  5.  What is static class loading & dynamic class loading, give example and difference?
  6.  Diff b/w ClassDefNotFound and NoClassDefFound exceptions.
  7.  what is checked and unchecked exception.
  8.  Draw the exception class hierarchy.
  9.  How will you create  your own exception class?
  10.  what is  difference between instanceOF and isInstance?
  11.  what is difference between final,finally,finalize?
  12.  How many types of reference are there in java?
  13.  what is soft refrence,weak refrence,phantom refrence?
  14.  what is weak hash map?
  15. what is stringpool , intern method?
  16. what is  diff b/w stringbuilder and string buffer?
  17. How do you make a class immutable. example with a class having a date object.?
  18. What are Atomic variables?
  19. Difference between equals and == ?
  20. Draw collection hierarchy.
  21. What are concrete implementations of list,set, map interfaces?
  22. What is difference between hashmap and hashtable?
  23. What method calls would be made internally, when i call get and put  function on a hash map.
  24. what is the return value of put function in hashmap?
  25. Why do objects have Hashcode and equals method?
  26.  How does hash map internally stores the data?
  27. What special methods do i need  to implement i want my class object to be key of a hashmap? 
  28. Why do objects have equals method? What would the code of equals method look like?
  29. Write your own hashmap implementation?
  30.  Write your own list implementation?
  31.  How can you make a singleton class?
  32.  what will happen when you de-serialize a single tone  object having  reference to itself?
  33.  LRU CACHE implementation, which Class will you use and why?
  34. What is ConcurrentHashMap, explain internal element storage and retrieval by multiple threads?

Sunday, September 16, 2012

Jforum Integartion with existing webapplication

JForum is a powerful and robust discussion board system implemented in Java.

There are various ways to integrate JFourm with a existing web application.
1. Co-Exist as a seprate web application with a existing web application.
2. Embedd Jforum in your web application.

It is suggested to use the approach 1(Jforum Co-Exist as a separate web application), as in this approach the only Change you need to do in your application code is to provide a link to JForum. This is just a view(jsp) level change. You do not make your application clumsy, complex and jforum dependent using this approach.

In this tutorial i will focus on approach 1(Jforum Co-Exist as a separate web application).

JForum Installation
1. Download jforum-2.1.8 zip from Here

2. Rename directory as JFroum and deploy it (copy it to webapp of tomcat) as a separate application

3. It is better to install Jforum tables in seprate database.create desired database in mysql using sql command:

Create database db_name

4. run tomcat and access following url:

http://localhost/JForum/install.jsp

Installation wizard will be shown,The field names are self explanatory. Provide the appropriate details and complete the setup.

It is cleaner approach to keep the JForum Database separate from the application database.
Consider your application name is “myapp”. And the app server used is tomcat.

Integrating myapp with Jforum


Our requirement is to provide Single sign on to between myapp and jforum,that is when a user who has already signed in into myapp clicks on the jforum link, User is successfully logged in into JForum(in back end, without taking any inputs from user) .
JForum uses Cookie for Authentication. Note this binds us to keep both myapp and jforu both in same domain. Best approach is to keep both myapp and jforum web applications collocated in tomcat’s webapps folder
Call flow for integration will be as follows
1. User log in into myapp.
2. User clicks on the jforum link.
3. Myapp sets cookie and opens jforum in a IFrame
4. JForum SSO module checks cookie and authenticates the user
Enough Theory, lets start coding .


Thursday, July 12, 2012

Single sign on with spring security and Siteminder

Enviorment-Spring version-3.0.5,Siteminder

Goal-Integrating Single sign on using site minder with spring security.


1.What is Single Sign On?
Single sign on is a property/concept means login once into a web portal and navigate to other supported independent portals without being prompted login again.
Say you login into portal A once, now you can navigate to supported independent portal b,portal c without need to login again.

2.what is Site minder?
Site minder is single sign on system that authenticates the user and puts a token in http request header(SM_USER).
Overview of the request request processing-
1. Consider a user say user1 in your system logs in, on successfull authentication siteminder would put a header(SM_USER) in the httprequest with value say smuser1.
2. User clicks on a link on your web page to navigate to SSO supported portalb(siteminder will again populate the request with SM_USER header token,we will not get into details here).
3. Portalb will check if the SM_USER header is available. In our sample case here SM_USER=SMUSER1.
4. portalb can further check for further check say if the SMUSER1 mapps to any user in there system if yes consider authentication done move for aurthorization check.

Spring security Support for Siteminder
Spring provide out of box support for SSO/Pre-Authentication scenarios. Refer Spring PreAuthentication documents section16.2.1 for siminder related configurations
Step 1. Create a bean to handel sso/pre-authentication,
<bean id="siteminderFilter" class="org.springframework.security.ui.preauth.header.RequestHeaderPreAuthenticatedProcessingFilter">
<property name="principalRequestHeader" value="SM_USER"/>
<property name="authenticationManager" ref="authenticationManager" />
</bean>

step 2. Specify the above bean to be used as preauth filter. Make following entry in <http.... tag


step 3. Create a Preauth provider bean,
<beans:bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<beans:property name="preAuthenticatedUserDetailsService">
<beans:bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">

<beans:property name="userDetailsService" ref="myUserDetailsService"/>
</beans:bean>
</beans:property>

<beans:property name="userDetailsChecker" ref="myUserDetailsChecker"/>
</beans:bean>

step 4. Add the preauthAuthProvider to the provider list in the authentication-manager tag.

step 5. Specify org.springframework.security.core.AuthenticationException in web.xml to handel the exceptions and show appropriate view
<error-page>
<exception-type>org.springframework.security.core.AuthenticationException</exception-type>
<location>/myportal/error</location>
</error-page>

Spring framework internal processing and hooks to put extra checks

RequestHeaderPreAuthenticatedProcessingFilter- Handles the request ,
1. checks if the header is not available throws the PreAuthenticatedCredentialsNotFoundException.
2. Iterates over the providers, as we have specified preauthAuthProvider on the top of provider list this is the first provider to be evaluated.
preauthAuthProvider calls the loadUserByUsername function of myUserDetailsService.
Note -This is the point to perform any extra check on the value coming in from the header and evaluate if value in header maps to a user in our system.
Typical implementation is

public UserDetails loadUserByUsername(String smHeadervalue) throws UsernameNotFoundException, DataAccessException {

// find it the user in my system maps to smHeadervalue
//if user is null throw exception
if (user == null) {
throw new UsernameNotFoundException("No such user");
}
return user;
}

3.Next the frame work call check function of the myUserDetailsChecker. As now we know the user exist in our system, check for various states as per your requirement ,throw exception to abort and show the error page.
This step is optional and can be avoided by removing from preauthprovider configuration.


public void check(UserDetails user) {
if (!user.isAccountNonLocked()) {
throw new LockedException( "User account is locked", user);
}
if (!user.isEnabled()) {
throw new DisabledException( "User is disabled", user);
}
if (!user.isAccountNonExpired()) {
throw new AccountExpiredException("User account has expired", user);
}

}
4. if no exception is thrown in the above steps (Authentication is successfull) , user will be checked for aurthorization . If the user hae appropriate roles
the requested page will be displayed.