138

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.

Community
  • 1
  • 1
Rachel
  • 91,207
  • 112
  • 255
  • 361
  • 3
    Why this question is not able to get similar response to .Net question ? – Rachel Jan 22 '10 at 02:25
  • 5
    Good Lord :), the .Net question was asked a year ago and this one is just a day old and you are comparing the responses. – zapping Jan 22 '10 at 06:07
  • Just to bring some statistics to notice, .Net question was last answered on 13th December 2008 and so last answer for that question is also 1 yr old :) – Rachel Jan 22 '10 at 06:11
  • 1
    Why don't you edit your question and add the sentence "Please answer your own question.", so that people even could learn something (new). – oliver31 Jan 22 '10 at 09:53
  • 9
    "what is the current abbreviation for the Enterprise Edition" ;) – Bozho Jan 22 '10 at 13:22
  • 1
    This reads like a study guide for the SCJP exam. – Pops Jan 22 '10 at 14:35
  • 17
    Albert Einstein's Anecdote.. ONE OF Einstein's colleagues asked him for his telephone number one day. Einstein reached for a telephone directory and looked it up. "You don't remember your own number?" the man asked, startled. "No," Einstein answered. "Why should I memorize something I can so easily get from a book?" Am I reaching everyone ;) ? Yeah I know, Einstein was not facing an Interviewer... – SB. Jan 25 '10 at 06:43
  • I was gratified to be able to answer promptly. I said, "I don't know." (Mark Twain) – Svante Mar 19 '10 at 01:55
  • Came across this question from http://stackoverflow.com/questions/5265846/questions-every-good-ruby-rails-developer-should-be-able-to-answer , which I'm also voting to close. – Andrew Grimm Mar 10 '11 at 21:12
  • Ignoring the "what's your fav..." format, this would have been a hell of a lot more useful if the "answers" requirement had been in there from the get-go. – Shog9 Dec 05 '11 at 03:53

35 Answers35

83

What is the relationship between hashCode() and equals()? What is the significance of these methods? What are the requirements for implementing them?

Jeff
  • 21,436
  • 6
  • 49
  • 55
  • Yes, every dev should at least be aware of the problems, even if you will not necessarily encounter them in practice. – sleske Feb 01 '10 at 09:09
  • 3
    equals() and hashCode() in java @ http://www.technofundo.com/tech/java/equalhash.html – pramodc84 Sep 14 '10 at 12:10
70

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.

Jon
  • 55,763
  • 30
  • 120
  • 149
  • 8
    Granted, but it's a matter of 20 secs looking at the docs on the net ("java collections framework"), so many worthwhile people may not bother with keeping it in memory. – Manur Jan 22 '10 at 14:13
  • 127
    Nope sorry don't buy that, it's basic knowledge that every developer should know. – Jon Jan 22 '10 at 17:02
  • 15
    I'd go as far to say anybody even thinking about a job in software needs to understand not only that, but also differences between different kinds of lists (ArrayList/LinkedList). Not necessarily best implementation or even O(n) notation, but an understanding of when it's right to use what. – Reverend Gonzo Jan 22 '10 at 19:27
  • 11
    +1 @Jon: I usually subscribe to the "no need to memorize details" school of thought, but if you don't even know the basic conceptual differences between those basic interfaces, then you're definitely not a good Java developer. – Joachim Sauer Jan 25 '10 at 13:01
  • 13
    @Joachim: you could drop the word "Java" from your statement. Sets, Maps, and Lists are basic algorithmic notions. – CPerkins Jan 25 '10 at 20:46
  • 2
    So many devs just use lists. I've had the misfortune of meeting someone who wrote methods to implement set semantics around a list. +1 as a simple but useful question to find out if someone has half a clue. – Spence Feb 01 '10 at 08:23
  • How does that qualify a Java EE developer? – BalusC Feb 01 '10 at 18:42
  • I agree. If you don't know this simple thing I would not hire you. – Shervin Asgari Oct 14 '10 at 18:20
  • 1
    @BalusC What do JavaEE developers not use collections or something? :) – Jon Oct 14 '10 at 20:54
44

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

John Topley
  • 107,187
  • 45
  • 188
  • 235
ewernli
  • 36,434
  • 4
  • 82
  • 119
  • I confused a C++ lecturer yesterday with the diamond inheritance problem, she didn't know about it at all :) – Esko Jan 22 '10 at 10:01
  • 2
    I was once asked this question and i answered "no". I think it was stress plus i answered too fast. its always hard to know answers to things you never use. – IAdapter Jan 22 '10 at 14:53
  • 1
    I elaborate a bit more in the text. Answering "no" is actually ok. What is nice with this question is that it's good way to trigger a discussion about OO concepts ans see how the candidate reasons. If the interviewer you had just wanted to hear "yes" then it's effectively pointless. Multiple inheritance of interfaces is indeed not that common to be known by heart. – ewernli Jan 22 '10 at 15:50
  • 3
    A trickier version of this question is "Does java support multiple inheritance?" to which the answer is "sort of" only for interfaces – nsfyn55 Sep 14 '11 at 17:55
23

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");
}

sateesh
  • 25,445
  • 7
  • 35
  • 44
  • I would really love to know answer for this question. It sounds very interesting. – Rachel Jan 22 '10 at 03:55
  • @Rachel: The reason is because the `final` keyword applied to the `Name` object, not the `name` field of class `Name` – ryanprayogo Jan 22 '10 at 04:38
  • 20
    Well, the parameter `n` is declared as final, which means it can't be reassigned in the `test` method body. It doesn't cause an error because the method `test` doesn't attempt to reassign the parameter, it merely sets a property on the parameter... `n = new Name("test");` would cause a compile error... – rjohnston Jan 22 '10 at 04:44
  • 7
    Adding to the @rjohnston's comments: the usage of final for method parameter doesn't ensure immutability of a class instance. If there is a need for immutability the class (Name in the present case) should be designed so (for example in present case don't provide the setter) – sateesh Jan 22 '10 at 05:04
  • Thank you all for sharing valuable information. I really appreciate your inputs on this. – Rachel Jan 22 '10 at 05:13
  • I'm confused. The above DOES give a compile error. Where is the public class that the test method is part of? Also, the final keyword would appear to have no effect - I don't see what this example shows...? – Alex Spurling Feb 01 '10 at 09:09
  • Sorry I notice that the ctr of Name class was private,changed it to be public.The example is not complete (they are code snippets).To get rid of compile error:a.Create a public class by name "Name" b.Create another public class (Test) that has method "test" c.In Test have a main method creating Name (Name n = new Name("hello");). Create Test instance in main and call test new Test().test(n). final keyword doesn't ensure that instance being passed isn't modified, it ensures that the ref is pointing to the same instance. Adding line: n = new Name("Kind") in the "test" gives compile error. – sateesh Feb 01 '10 at 10:13
19

One sure is comparison of string. Difference between

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

zapping
  • 3,963
  • 6
  • 38
  • 54
  • 14
    Pretty sure you'd need to do something like new String("Hello World"). Aren't string constants pulled from a pool, much like the effect intern() would have, therefore making both statements true? – Steven Schlansker Jan 30 '10 at 21:37
  • 1
    http://javatechniques.com/blog/string-equality-and-interning/ – zapping Feb 01 '10 at 08:37
17

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.

Chinmay Kanchi
  • 54,755
  • 21
  • 79
  • 110
  • I agree totally with you. I had struggled a lot with this discussion. – Rachel Jan 22 '10 at 01:14
  • I wanted to post "Is Java pass by value or pass by reference?" but was afraid it'd cause an internet argument – matt b Jan 22 '10 at 01:52
  • I think most people on SO have the right of it. It's not really a never-ending argument, because there is only one right answer, even the Java spec says so, IIRC. :) – Chinmay Kanchi Jan 22 '10 at 02:12
  • I wish I could upvote this more than once - I actually encountered this subtlety while developing, understanding what really goes on is a real eye-opener – laura Jan 22 '10 at 09:42
  • 4
    I wonder if the correct answer is always the one to give in an interview. In a place I interviewed for, the interviewer also parroted the same thing. – MAK Jan 22 '10 at 19:40
  • all are by value including the reference. – mP. Jan 24 '10 at 04:18
  • 2
    I've noticed a difference between folks who studied C as a first language and folks who studied C++ as a first language in answering this question about Java. Probably because the C users are taught that passing a pointer to a value is a "pass by reference". – Uri Jan 25 '10 at 18:03
  • I actually learnt C first, and it did take me a long time to wrap my head around the fact that passing a pointer is not the same as passing a reference, but that doesn't excuse ignorance, only somewhat mitigates it :). – Chinmay Kanchi Jan 25 '10 at 18:16
  • 23
    That's a stupid question as the "wrong" answer will most likely become technically right if you also ask *"what consequences has passing by reference?"*. It's just a matter of definition of what *pass by reference* means and is thus of not much value in the Java world as there is only one way to pass objects. It's more important to understand what really happens than to use a aribitrary definition for *pass by reference* the way you want. – x4u Jan 26 '10 at 02:09
  • 3
    This question is at least problematic, because it mostly hinges on the exact definition of "pass by value" / "pass by reference", which is often used incorrectly. While I agree that a good developer should know the definitions, it's more important to understand the consequences. If you understand Java's actual behaviour, then knowing the correct name for the concept is not very meaningful, because it's not something you discuss in practice, as it never changes. – sleske Feb 01 '10 at 10:58
  • Agreed. However, I've seen that a lot of Java developers who dabbled with C++ in college think that "pass by reference" means the same thing in both languages. – Chinmay Kanchi Feb 01 '10 at 12:19
  • 3
    Erm, objects *are* passed by reference in Java. You cannot pass an object by value; among other things, objects never exist on the stack. *References* are passed by value, sure. – Sean Owen May 06 '10 at 22:33
  • @MAK, yeah but that is a sign that you don't want to work there... – Zombies Jul 08 '10 at 15:55
  • 1
    Java has no concept of "pass by reference". Everything is passed by value. References are just another primitive type allocated on the stack like everything else - they just happen to be a key that resolves to something on the heap. – nsfyn55 Sep 14 '11 at 17:59
17

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 :)

Joachim Sauer
  • 278,207
  • 54
  • 523
  • 586
Elister
  • 1,536
  • 2
  • 10
  • 14
  • 8
    Answers would be nice, I don't know the answer to some of them. – MAK Jan 22 '10 at 19:46
  • Checked exceptions are those that a program has to have a plan to handle should they occur. If there is no try/catch block around something that throws a checked exception the program will not compile. wait, notify and notifyAll are for synchronising threads, and in Java all Objects can be synchronised on. I would extend Thread (as opposed to implementing Runnable) if conceptually the class requires its own thread, i.e. it needs to do some management, and does not represent a task that could be run on another worker thread. – ZoFreX Jan 24 '10 at 22:39
  • If an exception is thrown in a finally block then the rest of it will not run. In a "pure" Java program, canonical memory leaks do not exist. However, memory could still get used that shouldn't if data structures contain references to objects that are no longer needed. If using native libraries then their resources may need to be managed, for example in SWT it is important to call .dispose() on certain assets to make sure they do not leak. – ZoFreX Jan 24 '10 at 22:41
  • 2
    Use assertions for "This should never happen ever" errors which are to be dealt with in development. Use exceptions for errors that might actually happen at runtime, and the program will need to deal with them in some way. – MatrixFrog Jul 14 '11 at 05:58
16

What is difference between String, StringBuffer and StringBuilder?

Thunderhashy
  • 5,191
  • 13
  • 39
  • 46
  • 5
    String - immutable class representing a String. StringBuffer - builder pattern introduced in older versions of Java that synchronizes on every operation (or the majority of them) to use to build a String. StringBuilder - introduced in Java 5 (JDK 1.5), a class which shares the StringBuffer API to use to build a String that does *not* synchronize on every operation (or the majority of them). Because the construction of Strings tends to happen in a single thread, StringBuilder is preferred for this purpose in Java runtimes/JDKs that support it. – MetroidFan2002 Mar 17 '11 at 03:20
13

"What's a deployment descriptor?"

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

Michael Borgwardt
  • 327,225
  • 74
  • 458
  • 699
  • make it "shudders involuntarily + perspires heavily + drops dead after repeating this question 2 more times", I sometimes feel its the "one & only" reason they added/supported the whole Annotations thing! :) – Elister Jan 22 '10 at 19:35
12

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.

Community
  • 1
  • 1
Pascal Thivent
  • 535,937
  • 127
  • 1,027
  • 1,106
  • I dont like question "what don't you like about Java?", i would lie, because it sounds just like "why you left your last company?". plus they might think - "if you hate java we wont offer you the job". – IAdapter Jan 22 '10 at 14:57
  • @01 It's your right but I don't agree with you and I think that you missed the point of that question. – Pascal Thivent Jan 23 '10 at 06:51
  • 1
    I've usually seen this put more like: "What would you most like to see changed in Java", rather than "don't like". – CPerkins Jan 25 '10 at 20:54
  • @CPerkins That's a better wording indeed, better than "don't like" and much better than "hate" (in the reference). Thanks. – Pascal Thivent Jan 26 '10 at 01:35
11

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

Adisesha
  • 5,002
  • 1
  • 31
  • 41
10
  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.
Mark
  • 27,389
  • 7
  • 55
  • 88
  • 3
    If there was just _one_ thing I could change, I'd add operator overloading to the language, probably with just a restricted set of overloadable operators (i.e., no overloading `new` or `^` or `>>`, `<>>`). If I could change another thing, that would be to add _true_ call-by-reference semantics. A third thing would be to add `unsigned` integral types. – Chinmay Kanchi Jan 22 '10 at 12:29
  • 1
    delegates and closures and maybe a lambda expression, but that's not really necessary. Extension Methods would be grand as well. They really can clean code up if used properly. – Joel Mar 19 '10 at 02:29
10
  • 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?
John Topley
  • 107,187
  • 45
  • 188
  • 235
JuanZe
  • 7,603
  • 41
  • 57
9

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.

David
  • 1,840
  • 3
  • 17
  • 30
  • 16
    Is "throw new NullPointerException()" a correct answer? – Thorbjørn Ravn Andersen Feb 21 '10 at 20:16
  • 1
    Well, it's up to the interviewer. If they showed an example of testing a variable and throwing a NPE with a helpful message then I'd be happy. If I thought they used that answer because they couldn't come up with some code that would legitimately throw an NPE then I'd be worried. – David Feb 21 '10 at 23:22
9

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

zaletniy
  • 549
  • 4
  • 12
  • the first code indicates that finally is always excuted even if return statement was available in try block , but i didn't got the second code?? what has happened when statement builder = null ; happen ?? – palAlaa Nov 27 '10 at 19:46
  • 3
    @Alaa, it's almost like a temporary value is set to the builder, the builder is set to null in the finally block, and then the temporary value is what is returned. – deterb Mar 21 '11 at 11:23
  • 1
    @VextoR, yes Alaa has given nice description. That code checks how interviewee understands the try... finally block with return inside, and variables scope in general, variables handling – zaletniy Mar 29 '11 at 11:32
  • 4
    The return statement is returning the reference to the StringBuilder object. Changing the reference in the finally does nothing to the reference that is actually returned. However, changing the __contents__ of the object does affect what's returned, as in the first example. – Derek Litz Apr 13 '12 at 15:31
8

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.

tshepang
  • 10,772
  • 21
  • 84
  • 127
Ravisha
  • 2,983
  • 8
  • 36
  • 61
  • Don't know about the JDK/JRE part. For instance, there is no such distinction on the Mac. So as a Java developer on the Mac, there really is no need at all to know about that. – Fabian Steeg Jan 22 '10 at 19:28
  • I think this is a fine question, and if it helps expose people who are misguided enough to attempt serious Java development on a Mac all the better. Seriously, if you claim to be a Java developer but wouldn't know which download link to click on java.sun.com then there's a problem. – Mark B Jan 22 '10 at 19:38
  • Well being a java developer one need not worry at all about the platform he/she s woring on.understanding the java tools seems basic requirement.Atleast i consider so.i am not aware about Mac OS.still i do not m=worry much about OS in which i work. – Ravisha Jan 25 '10 at 05:28
  • @mbaird That comes off as a rather mean comment. Though I develop on a Mac and I do know what the JRE/JDK are, let's be honest, in a actual development, does it really matter? Especially with IDEs that make command-line use a thing of the past, a Java dev needs to know how to use the language more than anything else. – Alexis King Aug 06 '11 at 17:58
8

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.

ZoFreX
  • 8,536
  • 4
  • 28
  • 50
  • The only difference is abstract class can contains non-abstract methods. – TBH Apr 04 '10 at 22:19
  • 1
    That's the answer you'd have if you'd read a Java book, sure. Although then you might also add that they can contain member variables, too :P But the difference in when to use them, and why, is even more interesting. – ZoFreX Apr 05 '10 at 11:33
  • 1
    using of interface provides me with very powerful techniqe which is polymophism, which can call any overridden method from classes that implements the interface in a seemless way,that u don't need to know the type of each child classes. – palAlaa Nov 27 '10 at 19:51
  • @TBH - Do not forget that, in the single inheritance model Java currently uses, you can only extend one abstract class, for one set of functionality - but you can combine multiple interfaces in a single class for multiple functionalities to be implemented without the single inheritance restriction. – MetroidFan2002 Mar 17 '11 at 03:19
6

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.
CMR
  • 946
  • 6
  • 15
5

Difference between and web server and a web container

5

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

Carsten
  • 3,914
  • 4
  • 28
  • 47
5

why would you override the toString() method?

SWD
  • 289
  • 1
  • 5
  • 13
4

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 ?

David Nouls
  • 1,865
  • 12
  • 20
4

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().

Sai Upadhyayula
  • 2,074
  • 3
  • 20
  • 31
  • You can use `public static void main(String... args)` if you're so inclined :-) It has the same signature as `[]` – corsiKa Dec 01 '11 at 00:38
3

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

oxbow_lakes
  • 129,207
  • 53
  • 306
  • 443
  • 4
    Is the ability to keep marketing terminology straight really that important at the end of the day? – Laurence Gonsalves Jan 26 '10 at 02:03
  • @Laurence - that's a ridiculous thing to say. There is a real difference between the two things which you'd be amazed how many supposedly experienced developers just don't understand – oxbow_lakes Jan 26 '10 at 07:41
  • My point is that if someone is a good coder, I couldn't care less if they know the difference between J2SE and J2EE. – Laurence Gonsalves Jan 26 '10 at 22:58
  • I read the question as being "stuff that a JEE+JSE developer should know", in which case I think that understanding the difference between the two technologies is relevant. – oxbow_lakes Jan 27 '10 at 09:37
  • @Laurence, I would have a very hard time imagining a _good_ JEE coder which did not know the difference between EE and SE. – Thorbjørn Ravn Andersen Feb 21 '10 at 20:21
  • 4
    @Thorbjørn Ravn Andersen I doubt that most Java coders, good ones included, are strongly aware of the distinction above, "the enterprise edition is basically an interface definition ... Whereas the standard edition is an implementation in its own right". To most good Java coders the distinction that matters is which APIs are available. eg: Servlets are part of EE, etc. In any case, just as I think it's more important to find good programmers than good language-X programmers, I think it's more important to find good Java programmers than good JSE/JEE programmers. – Laurence Gonsalves Feb 21 '10 at 23:12
  • @Laurence. If the person in question is to have anything to do with a JEE system, I would strongly expect them to know this (not as much if they are not). Perhaps we just have different expectations of what a "good" programmer is. – Thorbjørn Ravn Andersen Feb 22 '10 at 02:34
3

How does volatile affect code optimization by compiler?

Roman
  • 59,060
  • 84
  • 230
  • 322
  • 3
    That entry should contain the correct answer too. – Thorbjørn Ravn Andersen Feb 21 '10 at 20:18
  • I don't remember full answer, look this lection http://www.youtube.com/watch#playnext=1&playnext_from=TL&videos=7pYeEVk1A40&v=1FX4zco0ziY for good explaination. In nutshell: assume that method use volatile variable at some point. Then compiler doesn't optimize code of this method after that point. – Roman Feb 21 '10 at 21:39
2

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

Kristian
  • 6,033
  • 6
  • 25
  • 29
2

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

Everyone
  • 2,288
  • 2
  • 26
  • 38
2

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() ?

YoK
  • 13,731
  • 4
  • 46
  • 66
  • can u please answer these questions ?it's the first time for me knowing about "checked and unchecked exceptions " !! – palAlaa Nov 27 '10 at 19:36
  • Simple google search can lead you to answers : http://www.google.co.in/search?aq=1&oq=checked&sourceid=chrome&client=ubuntu&channel=cs&ie=UTF-8&q=checked+and+unchecked+exception+java – YoK Dec 03 '10 at 04:16
1

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.

fastcodejava
  • 35,219
  • 24
  • 124
  • 181
  • 2
    That is because the answer ´is´ yes... – Fortega Feb 04 '10 at 16:09
  • @Fortega - How can that be? Each method has a lock on the object. If one `thread` is running the method, no other `thread` can obtain the lock. – fastcodejava Feb 24 '10 at 06:46
  • 1
    If you have two objects of the same type, you can call the first method on the first object, and the second method on the second object simultaneously. Unless the methods are static of course. – Fortega Feb 24 '10 at 13:12
  • @Fortega - That's a no brainer. You can call the same method simultaneously if it is on a different instance. – fastcodejava Feb 24 '10 at 22:25
  • 2
    If you don't understand properly how the locking takes place, that's not really a no brainer. Also, although it might be a no brainer, that does not mean my answer was incorrect :-) – Fortega Feb 25 '10 at 09:22
  • 1
    The answer could make confusion for progrmmers who didn't use threads in their work, but i think it's a good one:) – palAlaa Nov 27 '10 at 19:52
1

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";
}
Shervin Asgari
  • 22,044
  • 28
  • 92
  • 138
  • And Number's such as Integer, Long and so on – Arthur Ronald Oct 17 '10 at 02:06
  • Performance wise, there's no longer a difference between concatenating immutable strings and using StringBuilder. This is because modern java compilers will optimize the concatenation: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1.2 It's best to use whatever method is more readable. – Brent Wilson Jun 15 '11 at 15:12
  • 1
    @BrentWilson what you link will not do what you think. It will turn `s += "a" + "b" + "c"` into a `Stringbuilder.append(...)` scenario. But it will **not** optimize out a `for` loop. The code in this answer will end up creating a total 201 Strings, 100 StringBuilders, and (depending on implementation) 300 different `char[]`s inside those StringBuilders, and an estimated 425k+ characters. Changing it to use a StringBuilder outright will reduce this to 1 String, 1 StringBuilder, and 13-15 internal `char[]`s using only ~8k characters instead like it should. – corsiKa Dec 01 '11 at 00:44
0

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

mP.
  • 17,011
  • 10
  • 66
  • 101
  • 1
    Do you mean the four types of _nested_ class (http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html)? There are static nested classes, inner classes, anonymous classes and local classes, with only the last three being inner classes with a parent instance. – Andrew Duffy Jan 22 '10 at 13:47
  • 2
    @01 - Why should one not use inner classes? They are ubiquitous as event handlers in Swing programs, and functional collections libraries like Google Collections depend on them. – Andrew Duffy Jan 23 '10 at 16:33
  • What i meant by inner are the types one declares inline inside a method. If you really want you can extend to include other local types. – mP. Jan 24 '10 at 04:16
  • The better question is why would you use Swing – Woot4Moo Oct 14 '10 at 18:31
  • Local classes are actually quite useful sometimes, especially for Rapid Application Development or Rapid Prototyping. You need something quick and dirty, it gets the job done. Once you're past the prototyping stage, you can refactor things into the proper classes, and replace local classes. I wouldn't put them into production code because of the lack of maintainability, but they're really handy for a lot of things. – corsiKa Dec 01 '11 at 00:46
0

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.

Dan
  • 1,693
  • 3
  • 24
  • 39
  • could you go into detail about why a thread-safe class should not be trusted for multi-threaded applications? – corsiKa Dec 01 '11 at 00:47
0

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.

David Nouls
  • 1,865
  • 12
  • 20
0

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

akjain
  • 1,677
  • 3
  • 20
  • 35
  • Can you give me an example please? – gmhk Mar 08 '10 at 17:44
  • I don't have an exact answer for this, but basically if you have to write a servlet which can handle non-HHTP requests from a client then, is it possible to do it with a GenericServlet implementation ? – akjain Mar 11 '10 at 09:48
0

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

Sanjay Jain
  • 3,308
  • 7
  • 52
  • 88