Pages

Monday, 28 January 2013

Basic OOP interview questions

Basic OOP Questions  :
  1. http://stackoverflow.com/questions/1031273/what-is-polymorphism
The abiltiy to define more than one function with the same name is called Polymorphism. In java,c++ there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).
 
When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class.
Overloading occurs when several methods have same names with
Overloading is determined at the compile time.
 
Different method signature and different number or type of parameters.
Same method signature but different number of parameters.
Same method signature and same number of parameters but of different type 
 
Shape, rectangle and circle is an example of polymorphism
  1. What is encapsulation ? Combining the data and the methods to act on the data and putting them in a class together
  2. COMPOSITION
    Imagine a software firm that is composed of different Business Units (or departments) like Storage BU, Networking BU. Automobile BU. The life time of these Business Units is governed by the lifetime of the organization. In other words, these Business Units cannot exist independently without the firm. This is COMPOSITION. (ie the firm is COMPOSED OF business units)
    ASSOCIATION
    The software firm may have external caterers serving food to the employees. These caterers are NOT PART OF the firm. However, they are ASSOCIATED with the firm. The caterers can exist even if our software firm is closed down. They may serve another firm! Thus the lifetime of caterers is not governed by the lifetime of the software firm. This is typical ASSOCIATION
    AGGREGATION
    Consider a Car manufacturing unit. We can think of Car as a whole entity and Car Wheel as part of the Car. (at this point, it may look like composition..hold on) The wheel can be created weeks ahead of time, and it can sit in a warehouse before being placed on a car during assembly. In this example, the Wheel class's instance clearly lives independently of the Car class's instance. Thus, unlike composition, in aggregation, life cycles of the objects involved are not tightly coupled.
  3. Tip to remember : Composition RBS, association caterer, aggregation car
  4. IS A relationship means you inherit and extend the functionality of the base class.
    HAS A relationship means the class is using another class, so it has it as a member
  5. Composition is a specific case of aggregation
  6. Does java support pass by value or by reference ? Java supports plain pass by value but the object reference it passes will always be the references. Hence manipulations on the objects will always work.



Java Keywords :
  1. What is the volatile keyword in Java ?  When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn’t know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory
  2. ThreadLocal variables
    If you want to maintain a single instance of a variable for all instances of a class, you will use static-class member variables to do it. If you want to maintain an instance of a variable on a per-thread basis, you'll use thread-local variables. ThreadLocal variables are different from normal variables in that each thread has its own individually initialized instance of the variable, which it accesses via get() or set() methods.
    Let's say you're developing a multithreaded code tracer whose goal is to uniquely identify each thread's path through your code. The challenge is that you need to coordinate multiple methods in multiple classes across multiple threads. Without ThreadLocal, this would be a complex problem. When a thread started executing, it would need to generate a unique token to identify it in the tracer and then pass that unique token to each method in the trace.
    With ThreadLocal, things are simpler. The thread initializes the thread-local variable at the start of execution and then accesses it from each method in each class, with assurance that the variable will only host trace information for the currently executing thread. When it's done executing, the thread can pass its thread-specific trace to a management object responsible for maintaining all traces.
    Using ThreadLocal makes sense when you need to store variable instances on a per-thread basis.

  3. I estimate that roughly half of all Java developers know that the Java language includes the keyword volatile. Of those, only about 10 percent know what it means, and even fewer know how to use it effectively. In short, identifying a variable with the volatile keyword means that the variable's value will be modified by different threads. To fully understand what the volatile keyword does, it's first helpful to understand how threads treat non-volatile variables.
    In order to enhance performance, the Java language specification permits the JRE to maintain a local copy of a variable in each thread that references it. You could consider these "thread-local" copies of variables to be similar to a cache, helping the thread avoid checking main memory each time it needs to access the variable's value.
    But consider what happens in the following scenario: two threads start and the first reads variable A as 5 and the second reads variable A as 10. If variable A has changed from 5 to 10, then the first thread will not be aware of the change, so it will have the wrong value for A. If variable A were marked as being volatile, however, then any time a thread read the value of A, it would refer back to the master copy of A and read its current value.
    If the variables in your applications are not going to change, then a thread-local cache makes sense. Otherwise, it's very helpful to know what the volatile keyword can do for you.
  4. http://www.ibm.com/developerworks/java/library/j-5things15/index.html
  5. My understanding : all threads have local copy of the variables. to give them a global copy, use volatile. How is thread local different from normal thread variables. They are accessible from all the functions which are being called from the thread.
  6.  reading a volatile variable is synchronized and writing to a volatile variable is synchronized, but non-atomic operations are not.
  7.  What is a transient variable?
    Ans) If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. When an object is deserialized the transient variables retains the default value depending on the type of variable declared and hence lost its original value.
  8.  static variables/methods/why aren't non static variables accessible by static methods ?
  9.  
Garbage Collection :
  1. http://www.quora.com/How-does-garbage-collection-work-in-the-JVM
  2. http://java-questions.com/garbagecollection_interview_questions.html
  3. http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
  4. What is a strong reference ?  Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. As you don't want the garbage collector destroying objects you're working on
  5. A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.
  6. Reference Queues : Once a WeakReference starts returning null, the object it pointed to has become garbage and the WeakReference object is pretty much useless. This generally means that some sort of cleanup is required; WeakHashMap, for example, has to remove such defunct entries to avoid holding onto an ever-increasing number of dead WeakReferences.
    The ReferenceQueue class makes it easy to keep track of dead references. If you pass a ReferenceQueue into a weak reference's constructor, the reference object will be automatically inserted into the reference queue when the object to which it pointed becomes garbage. You can then, at some regular interval, process the ReferenceQueue and perform whatever cleanup is needed for dead references
  7. Soft references are like weak references, however the object they refer to stick around for a while. What defines this while part ?
  8.  softly reachable objects are generally retained as long as memory is in plentiful supply.
  9. A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead. How is that different from WeakReference, though?
  10. The difference is in exactly when the enqueuing happens. WeakReferences are enqueued as soon as the object to which they point becomes weakly reachable. This is before finalization or garbage collection has actually happened; in theory the object could even be "resurrected" by an unorthodox finalize() method, but the WeakReference would remain dead. PhantomReferences are enqueued only when the object is physically removed from memory, and the get() method always returns null specifically to prevent you from being able to "resurrect" an almost-dead object.
  11. When a weak reference dies, the object enters the reference queue and using an unorthodox finalize method, that object can be got back.However, when a phantom referenced object dies, this kinda method is not going to work as a phantom reference doesn't even support the get method.
  12. Phantom references allow you to determine exactly when an object was removed from memory
  13. http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
  14. What is island of isolation ?  an island of isolation is a group of objects that reference each other but they are not referenced by any active object in the application http://stackoverflow.com/questions/792831/island-of-isolation-of-garbage-collection
  15.  In brief, the GC can walk through the web of references from the known static and stack objects, and either
    • copy all objects found to a new memory pool, automatically leaving behind any "dead" objects (this is the "young generation" strategy), or
    • mark all objects found, so that once the whole web of references is walked traversed, it can delete all unmarked objects (this is the "old/tenured generation" strategy).
  16. What are the different ways to call Garbage Collector ? System.gc() and Runtime.getRuntime.gc()
  17. What is the purpose of overriding finalize() method?
    Ans) The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.
  18. Runtime.getRuntime().runFinalizersOnExit(boolean value)
Questions on the Main Method in Java  :
  1. 1. Main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.

    2. JVM throws NoSuchMethodException:main if it doesn't find main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.

    3. Main method is entry point for any Core Java program. Execution starts from main method.

    4. Main method is run by a special thread called "main" thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from main method is running.

    5. When you see "Exception in Thread main” e.g.
    Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.

    6. You can declare main method using varargs syntax from Java 1.5 onwards e.g.
    public static void main(String... args)

    7. Apart from static, void and public you can use final, synchronized and strictfp modifier in signature of main method in Java.

    8. Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature specified above.

    9. You can use throws clause in signature of main method and can throw any checked or unchecked Exception.

    10. Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.


    http://java67.blogspot.com/2012/12/main-method-interview-questions-in-java-answers.html

SCJP Practice Questions
  1. http://stackoverflow.com/questions/5515050/scjp-question-to-figure-when-object-gets-garbage-collected?rq=1
  2. http://stackoverflow.com/questions/5801732/scjp-mock-question-how-many-objects-are-eligible-for-garbage-collection?rq=1
  3. sd
  4. sd

Collections :
  1. http://stackoverflow.com/questions/1440134/java-what-is-the-difference-between-implementing-comparable-and-comparator
  2. Comparable : an object can compare with itself
  3. Comparator : an object can compare two different objects. When the source code is not available and you have to compare client's code, then you use comparator
  4. LinkedList implements both the List and the Queue interfaces
 http://java-questions.com/keywords_interview_questions.html

No comments:

Post a Comment