Google

Feb 23, 2014

Top 20 Java technical interview questions and answers for experienced Java developers -- Part 4

Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Q17. Can you explain singleton and prototype bean scopes in Spring framework? Which one is the default? Which one is thread-safe?
A17. Understanding Spring bean scopes - Singleton Vs Protype

After Spring, the most popular third-party framework is Hibernate.

Q18. Can you explain hibernate object states? Also, explain hibernate objects life cycle?
A18. 

Persistent objects and collections are short lived single threaded objects, which store the persistent state. These objects  synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List  etc or define your own synchronization points with session.flush(), transaction.commit() calls). If you remove an item  from a persistent collection like a Set, it will be removed from the database either immediately or when flush() or commit() is called depending on your flush strategy. They are Plain Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated session is closed, persistent objects become detached objects and are free to use directly as data transfer objects in any application layers like business layer, presentation layer etc.  

Detached objects and collections are instances of persistent objects that were associated with a session but currently not associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc. and become persistent objects.

Transient objects and collections are instances of persistent objects that were never associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Transient objects become persistent objects when associated to a session by calling methods like session.save( ), session.persist( )  etc.



Q19. Why use JAXB in your Java project?
A19. JAXB interview questions and answers.

If the organization you are being interviewed for is using an agile methodology, then you will be probed on agile development practices.

Q20a. What are the pros and cons of agile development methodology
A20a.  Pros and cons of agile development methodology.

Q20b. What is the difference between agile theme, epic and story?
A20b. Understanding theme, epic, and story



Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Labels: , ,

Top 20 Java technical interview questions and answers for experienced Java developers - part 2

Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Q6. How would you go about designing a car parking station?
A6.

Map out the requirements:
  • The car park needs to cater for different types of car parks like regular, handicapped, and compact.
  • It should keep track of empty and filled spaces.
  • It should also cater for valet parking.
Map out the classes that would be required. Use a UML class diagram. Here are some points to get started.
  • A CarPark class to represent a parking station.
  • A ParkingSpace can be an abstract class or an interface to represent a parking space, and RegularParkingSpace, HandicappedParkingSpace, CompactParkingSpace, etc are subtypes of a ParkingSpace. This means a RegularParkingSpace is a ParkingSpace.
  • A CarPark has a (i.e. composition) finite number of ParkingSpaces. A CarPark also keeps track of all the parking spaces and a separate list of all the vacant parking spaces.
  • A Vehicle class uses a (i.e. delegation) ParkingSpace.  The Vehicle class will hold attributes using enum classes like  VehicleType and ParkingType. The vehicle types could be Compact, Regular, and Handicapped. The parking types could be Self or Valet. Depending on the requirements, the self or valet types could be designed as subtypes of the Vehicle class.


Q7: Can you design the classes that represent a restaurant?
A7: Very popular. Good understanding of OO design is vital to job interview success. Learn the SOLID design principles, know why you favor composition over inheritance, and don't under estimate the power of coding to interface.
  • Java OO Interview Questions and Answers. A step-by-step tutorial explaining how you would go about designing your classes. The "Core Java Career Essentials" PDF covers more examples on SOLID design principles with working code.

How would you go about identifying thread safety issues in an application? How would you go about identifying memory leaks issues? How would you go about identifying performance issues?, etc to judge your experience. I am yet to work on a project that didn't face problems relating to thread safety, memory leaks, and performance issues. Hence, it really pays to market your skills and experience in fixing issues relating to these common challenges.


Q8. How will you go about fixing memory leaks in Java?
A8. Again, a very common problem, and a thorough answer will go a long way in securing your next Java job.

Q9: How will you go about fixing performance issues in Java?
A9:
  • Detecting performance issues in Java. A basic tutorial covering -- how to detect performance issues.
  • Also, refer to the JMeter tutorials in this blog as to learn how you can put load on your application to simulate concurrent users.

Q10: How will you go about detecting and fixing thread-safety issues in Java?
A10: Debugging concurrency issues and fixing any thread starvation, dead lock, and contention requires skills and experience to identify and reproduce these hard to resolve issues. Here are some techniques to detect concurrency issues.
  • Manually reviewing the code for any obvious thread-safety issues. There are static analysis tools like Sonar, ThreadCheck, etc for catching concurrency bugs at compile-time by analyzing their byte code.
  • List all possible causes and add extensive log statements and write test cases to prove or disprove your theories.
  • Thread dumps are very useful for diagnosing synchronization problems such as deadlocks. The trick is to take 5 or 6 sets of thread dumps at an interval of 5 seconds between each to have a log file that has 25 to 30 seconds worth of runtime action. For thread dumps, use kill -3 in Unix and CTRL+BREAK in Windows. There are tools like Thread Dump Analyzer (TDA), Samurai, etc. to derive useful information from the thread dumps to find where the problem is. For example, Samurai colors idle threads in grey, blocked threads in red, and running threads in green. You must pay more attention to those red threads.
  • There are tools like JDB (i.e. Java DeBugger) where a “watch” can be set up on the suspected variable. When ever the application is modifying that variable, a thread dump will be printed.
  • There are dynamic analysis tools like jstack and JConsole, which is a JMX compliant GUI tool to get a thread dump on the fly. The JConsole GUI tool does have handy features like “detect deadlock” button to perform deadlock detection operations and ability to inspect the threads and objects in error states. Similar tools are available for other languages as well.

Q. What is the difference between mutex and semaphores? What problem do they solve?
A.

Example 1: A trading system creates a buy order and places it in a queue, and a separate consumer thread picks up the order and sends it to the stock exchange. A typical producer and consumer scenario.

Example 2: If you want to recursively traverse through nested folders and spawn a number of worker threads to move the html files found to a destination folder and increment the semaphore permits with a release( ) method call. A separate thread will wait with the acquire(numberOfPermits) to acquire all the released permits before start archiving (i.e. zipping up) those files.

Example 3: A counter that keeps track of the number of active logged in users by incrementing the count when users log in and decrementing the count when the users log out.

Mutex and semaphores are used to solve producer and consumer synchroniztion scenarios outline above.. 

Q. Can you write code to demonstrate deadlock in Java?
A. Creating a deadlock in Java

Q. Can you give some examples of thread racing conditions you had experienced?
A. Thread racing conditions and atomic operations. 




Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Labels: , ,

Jan 15, 2014

Java Developer Career Success Training

50+ Java Developer Job Interview Questions and Answers

with lots of diagrams, examples, code snippets, and cross references. Brush-up prior to your Java job interviews to stand out from your competition or as a quick reference to get a task done like writing a spring-batch job. Preparation will breed confidence and success. 







Note: Most examples are industrial strength and not just "Hello World", which has its purpose.These posts are used as my quick reference to get the job done.

Labels: , , , , , , ,

May 1, 2013

Top 20 Java technical interview questions and answers for experienced Java developers -- Part 3

Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Most applications built today are web based and it is vital that you have a good handle on the web paradigms.

Q11. HTTP is a stateless protocol, so how do you maintain state? How do you store user data between requests? Is it a good thing to maintain state?
A11 . This is a commonly asked interview question. The “http protocol” is a stateless request/response based protocol.  You can retain the state information between different page requests as follows:

HTTP Session. A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism.  Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable. In a Java servlet the session can be obtained as follows:

HttpSession session = request.getSession(true); //returns a current session or a new session

//To put/get a value in/from the session 
Name name = new Name(“Peter”);
session.setAttribute(“Firstname”, name); //session.putValue(…) is deprecated as of 2.2

session.getAttribute(“Firstname”);//get a value. session.getValue(…) is deprecated

//If a session is no longer required e.g. user has logged out, etc then it can be invalidated.
session.invalidate(); 






Hidden Fields on the pages can maintain state and they are not visible on the browser. The server treats both hidden and non-hidden fields the same way.

URL re-writing will append the state information as a query string to the URL. This should not be used to maintain private or sensitive information.

Http://MyServer:8080/MyServlet?Firstname=Peter&Lastname=Smith

Cookies: A cookie is a piece of text that a Web server can store on a user’s hard disk. Cookies allow a website to store information on a user’s machine and later retrieve it. These pieces of information are stored as name-value pairs. The cookie data moves in the following manner:

Q12. Are states bad? if yes, why?
A12. State isn’t bad, it’s a necessity. But favor stateless architecture for the number of reasons described below.
  • You should ALWAYS make your systems not only as simple as possible, but also as scalable as possible. In a clustered or load balanced environment with multiple servers, maintainig of states requires the user to always return to the same server using sticky sessions or else the whole system breaks down. The answer to this problem is using sticky sessions which force the load balancer to send traffic for a given user to the same server every time.  The LB is hardly balancing load if it can’t decide who gets the traffic.  There are other more complicated methods for sharing sessions across multiple servers via true clustering, but getting this right is more complicated and time consuming. 
  • State can also be problematic from a security point of view due to sharing the state between the client and server.  There are methods around this problem using encryption and other techniques, but again can complicate your solution.

The single page rich web pages making a number of RESTFul web services via ajax requests is a very popular architecture. Making server side RESTful web services stateless is a central tenant of REST. A truly stateless RESTful web service is not only incredibly flexible and scalable thing, but also takes responsibility for handling security and deciding who can access what in the system.  Since there is  very little "under the covers stuff" happening to try to make this stuff “easier”, you are free to implement security however makes sense for your system.


Q13: What is your understanding of the following terms ... forward, redirect (aka sendRedirect), and post-back?
A13:


Forward
  • a forward is performed internally by the servlet.
  • The browser is completely unaware that it has taken place, so its original URL remains intact.
  • You can set request attributes from the forwarding request (e.g. s servlet) to the resource to which it is forwarded (e.g. JSP). 
Redirect
  • A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
  • A browser reload of the second URL will not repeat the original request, but will rather fetch the second URL. This makes the second resource link book markable.
  • A redirect can be marginally slower than a forward as it requires two browser requests as opposed to one with the forward.
  • Any attributes placed in the original request scope are not available to the second request, since it is a new request.
Post-back
  • The HTTP verb POST is used to send data  to the server in the body, with XML, JSON, or form fields. 
  • The term "back" really means that you retrieved the page initially with a GET verb to show the user the <form> elements, and at the end you're sending data back. So, a PostBack is a POST request for a page that is not the first request.

Spring framework is very popular and can be used as an IoC container, MVC2 web application framework, JDBC and JMS template, and so on. So you need to be prepared with basic Spring job interview questions.



Q14:What are the different ways can you wire up your dependencies using Spring?
A14: 3 different ways. You can combine all 3 ways.
Q15. Can you describe the following bean concepts
  1.     Spring managed beans life cycles.
  2.     Bootsrapping the initial Spring bean.
  3.     What is a bean factory?
  4.     How would you create an application context from a web application?
A15. The answers are clearly explained in this Spring training tutorial on bean life cycle.

Q16. Can you list some real life scenarios where you will use Spring AOP?
A16. 
 
1. You can use the Method AOP interceptors for dead lock retry and logging. Occasionally, you get deadlocks in databases and you database management systems resolves deadlocks by aborting a transaction. These transactions can be retried with the help of Spring AOP method interceptors. This is clearly explained in Step 3 under How do you wire up transaction manager?

2. Another area is service retry service in general where any failed remote service calls can be retried at a certain interval say every 10 seconds for 3 times.

3. for auditing purposes.

4. Spring itself uses aspects for things like transaction management, security, and caching.

Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Labels: , ,

Jan 21, 2013

Top 20+ Java EE interview questions and answers that experienced Java developers must know

Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

If you are an interviewer -- it really pays to ask well rounded questions to judge the real experience of the candidate as opposed to just relying on the number of years.

If you are an interviewee -- You have no control over what questions will be asked in Java job interviews, but there are a few Java interview questions that are very frequently asked in job interviews, and it really pays to prepare for those questions. Here are a few such questions. This is based on some of my recent interviews. Brushing up on these answers will boost your success rate in Java job interviews.

The focus is on judging your experience and technical strength. So, go through your resume and reflect back on your hands-on experience. Many of these answers will also serve you well in selling your technical strengths to open ended questions like -- tell me about yourself? , why do you like software development?, when reviewing others' work, what do you look for?, what was your most significant accomplishment?, etc

Q1. Can you describe the high level architecture of the application that you had worked on recently? or Can you give a 100 feet bird's eye view of the application you were involved in as a developer or designer?

A1. The purpose is to judge your overall experience. Here are a few links that will prepare for this most sought-after question, especially for the experienced professionals.
  • 3 to n-tier enterprise Java architecture, the MVC-2 design pattern, the distinction between physical and logical tiers, and the layered architecture.The logical tiers shown in the diagrams for the above link are basically layers, and the layers are used for organizing your code. Typical layers include Presentation, Business and Data – the same as the traditional 3-tier model. But when  talk about layers, we’re only talking about logical organization of code. Physical tiers however, are only about where the code gets deployed and run as war, ear or jar. Specifically, tiers are places where layers are deployed and where layers run. In other words, tiers are the physical deployment of layers.
  • high level architectural patterns and the pros and cons of each approach. Discusses a number different architectual styles like MVC, SOA, UI Component, RESTful data composition, HTML data composition, Plug-in architecture, and Event Driven Architecture (EDA). Also, covers a sample enterprise architecture, which is a hybrid of a number of architectural styles.
  • Single page web design. A single rich web page loading different sections (e.g tabs) of the page by making different ajax calls to relevant RESTful web services to get the JSON data to render the relevant sections.
  • Understanding of various types of application integration styles. Enterprise applications need to be integrated with other systems, and this post covers different integration styles like sharing the same database, feed based, RPC style (e.g. web services), and exchanging JMS messages.


Q2. How would you go about deciding between SOAP based web service and RESTful web service?
A2. Web services are very popular and widely used to integrate disparate systems. It is imperative to understand the differences, pros, and cons between each approach. Recently, I have been asked these questions very frequently, here is the answer that discusses the pros and cons of SOAP vs. RESTful web services in detail.  

Q3.How will you go about ensuring that you build a more robust application? or How do you improve quality of your application?
A3. This question is very popular with the interviewers because they want to hire candidates who write good quality application. Here are some useful links to prepare for this question.
Q4. What are some of the best practices regarding SDLC? Have you worked in an agile development environment? Did you use test driven development and continuous integration?
A4. 


Q5: Can you write code? How would you go about implementing .....?
A5:  You will be asked to write a small function or a program. The interviewer will be looking for things like
  • How well you analyze the requirements and the solution? Ask relevant questions if the requirements are not clear. Think out loud so that the interviewer knows that how you are approaching the problem.The approach is more important that arriving at the correct solution.
  • List all possible alternatives.
  • Write pseudo code.
  • Write unit tests.
  • Where required, brainstorm with the interviewer.
  • Find ways to improve your initial solution. Talk through thread safety and best practices where applicable.
Here are some links to popular coding questions and answers.
  • Java coding interview questions and answers:. Covers a number of coding questions with answers. These are some of the popular coding interview questions like reversing a string, calculating the Fibonacci number, recursion vs iteration, equals versus ==, etc.
Coding Questions and Answers worth brushing up on, especially before the screening written tests.
Q. Can you write Java code to compute a collection of numbers supplied to it? The computation could be addition, subtraction, etc. Use recursion to compute the numbers. Here are some requirements to take into considerations.

1. It should be flexible enough to convert from Recursion to iteration if required.
2. Computation will initially be "addition", but should be extendable to multiplication, subtraction, etc.
3. Should handle integers and floating point numbers.
4. Make use of generics.

A. Java coding with recursion and generics

Q. The SimpleDateFormatter and DecimalFormatter are not thread-safe. How will you use them in a thread-safe manner?
A. Using the ThreadLocal class as demonstrated in this tutorial.


Q. If Java did not have its own Map or Set implementation, how will you go about implementing your own?
A. Covered in detail with diagrams and code in "Core Java Career Essentials" book.

Java Interview Questions and Answers

1-5 for experienced developers 6-10 for experienced developers 11-16 for experienced developers 17-20 for experienced developers

Labels: , ,