Interview Questions for Java Engineers

Status
Not open for further replies.

green_buddy

Wise, Aged Ars Veteran
126
The purpose of this thread is to create a list of possible interview questions in order to get peoples minds oriented around the possible questions that could be asked them during an interview for a position using Java.

I make no discrepency regarding whether the position is server side or client side, requires JNI work, or web-development... the topic is broad, and likely boundless, so if you can think of a (or some) questions, please add them... either ones that you would ask, or ones that you have been asked yourself. Another thing I ask is that if you supply a question, please also supply the answer, or the one that you would like to hear if asking the same question.

Let's start it off simply...

Question: Can static methods access instance variables?

Answer: No... this causes a compile-time error...
non-static variable yourVariable cannot be referenced from a static context

-green
 

green_buddy

Wise, Aged Ars Veteran
126
Earl,

I so totally agree with you!!! :mad: But that said, it does happen, and in fact, because it does happen, that's why I decided that it might be a good idea to put something up there in order to try and solve this problem.

Originally posted by earl:

That's crap; I would walk out the door if someone gave me a language quiz.

And what's worse is, these types of questions usually occur in a phone-screen of the candidate before they actually get in the door. ;)

Basically, the reason that I'm trying to do this is so I can get a good idea of questions that are going to be asked of me... I hate these types of quizzes. I make no false representation of myself by saying that I suck at them, because I think there's a lot more to being a software engineer than language symatics and simple how too's. I typically don't concern myself with these issues since they will come out during the design process anyway, but that still doesn't solve my immediate problem of having to look for a job in a job market where the employer has the upper-hand. There are plenty of job-less people out there right now, and unfortunatly, I'm one of them! :(

If you can help... please do! :rolleyes: And maybe, if enough people here in ars get the word out there, that this isn't the best way to conduct an interview, then things might change! :D

-green
 

EgalitarianBovine

Ars Tribunus Angusticlavius
8,086
Why can't the clone() method be exposed as part of the Cloneable interface? Why does it need to be in the public interface for Object?

I should clarify:

Not all objects are cloneable.. and the Java spec recognizes this - it provides the Cloneable interface which cloneable objects should implement. However, the Cloneable interface itself is empty, and the clone() method is part of the Object interface. Why?

-EB
 

lensam69

Ars Scholae Palatinae
746
Here are some other ones (They are simple, but you never know):


Q: How may interfaces can a class implement?
A: As many as it needs.

Q: How do you create a class so that nobody can extend it?
A: Add the keyword "final" in the class declaration.

Q: How many constructors can a class have? How is this called?
A: As many as it needs (With different parameters of course). Polymorphism.

Q: Does Java support recursive functions?
A: Yes.

Q: Would you say Java is an OOP type Language or an Imperative type Language?
A: Both (Imperative languages are based on the memory assignment paradigm. Example a = 3 means that memory cell to which "a" points will store the value "3")


It's the simple questions in life that screw us...
 

vanguard

Wise, Aged Ars Veteran
194
/me risks looking like an idiot

I thought that when I passed objects around I was passing a reference. A copy of the reference but still the reference. I would have said that clone was in object so that's it's there for all it's children to use.

As for java questions, you may want to ask somebody to compare two arrays of values and make sure that array two doesn't have any values that array one is missing.

It's not brain surgery but doing it without looping through the arrays too many times is a nice test of their skill level (according to me).
 

vanguard

Wise, Aged Ars Veteran
194
I forgot to mention my thoughts on language tests. Totally acceptable. It's clearly bad to just try and stump people. Even somebody very good can be stumped so that doesn't prove much.

However, if I'm asking you things that anybody who has actually coded will know to seperate you from the people who have no experience that little language quizes like "Name three exceptions you have thrown" are fine.
 
One question that gets asked is being able to tell the difference between final, finally, and finalize...

final - class cannot be extended (I remember it now that someone mentioned it...)
finally - try/catch/finally (i.e. something you want to do regardless of an exception)
finalize - "the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded" (I forgot this one. oops)
 

lensam69

Ars Scholae Palatinae
746
Originally posted by EgalitarianBovine:
Why can't the clone() method be exposed as part of the Cloneable interface? Why does it need to be in the public interface for Object?

I should clarify:

Not all objects are cloneable.. and the Java spec recognizes this - it provides the Cloneable interface which cloneable objects should implement. However, the Cloneable interface itself is empty, and the clone() method is part of the Object interface. Why?

-EB


Are you sure not all objects are cloneable? Since all objects are extended from the Object superclass and it implements the clone() method they should be clonable.

The problem is that what clone() does is:

The Java runtime system allocates memory for the new instance and copies the memory allocated for the current object.

If object A includes a pointer to some other object B, when you do A1 = A.clone() you are creating a copy of A, which also points to B.


For example, if you have

class person and class employee so that you acces a name like this:
code:<HR>
Code:
mike = new Person("mike asus");
employee1 = new Employee(mike);

then
code:<HR>
Code:
employee1.name()
will return "mike asus"

if you say:


code:<HR>
Code:
employee2 = employee1.clone();
employee2.setName("Alan Abit");<P>

then
code:<HR>
Code:
employee2.name()
will return "Alan Abit"
and ALSO
code:<HR>
Code:
employee1.name()
will return "Alan Abit"


You need the Clonable interface so you can create your own cloning methods; But since it's getting late i leave that one to the java gurus out there.

night y'all.... :cool:
 

lensam69

Ars Scholae Palatinae
746
Originally posted by vanguard:
/me risks looking like an idiot

I thought that when I passed objects around I was passing a reference. A copy of the reference but still the reference.


Sorry, my bad. Let me clarify: Indeed you are passing a copy of the object. The problem is that what you see as the content of the object, in most cases, isn't a part of the object itself. Instead it's something that is pointed to by the actuall content of the object(AKA pointers). So when you create a copy of the object, you create a diferent set of pointers which also point to the original content. Thats why modifying the copy's content can alter the original
 

green_buddy

Wise, Aged Ars Veteran
126
I haven't gone to the Java language spec for this one, but I have perused the javadocs a bit regarding Clonable (and Serializable)...

Originally posted by lensam69:

You need the Clonable interface so you can create your own cloning methods; But since it's getting late i leave that one to the java gurus out there.

I think rather than the Clonable interface allowing you to be able to create your own cloning methods, it behaves more like a vm indicator providing for the object to be cloned when called. Similar to the Serializable interface where when writing and reading an Object from a Stream it's able to store and restore the state of that Object, or if overriding the private void readObject/writeObject methods, then you can choose how you want the state of the Object to be saved... which I have found to be buggy (the overriding part, not the pure serializing part).

Isn't the fact that class Object itself contains a clone() method reason enough to be able to create my own clone() method simply by being able to override it? I mean, if I'm a class, then I'm a subclass of Object by default, and I can override the clone() method too by the mere fact that I'm a derivative of Object, not because I implement the Clonable interface... the interface itself is empty. Of course, you need to implement the interface so that you indicate to the vm which objects you want to have malloc'd and memcopy'd when I call clone(). Although, I know absolutetly nothing of c/c++ lingo so it's highly possible that I could be using malloc, and memcopy incorrectly.

Question: If the Serializable and Cloneable interfaces are empty, why do I need them, and what is it they do?

-green
 

gumbo

Ars Tribunus Angusticlavius
6,107
I always learned that it was more of a "placeholder" or an identification - i.e. the vm/compiler simply used them as a flag that that object was Cloneable or Serializeable. For example, in the Sun tutorials, it notes that a class must implement Serializeable to be able to be serialized.

In the Javadoc for Cloneable, it says this:

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

Attempts to clone instances that do not implement the Cloneable interface result in the exception CloneNotSupportedException being thrown.

The interface Cloneable declares no methods.

This is inline with what I said above.

gubmo
 

EgalitarianBovine

Ars Tribunus Angusticlavius
8,086
This is my understanding of why cloneing is the way it is on java:

The clone() method is exposed on Object's interface because it needs to be there. The only standard way of creating instances in java is throw constructing one. With cloning, you don't want to re-construct an instance from scratch, you want to copy an instance that's already there. So there needs to be a method with an implementation that does this task for you. It can't be simply exposed on the Cloneable interface because interfaces cannot have members that are actually implemented. So clone() is a method that hooks into the VM and creates lightweight copies of instances. The Cloneable interface is provided because even though clone() exists on Object, not all objects are cloneable. To ensure that only classes which support cloneing are cloned, Java provides the Cloneable interface, which is checked for by the implementation of clone().

-EB
 
out of experience doing this kinda thing i find that you always have to start from the extreme bottom first, e.g.

Q: What is the difference between a .java & a .class file?
A: .java is the source, .class is the compiled bytecode.

Q: What is a .jar file
A: A zip file of .class files.

Q: What is Swing?
A: A high level GUI API for Java.

Q: Name three advantages of Java over C++.
A: Garbage collection, cross platform, debugging, etc.

Q: What is reflection?
A: The ability to query the functions provided by a class.

Q: Name a couple of Java development environments
A: Borland JBuilder, Symantec Cafe, IBM VisualAge, Sun SDK, ...

Smarty arse questions are fun too:

Q: Which version of Java is used in MSIE?
A: 1.1, MS refused to implement 1.2 because Sun took them to court.

Q: Which platform has the best reference implementation of the JVM?
A: Windows, the Sun Java engineers develop on Windows first then port back to Solaris including many many O/S patches.

Q: If you are deploying on Linux which JVM should be used?
A: IBM's, because of defects to the posix threads used by Sun (got that one from the head Linux guy at IBM :))
 

green_buddy

Wise, Aged Ars Veteran
126
Originally posted by lensam69:

An interface isn't empty, it has declared functions that aren't implemented. When you implement an interface you have to write what the functions do (implement them)

Yes, I do understand that, but in the case of the Cloneable and Serializable interfaces they are empty, for lack of a better word, meaning they don't declare any methods/functions for the implementee to implement, which brings me back to the original question...

If the Serializable and Cloneable interfaces are empty, why do I need them, and what is it they do?

I think EgalitarianBovine answered it pretty understandably... Thanks! :)

Next question...

What are the different access modifiers available to java, and how are they used wrt classes, constructors, methods and variables?

Another good one I think that causes a lot of good convesation...

Are arguments passed by value, or by reference?

In the case of that one I had a long discussion with a fellow engineer who straightened me out... but I think it covers symantics about the actual defined meanings of pass by value and pass by reference which I think some of my professors in college needed to convey a little more precisely.

-green
 

green_buddy

Wise, Aged Ars Veteran
126
Originally posted by wb:

That's not correct, or at least the question isn't specific enough. You can easily access instance variables and methods from a static method by passing in a reference to the instance as an argument.

Yeah, I was waiting for someone to say that. :( I guess also one of the problems with these types of language quizzes is that you can always have a more correct/specific answer right? I guess i should have stated that you can't access instance variables directly without passing in a reference to the instance!?! But then again, if you're passing in an Object reference, you're not really accessing the instance variable with the static method are you? You're really accessing the passed by value Object reference aren't you? :confused:

Is that specific enough? What would be the most specific answer? How can you be sure that the answer you give is going to be correct enough? All rhetorical questions I guess, since the person it only really matters to is the person asking the question. But I agree, the question is kindof a loaded question... aren't they all in these situations though?

But seriously, what would you want to hear as the answer to my first, original question: Can static methods access instance variables?

-green
 

m1sh1

Smack-Fu Master, in training
89
Hana wrote:

Q: Which version of Java is used in MSIE?
A: 1.1, MS refused to implement 1.2 because Sun took them to court.

Not to turn this into a battlefront issue but MS did not refuse, they were not allowed to do so by Sun. In a way it is kinda sad because MS's JVM was pretty good to me and I loved being able to use Visual J++ to do my development.

As for what kind of questions to ask at an interview well atm I don't have any input, but I like this thread since I get to see what kind of things are considered as important concepts that Java programmers should know.
 

green_buddy

Wise, Aged Ars Veteran
126
Originally posted by m1sh1:

As for what kind of questions to ask at an interview well atm I don't have any input, but I like this thread since I get to see what kind of things are considered as important concepts that Java programmers should know.

Yes... I couldn't agree more! One of the reasons I started it. I think I know what's important, but when I think about it more, I really only know what's important to me ;) I really want to know what other people (namely those in hiring positions) think is important! :D

-green
 

Quaro

Ars Scholae Palatinae
803
Originally posted by lensam69:

employee2 = employee1.clone();
employee2.setName("Alan Abit");

then Quote: "employee2.name()" will return "Alan Abit"
and ALSO Quote: "employee1.name()" will return "Alan Abit"

Isn't that what clone is there to avoid happening? If properly implemented, shouldn't employee1 still have a different name? Or are you saying that this is what happens if you call clone() without implementing it first?
 

lensam69

Ars Scholae Palatinae
746
Originally posted by Quaro:


Isn't that what clone is there to avoid happening? If properly implemented, shouldn't employee1 still have a different name? Or are you saying that this is what happens if you call clone() without implementing it first?


Yeah, If you read the post you'll see it's an example of what happens if you don't implement your own clonning.
 

green_buddy

Wise, Aged Ars Veteran
126
Originally posted by skylark:
Here's a non-trivial one :

In which cases is it better to use an interface instead of an abstract class (or the contrary) ?

Think about it.

Good question!!! :)

The distinction between when it's better to use an interface vs. an abstract class is an important one in Java and OO programming in general.

Interfaces define a general set of behavior that your class may choose to implement, while abstract classes define a default set of behaviors while forcing your subclasses to define others. I think the following article says it best:

JavaWorld - Interfaces vs. Abstract Classes

In short though, interfaces are good in places where you need to implement a certain set of generalized behaviors (ie. List). There are many different types of lists: ArrayList, LinkedList, and Vector - our favorite - just to name a few. However, when it comes to a List(s), they all support the same types of behaviors... you want to be able to add Objects to it, get Objects out of it, and check it's size, and iterate through it's elements, but all the above listed implementations do this in different ways, and also define some of their own distinct behaviors. The List interface allows, and interfaces in general, allow for this.

Abstract classes, on the other hand, allow subclasses to utilize specific pre-defined general behaviors, reducing code redundancy, while at the same time provide subclass-defined behavior for those abstract parts of the parent class.

The definition of "abstract" makes things a little more clear:

abstract(adj): disassociated from any specific instance.

abstract(noun): a summary of points usually presented in skeletal form; also : something that summarizes or concentrates the essentials of a larger thing or several things.

Merriam-Webster Online Dictionary

But for the best explanation, I think the javaworld article is something you should read! ;)

-green
 

OneFootsTheSame

Smack-Fu Master, in training
70
My "best" interview question goes something like this:

Let's work up a basic implementation of an Object Oriented binary tree with an integer key. Don't worry about implementations of add and delete, just declare your class or classes, any members you'll need, and create a search method that will tell me if a node exists in the tree with a given value. I'll also want to know how to use it. Please ask me any questions you have.

There isn't exactly a right answer to this, although there is a basic ~20 line implementation I consider as correct. Mostly what I'm looking at is how the candidate thinks through the problem, if they make it more complex then it needs to be, do they use an OO approach or one class for data and one for functions (shudder), and if they ask questions. I also get to see how they work under pressure. I learn almost everything about a candidate that I can in an interview from this one question.

So, Mr. Green ... what's your answer? ;)
 

wb

Ars Legatus Legionis
25,208
Subscriptor
But seriously, what would you want to hear as the answer to my first, original question: Can static methods access instance variables?

The correct answer is "yes." If someone asked me that question verbatim in an interview, I would say "yes." If they indicated I was wrong, I'd show them their mistake. I can't think of a better way to prove you're a good candidate for the position than to demonstrate innovation and expertise in the same blow.

BTW although in Java the "interface" mechanism is preferable, in C++, especially in Windows/MFC apps, this is a very common way of accessing instance variables and methods from within a callback function.


Here's another interview question that would make me laugh in the interviewer's face:

Q: How many constructors can a class have? How is this called?
A: As many as it needs (With different parameters of course). Polymorphism.

code:<HR>
Code:
public class MyFrame extends Frame
{
   // default constructor
   public MyFrame()
   {
      super( "MyFrame" );
   }<P>   public MyFrame( String name )
   {
      super( name );
   }
}

So, you're telling me the above code demonstrates polymorphism? How?

Rather, polymorphism is something like the following:

code:<HR>
Code:
public class Color
{
   public void printColor()
   {
      System.out.println( "no color defined" );
   }<P>   public static void main( String args[] )
   {
      Color list[] = new Color[4];
      list[0] = new Color();
      list[1] = new Red();
      list[2] = new Green();
      list[3] = new Blue();<P>      for( int i=0; i<list.length; i++ )
         list[i].printColor();
   }<P>}<P>class Red extends Color
{
   public void printColor()
   {
      System.out.println( "Red" );
   }
}<P>class Green extends Color
{
   public void printColor()
   {
      System.out.println( "Green" );
   }
}<P>class Blue extends Color
{
   public void printColor()
   {
      System.out.println( "Blue" );
   }
}
 
Originally posted by wb:
Quote: "
public class MyFrame extends Frame
{
// default constructor
public MyFrame()
{
super( "MyFrame" );
}

public MyFrame( String name )
{
super( name );
}
}
"

So, you're telling me the above code demonstrates polymorphism? How?

It actually does demonstrate one type of polymorphism. Specifically, method overloading. Of course, its not the only type of polymorphism that you can have. Your example is also polymorphism, but not using the same definition ;)
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by hikikomori:]
It actually does demonstrate one type of polymorphism. Specifically, method overloading. Of course, its not the only type of polymorphism that you can have. Your example is also polymorphism, but not using the same definition ;)

Err, yeah. The problem is that "polymorphism" is itself overloaded.

If I got asked that question, I might respond with: "Do you mean ad hoc polymorphism, subtype polymorphism, or parametric polymorphism?"

(kg*m*m)/(s*s)
 

green_buddy

Wise, Aged Ars Veteran
126
Originally posted by OneFootsTheSame:
My "best" interview question goes something like this:

(...)

So, Mr. Green ... what's your answer? ;)

I haven't had time to get anything done on your answer... don't give me a procrastination ding on answering. My first question to this answer (which I expect you to reply with, doesn't matter), is would you like to see pre-order, post-order, or in-order traversal?

But just to let you know, I think this question is academic. They've solved it there many times. What I usually look for is creative thought in complex architectures. Something like, how would you implement the EntityCache for a persistence layer? Something like that. Something that you would never have a chance to learn in school, 'cause it relies on things that most of the professors don't even know themselves... jdbc libraries for one, and also because they are too concerned with how to reduce the runtime of a O(n^2) algorithm to a O(1) algorithm!?! And my thinking on that is, is this something you guys worry about on a daily basis? And the funny thing is... everywhere I've worked so far, never has any implementations of Binary Search Trees, or Binary Trees for that matter for anything. So if they're so important... why aren't they everywhere? Why isn't there an implementation of it in any of the jdk's? More specifically, why isn't there a java.util.tree.* package which includes a BinaryTree, and BinarySearchTree in addition to others?

Anyway... I'll get you an answer to that as soon as I get some time! ;)

-green
 

green_buddy

Wise, Aged Ars Veteran
126
Just a continuation of my last little bit of the rant I was on regarding why there aren't any implementations of java.util.tree.* package and BT, and BST related interfaces/classes...

I think the answer to that is that people aren't writing little utilities anymore. Not writing utilities like grep, sed, awk, ls, etc. Kinda like why I think they need to expand the CS curiculum in academia to include a software patterns course. Something you're required to take after your Object-Oriented Programming class, and your Software Engineering class. But the problem with that is that all the instructors still think basic ADT's are all there is! :eek:

Ok... that ends that... seriously, no more ranting. :rolleyes:

Just so you know, OFTS, I like your question... I've been asked it at every interview I've ever been on, or a related one. It's great! But I don't think it allows you to judge someone software engineering skills by it... but it definitely gives you insight into how the candidate reacts under pressure, and how they approach a problem.

-green
 

wb

Ars Legatus Legionis
25,208
Subscriptor
What is overloaded is the name "MyFrame", no ?

Huh? You mean the fact that MyFrame is derived from Frame means it's polymorphic?

I consider an object polymorphic when accessing the same method or variable via a reference to a base object changes behavior based on the derived object's type. In the case of MyFrame, you must call the constructor explicitly, e.g.:

Frame f = new MyFrame();

So I don't see how the constructor is polymorphic in that case.

Also, I don't consider methods that have the same name, but different parameters as polymorphic, at least in Java. In this case the methods *must* be invoked explicitly based on the argument types and number of arguments. However, in a language like Perl which has loose typing and unspecified arguments to functions, I could see two methods of the same name, even with different arguments, being polymorphic.

Is there some other definition of polymorphism that has become common since I learned OOP?
 

OneFootsTheSame

Smack-Fu Master, in training
70
Green, I agree with you that in practice folks aren't writing utilities like b-trees and such. Unless it's something real quick, you find a library with a good implementation of what you need and use it.

The reason I started using the binary tree question though, was that I needed something to ask people who had just recently gotten their BS or MS and didn't have enough work experience for me to dig into. So I said to myself, "self, what would be a strait forward question that would require a little programming demonstration?" and it just popped out. I figured, this was something people would have seen in school so they would just scratch their head a bit and spit out an answer that would reassure me that they had at least some basic skills. After that I would move on to more "real" questions. What I found in reality was that people have a really hard time with the problem.

I've had everything from answers involving stacks (no kidding), the whole data object and function object approach, to many people who just didn't get it at all and could not produce any kind of acceptable answer. At first I was shocked, but eventually I got over it and accepted the fact that there are a lot of lame "programmers" out there. So many people get into it for the money.

Anyway, I generally prefer to work with real projects the candidate has done instead of academic questions. I had one guy come in with a disc of C++ stuff which I loaded it into my machine and started asking questions about what he had done and why. When I started finding memory leaks (love that debugger), I made him debug it on the spot. I thought the poor guy was going to come unglued, but I sure learned a lot about him. :D (he was a very good candidate by the way, and it was too bad he had immigration problems that prevented us from hiring him.)

I guess what I'm getting at (did I have a point?) is that people need some way to evaluate your skills. Believe a resume? Wahhh ha ha ha ha ha ... they're borderline fiction. So, you either have to defend your work in a previous job, which is a little weak because people can skate by on the work of others, or have samples of your own projects, or it comes down to some kind of programming questions.

A couple other points on interviews. Weak interviews indicate a company that doesn't care about who they hire. Always treat the interview as if it's as much for you as for them (because it is). Do your research and ask questions about the job, product, company, etc.. Don't be afraid of what you don't know. If you don't know something, say so. I catch someone BSing me and it's an immediate two thumbs down.

OKay, sermon over. Good luck!
 
Status
Not open for further replies.