[java] Questions every good Java/Java EE Developer should be able to answer?

I was going through Questions every good .Net developer should be able to answer and was highly impressed with the content and approach of this question, and so in the same spirit, I am asking this question for Java/Java EE Developer.

What questions do you think should a good Java/Java EE programmer be able to answer?

I am marking this question as community wiki as it is not user specific and it aims to serve programming community at large.

Looking forward for some amazing responses.

EDIT: Please answer questions too, as suggested in the comments, so that people could learn something new regarding the language, too.

This question is related to java jakarta-ee

The answer is


Write a program to accept two integers and output the largest of two numbers to a file at a location of your choice. Now describe what each statement does.

It's possible to drill down pretty deep starting from the significance of the import statement, right down to abnormal termination


Many questions and interviews are available at http://www.techinterviews.com/interview-questions/java and I don't really see value in copy / pasting a selection of them.

No, it's up to you to create your own compilation of things you think are important. Personally, I proceed always in two steps: first a few questions to get a basic idea of the experience and skills, then a problem solving situation. I'm indeed not convinced that being able to answer any known questions makes you a good or bad unknown problems solver. So, I prefer to ask people to solve a given problem, to give them some requirements, and ask them to write code (but not on paper). I give them some time to come back to me and check how they did it, their coding style, how they used the suggested APIs, etc.

That all being said, my favorite question is "what don't you like about Java?" (in the spirit of this one). It is really a excellent question, it gives you an immediate feedback on how much a candidate has used Java and explored its API and if he just religious about it or not (as the OP wrote).

Update: As suggested by CPerkins, a better wording for the question suggested above might be "What would you most like to see changed in Java?". And indeed, I prefer this way.


Top 5 J2EE/JEE questions

The list of J2EE/JEE middleware questions I have faced is exceptionally long, but here are the top 5 that I have been asked, and have lead to good discussions:

  1. What happens when an MDB encounters an exception that it cannot handle?
    This question usually leads to various interesting discussions about poison messages, error queues, etc.,
  2. Given a JMS Topic, and a few consumers on different JVMs, questions on various scenarios with and without durable consumers.
    This question usually allows me to discuss in terms of when to use durable subscribers, when to use queues, etc.,
  3. If stuck in a situation where accessing a Hibernate/JPA POJO contents leads to exceptions, how would one resolve it?
    This leads to wonderful discussions about lazy loading, rehydrating, etc., It has even lead to comparing and contrasting JPA with Entity beans. I have found it useful to be prepared, and to be clear in concepts.
  4. How could a simple web service be provided?
    Any solution from simple web server based to sophisticated SOAP/REST solutions, and any in between, should be good enough. Also, based on the interviewer, sometimes it leads to very interesting discussions on topics such as some design ideas - WSDL first, doc-style, SOAP intermediaries, etc., It might lead to questions such as listing improvements in JAX-WS over JAX-RPC, or SOAP1.2 over SOAP1.1, answers to which are usually based on how much I remember.
  5. JEE 5 resource injection
    This question is posed in many ways, starting from Service Locator pattern to javax.naming.Context questions.

Another tricky question I find troubling, but have faced many times is, How are dependent libraries packaged into an archive?
or Visibility of various classes in a bundled archive.
If the discussion does not lead to class loader hierarchy of different application servers, resource archives, etc., it is best to resign and move on.

Top 5 core Java questions:

  1. Questions on java.util.collections
    This is the mother of all questions. Once you can effectively land the interviewer in this area, and if you are prepared, the rest of the interview usually stays here. Be sure of knowing Set, List, Map, and the importance of Object.equals() and Object.hashCode() in every implementation of these interfaces.
  2. Refactoring questions
    These are good if the interviewer has an open mind. If the interviewer already has a specific solution in mind, and yours does not match his/hers, you are pretty much doomed. It is best to agree with the answer "I understand other solutions are possible. "
  3. Questions on multi-threading in JDK5, comparing with earlier JDK versions I have found it is best to be prepared with java.util.concurrent package classes. Doug Lea's book has most of the answers.
  4. What's new in JDK1.6/JDK1.7...?
    This is a sure shot question with many interviewers. As much as I hate this, it is best to be prepared. At least remembering a few that I have worked with, and leading the discussion in some other direction, largely and effectively dodges and solves the problem.
  5. Patterns in Java API
    Time and again I have been asked to point out a GoF pattern in the Java API. Better be prepared for this one.

Simple questions such as,

  • What is JRE and JDK?
  • Why does java claim interoperability?

Though these are very basic, many developers do not know the answers. I suggest these be asked before the code-related queries.


Q. Give a real world example scenario where you will use GenericServlet not HttpServlet ?


This is the question I faced in my interview.

Why is main method in Java called as public static void main(String[] args) ?

Answer:

1.main() must be declared public because it is invoked by JVM whenever the program execution starts.JVM doesnot belong to our program package.

Inorder to access main outside the package we have to declare it as public.If we declare it as anything other than public it shows a Runtime Error but not Compilation time error

2.main() must be declared as static because if a method is declared as static then we can call that method outside the class using ClassName.methodName();

class Sample
{
     static void fun()
     {
           System.out.println("Hello");       
     }
}

class Test
{
      public static void main(String[] args)
      {
                Sample.fun();
      }
}

The JVM will first Load the Test class,and will check for the Commandline arguments and calls the main method as Test.main();

3.main() must be declared as void main() because JVM is not expecting any value from main().So,it must be declared as void.

If other return type is provided,the it is a RunTimeError i.e;NoSuchMethodFoundError.

4.main() must have String arguements as arrays because JVM calls main method by passing command line arguement.As they are stored in string array object it is passed as an argument to main().


What do you like most / least about Java and why?


When would you use Session Beans or Message Driven Beans ?

How are transactions handled in session beans ?

What is the difference between local and remote session beans ? This question is more about knowing that RPCs are in the picture or not, since a method that is exposed as both Local or Remote might still work differently (side-effects on parameters are possible with Locals, while not possible with Remotes).

A good test is: never ask the questions in the same order. We had the experience with offshoring that sometimes they were actually giving the response in the wrong order :-). As a result you should make sure that you can actually see the person you are interrogating.


Core: 1. What are checked and unchecked exceptions ? 2. While adding new exception in code what type (Checked/Unchecked) to use when ?

Servlet: 1. What is the difference between response.sendRedirect() and request.forward() ?


  1. Explain the various access modifiers used in Java. I have had lots of people struggle with this, especially default access.
  2. If you could change one thing about the Java language or platform what would it be? Good developers will have an answer here while those who aren't really interested in development probably don't care.
  3. If their CV says something like they use EJB2.1 then ask about EJB3 to see what they know about it. The best developers will keep up with the latest developments even if they don't use the newer versions.

How about what is a session bean and describe some differences between stateless and stateful session beans.


How do threads work? What is synchronized? If there are two synchronized methods in a class can they be simultaneously executed by two threads. You will be surprised to hear many people answer yes. Then all thread related question, e.g. deadlock, starvation etc.


One thing many Java programmers don't know is that Strings are immutable, so use StringBuilder or StringBuffer!

String s = "";
for(int i = 0; i < 100; i++) {
  s += "Strings " + "are " + "immutable, " + " so use StringBuilder/StringBuffer to reduce memory footprint";
}

  • What is the general contract when overriding equals?
  • Is better option prefer lists or arrays?
  • What are the generally accepted naming conventions?
  • How serialization works?
  • How to implement Comparable?
  • What are the advantages of using JDBC's Prepared Statements?
  • What is Java EE?
  • What is a container and what services does it provide?

You said "Good","Developer". Here are my 2 cents too.. :)

  • What does a "checked exception" mean?
  • Which one is better to use and when: Assertions or Exceptions to handle unexpected conditions?
  • Why String class is final? (or is it not? ;) )
  • are the wait, notify and notifyAll methods in Object class?
  • Why isn't Thread class final? Why would I extend Thread, ever?
  • Why there are two Date classes; one in java.util package and another in java.sql?
  • What happens if an exception is thrown in finally block? Is the remaining finally executed or not?
  • There is a garbage collector alright, but then is memory leak totally absent in a Java applications? If not, how so?

For J2EE:

  • Is it good to have instance/static variables in a servlet? Why not? Then where do you store "state"?
  • continuing on above question: what & where is a "state" for a (web) application?
  • What happens if I started creating/closing DB connections in "JSP"?
  • What are the ways to handle JSP exceptions? try-catch? Hmmm.. is there anything else?

I can think many, many, many more of 'em but this'll do for now :)


What is the difference between J2SE and J2EE (or JSE and JEE)?

A developer should be able to point out that the enterprise edition is basically an interface definition (i.e. a specification) which can be implemented by vendors. Whereas the standard edition is an implementation in its own right


What is 'System', 'out', 'println' in System.out.println ? What happens when you call 'put' on HashMap ?


"What's a deployment descriptor?"

If the candidate shudders involountarily, he has experience working with pre-3.0 EJBs.


What is the difference between an abstract class and an interface? When would you use each of them?

Lots of Java developers don't know this, I asked most people on my computer science course at university and the vast majority could not answer it.


What will be printed?

public void testFinally(){
    System.out.println(setOne().toString());

}

protected StringBuilder setOne(){
    StringBuilder builder=new StringBuilder();
    try{
        builder.append("Cool");
        return builder.append("Return");
    }finally{
        builder.append("+1");
    }
}

Answer: CoolReturn+1

A bit more difficult:

public void testFinally(){
    System.out.println(setOne().toString());

}

protected StringBuilder setOne(){
    StringBuilder builder=new StringBuilder();
    try{
        builder.append("Cool");
        return builder.append("Return");
    }finally{
        builder=null;  /* ;) */
    }
}

Answer: CoolReturn


One sure is comparison of string. Difference between

String helloWorld = "Hello World";
helloWorld == "Hello World";
"Hello World".equals(helloWorld);


Great questions and great answers by all.It is nice to see such type of questions. I would like to add some more which can make this answer repository more rich.

For Core Java Is main is keyword in java ? More info

Java is plat form independent what about JVM?

Can we have private constructor in class, If yes what the usage of it.

Why we need to have constructors in abstract class though we cant instantiate it? More Info

Instead of above all there are many more question related to core java. More Info


A more pure Java question:

What is the difference between sleep and wait ? Not many people actually understand how wait is working.

How do you need to handle InterruptedExceptions ?


Trick question: What kinds of parameters are passed by reference in Java?

It's amazing how many people still parrot the "primitives are passed by value, objects are passed by reference" mantra.


Usage of final keyword in method calls. For example why does the method test in below code does not give any compile error despite using final qualifier for the method parameter.

class Name {
    private String name;

    public Name (String s) {
        this.name = s;
    }

    public void setName(String s) {
        this.name = s;
    }
}

private void test (final Name n) {
    n.setName("test");
}


If you are hiring graduates with Java "experience" a simple question like Write some code that will cause a NullPointerException to be thrown can distinguish which candidates have used Java recently, and didn't just stop when they finished their unit/course.


Difference between and web server and a web container


Advantages and disadvantages of thread-safe classes and explicitly synchronized code and examples of good applications of both. It is often not correct to trust on thread-safe classes as guarantees for data consistency in multi-threaded applications.


What is difference between String, StringBuffer and StringBuilder?


Describe the differences between the "four" (not three ;)) types of inner class..


why would you override the toString() method?


Can an interface extend multiple interfaces?

Most people answer "no", because they know java doesn't have multiple inheritance. But an interface can still extend multiple interfaces (but a class can't extend multiple classes). This doesn't lead to the diamond problem.

If the answer is "no", the interviewer should ask "why would it be forbidden?". Then you start thinking about it and you should realize that there is not problem with it.

So you learned something (by yourself) in the interview and you showed the interviewer that you are able to reason about classes, objects, inheritance, polymorphism, etc. It's actually much better than a candidate who knows the answer by heart but doesn't understand why


How does volatile affect code optimization by compiler?


What is the difference between Set, Map and List?

I'm still amazed how many people don't know this one in a telephone interview.