Card Set Information

2013-05-02 13:00:04

Java Questions and Answers
Show Answers:

  1. 001 [Thread] What are the two ways of creating thread?

    1.Extend Thread and override run() method. Create an instance and invoke the start().

    2. Implements Runnable interface and implement run(). Create an instance of this class. Pass the reference of this instance to the Thread constructor and invoke start()
  2. 002 [Thread] What is use of synchronized keyword?
    1. synchronized keyword can be applied to static/non-static methods or a block of code.

    2. Only one thread at a time can access synchronized methods for an object or a class (static methods).

    3. Synchronized static method provides a lock on class. Synchronize member method provides a lock on object
  3. 003 [Thread] Difference synchronized a static method and synchronize a non static method?
    1. When a synch non static method is called a lock is obtained on the object.

    2. When a synch static method is called a lock is obtained on the class.

    3. The lock on the object and the lock on the class do not interfere with each other.
  4. 004 [Thread] What is a volatile keyword?
    1. In general each thread has its own copy of variable.

    2. The copy of volatile variable is stored in the main memory, every time a thread access the variable even for reading, the local copy is updated each time from the main memory.

    3. The volatile variables have performance issues.
  5. 005 [Thread] Difference between yield() and sleep()?
    1. yield() allows the current thread to release its lock and scheduler gives the lock to the other thread with same priority.        

    2. sleep() allows the thread to go to sleep for x milliseconds. When a thread goes into sleep it doesn’t release the lock.
  6. 006 [Thread] Difference between wait() and sleep()?
    1. sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.

    2. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.
  7. 007 [Thread] Difference between notify() and notfiyAll()?
    1. notify( ) wakes up the first thread that called wait( ) on the same object. 

    2. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first.
  8. 008 [Thread] What happens if a start method is not invoked and the run method is directly invoked?
    1. If a thread has been instantiated but not started its is said to be in new state.

    2. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive.

    3. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread.
  9. 009 [Thread] What happens when start() is called?
    A new thread of execution with a new call stack starts. The state of thread changes from new to runnable. When the thread gets chance to execute its target run() method starts to run.
  10. 010[Thread] Can the variables or classes be Synchronized?
    No. Only methods and code block can be synchronized.
  11. 011 [Thread] Can a thread call multiple synchronized methods on the object of which it hold the lock?
    Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that same object using the lock that it already holds.
  12. 012 [Thread] Can static methods be synchronized?
    Yes. As static methods are class methods and have only one copy of static data for the class, only one lock for the entire class is required. Every class in java is represented by java.lang.Class instance. The lock on this instance is used to synchronize the static methods.
  13. 013 [Thread] Can two threads call two different static synchronized methods of the same class?
    No. The static synchronized methods of the same class always block each other as only one lock per class exists.
  14. 014 [Thread] What are the methods of the thread class used to schedule the threads?
    • 1. sleep(long millis)  
    • 2. yield()public fina
    • 3. join()
    • 4. setPriority(int priority)
    • 5. wait()
    • 6. notify()
    • 7. notifyAll()
  15. 015 [Thread] Which thread related methods are available in Object class?
    • 1. wait()
    • 2. notify()
    • 3. notifyAll()
  16. 016 [Thread] Which thread related methods are available in Thread class?
    • 1. sleep()
    • 2. yield()
    • 3. setPriority()
    • 4. start()
    • 5. interrupt()
    • 6. join()
    • 7. run()
    • 8. resume()
  17. 017 [Thread] What is thread starvation?
    Thread starvation occurs if a low priority thread is not able to run or get a lock on the resoruce because of presence of many high priority threads.
  18. 018 [Thread] What is join()
    The join method allows one thread to wait for the completion of another.

    If t is a Thread object whose thread is currently executing, t.join() causes the current thread to pause execution until t's thread terminates.
  19. 019 [Collection] What is difference between ArrayList and vector?
    • 1. Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe.
    • 2. Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
  20. 020 [Collection] How can Arraylist be synchronized?
    Collection.synchronizedList(List list)

    Collection.synchronizedMap(Map map)

    Collection.synchronizedCollection(Collection c)
  21. 021 [Collections] How can I sort an ArrayList?
    1. Implement Comparable interface and override the compareTo(Object obj) method, and call Collections.sort() method and pass list as an argument.

    2. Create Comparator and override the compare(Object obj, Object obj1) method . Call Collections.sort() on the list and pass comparator as an argument.
  22. 022 [Collection] What are the classes implementing List interface?
    1. ArrayList : It is a resizable array implementation. Data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

    2. Vector: It is thread-safe implementation of ArrayList.

    3. LinkedList: LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.
  23. 023 [Collection] Which all classes implement Set interface?
    1. SortedSet - It is an interface which extends Set.  All elements inserted into the interface must implement Comparable or Comparator interface.

    2. TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.

    3. HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set;  This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets
  24. 024 [Collection] What is difference between Arrays and ArrayList ?
    1. Arrays are created of fix size whereas ArrayList is of not fix size.

    2. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.

    3. ArrayList is one dimensional but array can be multidimensional.

  25. 025 [Collection] When to use ArrayList or LinkedList ?
    ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.
  26. 026 [Collection] Is it better to have a HashMap with large number of records or n number of small hashMaps?
    1. If the objects are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.

    2. If the objects are of different type then also one can have single hashmap but different hashmap would score over it as it would have better readability.
  27. 027 [Collection] Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();
    1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.

    2. The most important one – When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible
  28. 028 [Collection] HashMap vs Hashtable vs HashSet
    Hashtable is basically a data structure to retain values of key-value pair.

    • 1. It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
    • 2. It is synchronized. So it comes with its cost. Only one thread can access in one time.

    HashMap also accepts key value pair.

    • 1. It allows null for both key and value
    • 2. It is unsynchronized. So come up with better performance

    HashSet does not allow duplicate values.

    • 1. It provides add method rather put method.
    • 2. You also use its contain method to check whether the object is already available in HashSet.
    • 3. HashSet can be used where you want to maintain a unique list.
  29. 029 Override vs Overload
    Overload - different parameter number and/or types.

    Override - Subclass rewrite the method without changing its signature.
  30. 030 What’s the point of having a private constructor?
    1. In the singleton design pattern.

    2. Prevent creation of objects
  31. 031 Copy constructor
    A copy constructor is a constructor that takes only one parameter which is the same exact type as the class in which the copy constructor is defined.

    Why: we my not want other to access the original object.
  32. 032 Finally runs after return
    1. Yes. The code in a finally block will take precedence over the return statement.

    2. Return in finally will override return in try. It is bad to have return in finally.
  33. 033 Dynamic binding in Java
    Dynamic binding basically means that the method implementation that is actually called is determined at run-time. For example, polymorphism
  34. 034 Can constructors be synchronized in Java?
    Synchronizing a constructor does not make sense simply because only one thread needs to have access to a constructor. Only the thread that creates an object needs to have access to it while it is being constructed. In other words, there is no need to switch out of the constructor to another thread. Also, when the constructor is called, the object does not even exist yet.
  35. 035 Does Java pass by reference or by value?
    1. Java passes everything by value, and not by reference

    2. Object - The reference is passed by value because a copy of the reference value is created and passed into the other object.

    3.  Variable of a class type stores an address of the object, and not the object itself. The object itself is stored at the address which the variable points to.
  36. 036 Downcasting
    1. Anytime an object of that base class type is type cast into a derived class type, it is called a downcast.

    2. If the object is created from parent class, down casting will cause run time error.

    3. Check if down casting is valid: if (getClass( ) != anObject.getClass())
  37. 037 Can an interface extend another interface in Java?

    • public interface FourLegs extends Body {
    •   public void walkWithFourLegs( );
    • }
  38. 038 equals() vs ==
    1. ==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory.

    2. If not override, by default, the equals() method actually behaves the same as the “==” operator.
  39. 039 Reflection
    1. Reflection in Java is the ability to examine and/or modify the properties or behavior of an object at run-time.

    2. Java reflection is part of an API package

    3. Reflection exposes the internals of a class

    4. Reflection can slow down performance because reflection involves types that are resolved at run-time
  40. 040 When should inner classes be used in Java?
    1. Inner classes allow you to define one class inside another class. A class can have member classes, just like how classes can have member variables and methods.

    2. Combine related things into a big one, such as one object with its event handler. Also they need to inheritance different classes.

    3. Reuse - An instance of an inner class can access members of an instance of the outer class, because an inner class is just another member of the outer class. And, inner classes can even access the private members of the outer class
  41. 041 How to create inner class instance
    • 1. Inside outer class: 
    •     InnerClass inClass = new InnerClass();

    • 2. Outside of the outer class code or static code
    •     OuterClass.InnerClass inner = new OuterClass().new InnerClass();

  42. 042 What is the difference between an inner and nested class in Java?
    • 2. An inner class in non static.
    • 2. An nested class is a static inner class but it cannot access outer class member variables if they are not static.
  43. 043 Anonymous classe
    1. Anonymous classes in Java are more accurately known as anonymousinner classes

    • class ProgrammerInterview {
    •    public void read() {
    •       System.out.println("Programmer Interview!");
    •    }
    • }

    • class Website {
    •    ProgrammerInterview pInstance = new ProgrammerInterview() {
    •       public void read() {
    •          System.out.println("anonymous ProgrammerInterview");
    •       }
    •    };
    • }

    2. Anonymous inner classes are especially useful when you only need to override a small amount of functionality (like just one method) in a superclass, and don’t want to deal with the overhead of creating an entire class for something so simple.
  44. 044 Argument defined anonymous inner class
    • interface ExampleInterface {
    •    void interfaceMethod();
    • }

    • class ExampleClass {
    •    void exampleMethod(ExampleInterface e) {}
    • }

    classSomeOtherClass {

    •    void start(){
    •       ExampleClass ex = new ExampleClass();
    •       ex.exampleMethod (new ExampleInterface () {
    •          public void interfaceMethod() {
    •          System.out.println("Hello!");
    •       } //end interfaceMethod
    •     }//end anonymous inner class definition
    •   ); //end argument and exampleMethod call
    • }