Card Set Information

2010-09-11 16:38:41
java interview questions

Java Interview Questions
Show Answers:

  1. Give a few reasons for using java
    multi-threading, oo, portability, networking, memory management
  2. What is the main difference between the java platform and the other software platforms?
    Software only platform, which compiles into bytecode, and runs on top of the JVM
  3. What is the difference between C++ and Java
    • no pointers
    • no multi inheritance
    • no destructors, but finalize()
    • no structures or unions
  4. What are the usages of Java Packages
    • Helps resolve naming conflicts
    • Helps orginize your files
  5. Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?
    Class loading is hierarchial. Classes are introduced into the JVM as they are referenced. You start with a bootstrap class which has a public static void main, and then the rest of the classes are referenced from there.
  6. What is the difference between constructors and other methods
    • Constructors must have the same name as the class, and cannot return a value. They return a reference to the new object.
    • They are only called once
  7. What are the advantages of OOP?
    OOP represents real life objects, so it's easier to follow along, and match up actions and roles with code. Also, you can have polymorphism, inheritance, and encapsulation. (PIE) This allows reuse of previous work, real mapping to the problem domain, and modular archeture
  8. How do you express an 'is a' relationship and a 'has a' relationship or explain inheritance and composition? What are the differences between composition and aggregation?
    The 'is a' relationship is expressed with inheritance, and 'has a' relationship is expressed with composition.

    Composition means the inner object cannot exsist by it self. Aggregation means the inner object can exsist by it self.
  9. What do you mean by polymorphism?
    Polymorphism - single variable can be given to reference objects of many types. Dynamic binding is the process where the right subclass type is called.
  10. Inheritance
    Inheritance - the inclusion of behavior and state of a base class in a derived class so that they are accessible from that class
  11. Encapsulation
    Keeping the internal details of a class private, and providing good public standard interface promoting modularization. This keeps objects from interacting with each other in unexpected ways.
  12. What is design by contract? Explain the assertion construct?
    • Specifies the obligations of calling-method and called method to each other. Gets the programmer to think clearly about what the fuction does.
    • 1. Preconditions - Use IllegalArgumentException for public methods. Assert for private methods.
    • 2. Postconditions - Checking what must be true after the method returns. Use assert
    • 3. Call invariants - what should always be true
  13. What is the difference between abstract class and interface, and when should you use them.
    Abstract classes should be used when you want to provide a partial implementation, and you want to have the ability to upcast into an object.

    An interface prevents method implementation at all. It provides the seperation of interface and implemention. Coding to an interface reduces coupling.
  14. Why are there some interfaces with no defined methods in Java?
    They tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently.
  15. When is a method said to be overloaded, and when is a method said to be overridden?
    Overloading: multiple methods, same class, same name, but different signatures.

    Overridden: two methods, one in the parent class, and the other in the child class
  16. What is the main difference between an ArrayList and a Vector? HashMap and Hashtable? Stack and Queue?
    Vector and Hashtable are synchronized. ArrayList/HashMap should be preferred, if you need multithreads, you should use collections API external synchronization = Collections.synchronizedMap / synchronizedList. Or in Java 5 you can use java.util.concurrent. Queue is FIFO, Stack is LIFO
  17. Explain the Java Collections Framework?
    Key interfaces are List, Set and Map.

    • Set prevents duplicate elements.
    • List is an ordered sequence of elements, and may contain duplicates
    • Map can contain duplicate values, but the keys must be distinct.
    • Comparable interface should be implemented by objects in a collection.
  18. What are best collection use practices?
    • Use Arraylist/Hashmap over Vector/Hashtable where possible
    • Set the initial capacity of a collection appropriately
    • Program in terms of interface, not implemention.
    • Return zero length collections or arrays as opposed to returning null
    • Immutable objects should be used as keys for the HashMap
    • Encapsulate collections - don't return them to the caller.
    • Avoid storing unrelated or different types of objects into same collection
  19. What is the difference between equals and "==" Or what is the difference between shallow comparision and deep comparison?
    The == performs a shallow comparison, and the equals() performs a deep comparison. Shallow comparison looks at the memory reference. Equals runs the equals() method which if implemented properly will tell us if two objects are similar.
  20. What are the non final methods in the Java Object class which are meant primarily for extension?
    equals(), hashCode(), toString(), clone(), finalize()
  21. When providing a user defined key class for storing obejcts in the HashMaps or Hashtables, what methods do you have to provide or override?
    equals() and hashCode()
  22. What is the main difference between a String and a StringBuffer class?
    String is immutable. StringBuffer can yeild better performance for editing and modifying strings.
  23. What is the main difference between pass-by-reference and pass-by-value
    Java uses pass by value - which means the method gets a copy of the arguments passed in. Pass by reference means that a pointer is used.
  24. What is serialization? How would you exclude a field of a class from serialization or what is a transient variable? What is the common use? What is serial version id?
    • Process of saving an object's state to a sequence of bytes, as well as building them back. Transient variables cannot be serialized. (file handle, db handle, etc)
    • Commonly used for sending an object over the network (EJB, HTTP session) or saving it to a file.
    • Java Serial Version Id can be used to control serialization when the class is updated so old classes can still be read.
  25. Explain the java I/O stream concept and the use of the decorator design pattern in Java I/O
    I/O is defined in terms of streams, which is a sequence of data.

    The decorator pattern is used to add filtering functionality to streams by constructing one stream as using another as input. For example, to add a buffer on a file input stream, you'd create BufferedInputStream(FileInputStream)
  26. How can you improve Java I/O performance?
    • -Buffering
    • -Minimzing and batching calls to the underlying system
    • -Caching like reading in all lines into a memory object.
  27. What is the difference between an instance variable and a static variable?
    Static variables are one per class, and one value is shared among all instances of that class. Instance variables are one per instance, and not shared.
  28. Give an example where you might use a static method?
    • Utilitiy classes
    • Singleton classes
    • Factory classes
  29. What are access modifiers?
    • public, protected, private, and package level.
    • Public can be accessed by everyone. Protected can be accessed by subclasses. Private can be accessed by only internal objects of that class. Package level can be accessed by other classes in the same package.
  30. Where and how can you use a private construtor.
    Singleton pattern. Private constructor is used when you don't want other classes to instantiate the object.
  31. What is a final modifier?
    Final class can't be extended. Final method can't be overridden when it's class is inherited. Final variable cannot be changed.
  32. What is volatile? What is const?
    • const is not yet added to the language
    • volatile synchronizes a single instance variable
  33. if you want to extend the "java.lang.String" class, what methods will you override in your extending class?
    Class is declared final and cannot be extended.
  34. What is the difference beteen final, finally, and finalize in java?
    • final - constant declaration
    • finally - Optional block after a try catch block to clean up after an exception. Will always be called.
  35. Explain outer and inner classes in java. When will you use an inner class?
    An inner class is where a class definition is inside of another class. We should avoid using inner classes.
  36. What is type casting? Explain up casting vs. down casting? When do you get ClassCastException?
    Type casting means treating a veriable of one type as though it is another type. ClassCastException happens during a downcast where the object is not of that type.
  37. What do you know about the Java garbage collector? WHen does the garbage collection occur? Explain different types of references in Java?
    • Garbage collection runs in low memory situations. When it runs it releases the memory allocated by an unreachable object. System.gc() requests the collector run.
    • java.lang.ref allows declaring soft, weak, and phantom references.
    • soft - removed when memory is low
    • weak - removed on the next garbage collection cycle
    • phantom - finalized but the memory will not be reclaimed
  38. Discuss the Java error handling mechanism? What is the difference between Runtime (unchecked) exceptions and checked exceptions? What is the implication of catching all the exceptions with the type "Exception"
    All exceptions are checked except for RuntimeException and subclasses. Checked means that the programmer has to explicitly catch them.

    Catching all exceptions can hide problems and lead to unintelligent and uninformative error handling.
  39. Explain different ways of creating a thread?
    • Extending the thread class
    • Implementing the runnable interface
    • Prefer the runnable interface because it allows for another class to be extended.
  40. What is the difference between yeild and sleeping? What is the difference between methods sleep() and wait() (with threads)
    • yeild = changes from running state to runnable state
    • sleep = changes from running state to waiting/sleeping state

    method wait(1000) causes thread to sleep for up to one second unless recieving a notify() or notiftyAll() method.
  41. How does thread synchronization occurs inside a moniter? What levels of synchronization can you apply? What is the difference between synchronized method and a syncronized block?
    Each object has a lock and a lock can be obtained using synchronized keyword. Method level = course grain, block level = fine grained. Monitor makes sure only one thread executes at a time.
  42. How can threads communicate with each other? How would you implement a producer (one thread) and a consumer (another thread) passing data?
    Use a stack. The wait() notify() and notifyAll() methods are used to provide an efficient way for threads to communicate with each other.
  43. What is the singleton pattern? HOw do you code it in Java?
    where only one class exsists in JVM. You make constructor private, and then create one instance of it.
  44. What is a factory pattern?
    Factory pattern is a creational pattern. Hides how the objects are created. Could create different concrete objects of one abstract class depending on changing conditions.
  45. Explain some of the new features in java 5.0 which improve ease of development
    • Generics - allows you to pass arguments as classes, used mostly with collections
    • Metadata
    • Autoboxing and auto unboxing of primitives
    • Enhanced for loop
    • enumerated type
    • static import
    • C style formatted output
    • formatted input (Scanner)
    • varargs
  46. How would you improve the performance of a Java application?
    • Pool valuable system resources
    • Minimize network overheads or calls to system resources
    • Manage memory and objects efficiently
    • Watch for large synchronization blocks
    • minimize the use of casting or instanceof
    • Avoid inner loops where possible.
    • Minimize JNI calls
  47. How would you detect and minimize memory leaks in Java?
    • Tools: JProbe, OptimizeIt
    • OS tools like vmstat, ps, task manager
    • Minimize:
    • Use weak references if you're the only one using it
    • Letting go of references after you're done
  48. Did you have to use any desing patterns in your Java project?
    • MVC - struts like archeture.
    • Singleton - cache
  49. Tell me about yourself or about some of the recent projects you have worked with?What do you consider your most significant achievement? Why do you think you're qualified for this position? Why should we hire you and what kind of contributions will you make?
    Talk enthusiastically about Order Generation Optimization

    • Design concepts and design patterns - singleton with caching object
    • Performance and memory issues - identifying slowness, using db tool to compare how long calling procs took to narrow down which one caused the slow down, and then devising a way to fix it.
    • Exception handling and best practices - looking through methods to make sure handling in EJB, thowing exceptions to make sure transaction rolled back.
    • Multithreading and concurrent access: care being taken in the design with 10 tables to make sure threads didn't block each other in the database.
  50. Do you have any questions for me?
    • Do you have any performance or desing related issues? - Try to demonstrate how you can help.
    • Why are you hiring?
    • Do you follow any software development processes like agile methodology?
    • Do you use any open source frameworks?
  51. Why are you leaving your current position?
    • I like challenges
    • I love learning new things
    • I like oppertunity to grow into design, architecture, performance tuning
    • I like to meet new people
  52. How do you handle pressure? Do you like or dislike these situations?
    I work very well under pressure. Give support related example (tell story about fix engines).

    I like these situations because it makes the time go by quickly.
  53. What are your strengths?
    • Taking initiative - tell story about Fix engines
    • Design skills - tell story about being frustrated with design of UPS, so working on a different one in spare time
    • Problem solving skills - tell story about finding the sell all bug over the weekend - forming a hypothesis, dissecting the data, stepping through the code line by line...
    • Communication skills - Business loves me -
  54. What are your weaknesses?
    I can be very trusting, which leads to heart ache when people let me down. I tend to have high expectations of myself and others.

    I'm working on being more clear on my expectations by repeating what I am taking away from a conversation
  55. What are your career goals? Where do you see yourself in 5-10 years?
    • Next 2-3 years to become a solution designer or architect.
    • Next 3-5 years to lead a team of developers
  56. Give me an example of a time when you set a goal and were able to achieve it? Give me an example of a time where you showed initiative and took the lead? Tell me about a difficult decision you made in the last year? Give me an example of a time you motivated others? Tell me about a most complex project you were involved in?
  57. Describe a time when you were faced with a stressful situation that demonstrated your coping skills? Give me an example of a time when you used your fact finding skills to solve a problem? Describe a time when you applied your analytical and or problem solving skills?