Pages

Sunday, September 12, 2010

Java Interview Questions Volume 1

Collections

1) Can u explain the collections hierarchy?







The Collection interface is a group of objects with duplicates allowed.
The Set interface extends Collection interface but not allowed duplicates.
The List interface extends Collection interface allows duplicates and introduces positional indexing.
2) What is the List interface?
List represents an ordered collection of objects, In a List user can specify the position into which an object must be inserted, and Users can access elements by their index and can also search for objects in the List.
3)  What are the different implementations of List interface?
ArrayList, LinkedList and Vector.
4) Difference between Vector and ArrayList? What is the Vector class?
  1. Vector is synchronized whereas ArrayList is not.
  2. The Vector class provides the capability to implement a growable array of objects.
  3. ArrayList and Vector class both implement the List interface.
  4. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method.
  5. ArrayList has no default size while vector has a default size of 10.
  6. When you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.

5) How do you decide when to use ArrayList and When to use LinkedList?
In an ArrayList direct access to any element based on its index is very fast ,where as in linked list the access to elements by index is comparatively slow. In array list Insertion and deletion are very slow where as in LinkedList it is very fast. So I would use ArrayList where I need fast retrieval by index and I would use LinkedList when I need to do many insertion and deletion.
6) Why is insersion and deletion in ArrayList slow compared to LinkedList?
ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array. During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
7) What is an Iterator?
Iterator is an Interface whose implementations are returned by the iterator() method in the collection classes, Iterators are used for iterating through the elements in a collection, It also allows us to remove elements during the iteration.
8) How do you traverse through a collection using its Iterator?
 Iterators have methods hasNext() and next(). Using hasNext() we can find whether the iterator has more elements and by calling next() we can get the next element.
9) How do you remove elements during Iteration?
 Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.
10) Why are Iterators returned by ArrayList called Fail Fast?
Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
11) What is the significance of ListIterator? Or What is the difference b/w Iterator and ListIterator?
Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements
12) What is difference between array & arraylist?
An ArrayList is resizable, whereas, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.
Array: can store primitive                              ArrayList: Stores object only
Array: fix size                                               ArrayList: resizable
Array: can have multi dimensional
Array: lang                                                  ArrayList: Collection framework
13) Can you limit the initial capacity of vector in java?
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity 
public vector(int initialcapacity)
14) What is the difference between the size and capacity of a Vector?
The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time
15)  What is a Set?
A set is a collection of Objects in which duplicates are not allowed, it models the mathematical set.
16)  What are the main Implementations of the Set interface?
HashSet, TreeSet, LinkedHashSet and EnumSet?
17)  What is an EnumSet?
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.
18)  What is a HashSet?
A HashSet is an Implementation of the SetInterface which internally uses a Hash Table like datastructure(actually elements are stored as keys in a HashMap) structure. It does not guarantee that the insersion order will be maintained and order may not remain constant with time.
19)  What is a TreeSet?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.
20)  Are HashSet and TreeSet thread safe?
Both are not thread safe.
21) What is the difference between set and list?
Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.
Set
  1.       A set represents a collection of elements. Order of the elements may change in the set.
  2.       Set will not allow duplicate values to be stored.
  3.       Accessing elements by their index (position number) is not possible in case of sets.
  4.       Sets will not allow null elements.

List
  1.      A List represents ordered collection of elements. List preserves the order of elements in which they are entered.
  2.      List will allow duplicate values.
  3.      Accessing elements by index is possible in lists.
  4.      Lists allow null elements to be stored.

21) Explain Map Interface?
A Map is a Collection of Key Value Pairs, Each Key is mapped to one value, Keys cannot be duplicated. We can get the value from the map by providing the key.
22)  What Are the Different Collection Views That Maps Provide?
Maps Provide Three Collection Views
1) Key Set - allow a map's contents to be viewed as a set of keys.
2) Values Collection - allow a map's contents to be viewed as a set of values.
3) Entry Set - allow a map's contents to be viewed as a set of key-value mappings.
23)  What is a KeySet View?
KeySet is a set returned by the keySet() method of the Map Interface, It is a set that contains all the keys present in the Map.
24)  What is a Values Collection View?
Values Collection View is a collection returned by the valueSet() method of the Map Interface, It contains all the objects present as values in the map.
25)  What is a EntrySet View?
Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map.Entry each of which has both Key and Value.
26) What are the main implementations of Map?
HashMap, HashTable, TreeMap and EnumMap.
27)  What is EnumMap?
A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.
28) What is a HashMap?
HashMap is an implementation of HashMap that is based on the hash table data structure.
29)  What is the HashTable Class then?
HashTable is also like HashMap, It is implementation of map that is based on the hash table data structure but the difference is that HashTable is synchronized and does not allow null keys or values. While HashMap is not synchronized and allows null as key and value.
30) What is a TreeMap?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
31) What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().
32) What is the difference between Enumeration and Iterator?
  • The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.So Enumeration is used whenever we want to make Collection objects as Read-only.
  • Enumeration and Iterator are the interface available in java.util package. 
  • Enumeration contains 2 methods namely hasMoreElements() & nextElement().
  • Iterator contains 3 methods namely hasNext(), next(),remove().Using remove() we can also delete the objects but Enumeration interface does not support this feature.

33) Difference between HashMap and HashTable? Can we make hashmap synchronized?
1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Note on Some Important Terms:
1) Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2) Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap); 

 Threads



34) What is the difference between Thread and Process?
  Threads run inside process and they share the data. One process can have multiple threads, if the process is killed all the threads inside it are killed, they don’t share data.
35) Which thread always runs in a Java program by default ?
Main thread. A thread represents execution of statements. The way the statements are executed is of two types:
1) Single tasking
2) Multi tasking.
 36) What is the difference between single tasking and multitasking ?
Executing only one job at a time is called single tasking. Executing several jobs at a time is called multi tasking. In single tasking, the processor time is wasted, but in multi tasking, we can utilize the processor time in an optimum way.
37) Why threads are called light-weight ?
Threads are light-weight because they utilize minimum resources of the system. This means they take less memory and less processor time.
38) What are all the methods available in the Thread class?
  • isAlive()
  • join()
  • resume()
  • suspend()
  • stop()
  • start()
  • sleep()
  • destroy()


39) How can you stop a thread in Java ?
The Thread.stop() method is unsafe and thus deprecated. If the thread being stopped was modifying common data, that common data remains in an inconsistent state.
A better way would be to have a variable indicating if the thread should be stopped. Other threads may set the variable to make the thread stop. Then, the thread itself may clean up and stop.
Consider the basic example shown below. The thread MyThread will not leave common data in an inconsistent state. If another thread calls the done() method forMyThread while MyThread is modifying data, MyThread will finish modifying the data cleanly before exiting.

public class MyThread extends Thread {
    private boolean threadDone = false;
    public void done() {
        threadDone = true;
    }
    public void run() {
        while (!threadDone) {
            // work here
            // modify common data
        }
    }
}
Note that this method does not eliminate concern about synchronization.
40) What is the difference between ‘ extends Thread’ and ‘implements Runnable’ ? Which one is advantageous? 
extends Thread and implements Runnable – both are functionally same. But when we write extends Thread, there is no scope to extend another class, as multiple inheritance is not supported in Java.

Class Myclass extends Thread, AnotherClass//invalid

If we write implements Runnable, then still there is scope to extend another class

class Myclass extends AnotherClass implements Runnable //valid

This is definitely advantageous when the programmer wants to use threads and also wants to access the features of another class.
You have two ways to do so. First, making your class "extends" Thread class. The other way is making your class implement "Runnable" interface. The latter is more advantageous, cause when you are going for multiple inheritance, then only interface can help. . If you are already inheriting a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread class. Also, if you are implementing interface, it means you have to implement all methods in the interface. Both Thread class and Runnable interface are provided for convenience and use them as per the requirement. But if you are not extending any class, better extend Thread class as it will save few lines of coding. Otherwise performance wise, there is no distinguishable difference. A thread is in the ready state after it has been created and started.
41) What is Thread synchronization?
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors. 
E.g. synchronizing a function:
public synchronized void Method1 () {
// method code. 
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) { 
// synchronized code here.
}
}
42) What is the difference between synchronized block and synchronized keyword ? 
Synchronized block is useful to synchronized a block of statements. Synchronized keyword is useful to synchronize an entire method.
43) What is Thread deadlock ?
When a thread has locked an object and waiting for another object to be released by another thread and the other thread is also waiting for the first thread to release the first object, both the threads will continue waiting forever. This is called ‘Thread deadlock’.
44) What is the difference between the sleep( ) and wait( ) methods ?
Both the sleep( ) and wait( ) methods are used to suspend a thread execution for a specified time. When sleep( ) is executed inside a synchronized block, the object is still under lock. When wait( ) method is executed, it breaks the synchronized block, so that the object lock is removed and it is available.
 Generally, sleep( ) is used for making a thread to wait for some time. But wait( ) is used in connection with notify ( ) or notifyAll( ) mehtods in therad communication.
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000); causes a wait of up to one second. A thread can stop earlier if it receives the notify() or notifyAll() call. Wait() method is defined in class Object and the method sleep() is defined in the class Thread.
45) What is demon thread ?
 A daemon thread is a thread is a thread that executes continuously. Daemon threads are service providers for other threads or objects. It generally provides a background processing.
 46) What is thread life cycle ?
 A thread is created using new Thread( ) statement and is executed by start( ) method. The thread enters ‘runnable’ state and when sleep( ) or wait( ) methods are used or when the thread is blocked on I/O, it then goes into ‘not runnable’ state. From ‘not runnable’ state, the thread comes back to the ‘runnable’ state and continues running the statements. The thread dies when it comes out of run( ) mehtod . These state thransitions of a thread are called ‘life cycle of a thread’. 
47) How can I tell what state a thread is in?
 Prior to java 1.5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two.
          Starting with Java 1.5, you can now get what state a thread is in by using getState() method which returns an Enum of Thread States.

Public class ThreadStates{
Public static void main(String args[])
{
Thread t = new Thread();
Thread.State e = t.getState();
Thread.State[] ts = e.values();
For(int i=0;i
System.out.println(ts[i]);
}

States                                                          Description
NEW                               A Fresh thread that has not yet started to execute
RUNNABLE                     A thread that is executing in the JVM
BLOCKED                        A thread that is blocked waiting for a monitor lock
WAITING                        A thread that is waiting to be notified by another thread
TIMED_WAITING             A thread that is waiting to be notified by another thread for a specific of time
TERMINATED                  A thread who’s run method has ended.

48) What happens when you call Thread.yield() ?
It caused the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield method is Static method of class Thread.
49) What is an object's lock and which objects have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object
50) How would you implement a thread pool?
public class ThreadPool implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool.
51) Is there a separate stack for each thread in Java?
Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations, 
called activation records or stack frame. The activation record contains pertinent information about a method like local variables.



 Exceptions




51) What is an Exception?
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.
52) What is a Java Exception?
A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.
53) What are the different ways to generate and Exception?
There are two different ways to generate an Exception.
  1. Exceptions can be generated by the Java run-time system
Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.
  1. Exceptions can be manually generated by your code.
Manually generated exceptions are typically used to report some error condition to the caller of a method.
54) Where does Exception stand in the Java tree hierarchy?
  • java.lang.Object
  • java.lang.Throwable
  • java.lang.Exception
  • java.lang.Error
55) Is it compulsory to use the finally block?
It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block.
56) How are try, catch and finally block organized?
A try block should associate with at least a catch or a finally block. The sequence of try, catch and finally matters a lot. If you modify the order of these then the code won’t compile. Adding to this there can be multiple catch blocks associated with a try block. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch-finally block.
57) What is a throw in an Exception block?
throw” is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

        throw ThrowableInstance;

        ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

        throw new NullPointerException("thrownException");

58) What is the use of throws keyword?
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.

59) What are Checked Exceptions and Unchecked Exceptions?
The types of exceptions that need not be included in a methods throws list are called Unchecked Exceptions.
  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • ClassCastException
  • IndexOutOfBoundsException
  • IllegalStateException
  • NullPointerException
  • SecurityException

The types of exceptions that must be included in a methods throws list if that method can generate one of these exceptions and does not handle it itself are called Checked Exceptions.
  • ClassNotFoundException
  • CloneNotSupportedException
  • IllegalAccessException
  • InstantiationException
  • InterruptedException
  • NoSuchFieldException
  • NoSuchMethodException

60) What are Chained Exceptions?
The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. Lets take a simple example. You are trying to read a number from the disk and using it to divide a number. Think the method throws an ArithmeticException because of an attempt to divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. This is the place where chained exceptions come in to picture.

            Throwable getCause( )
           
            Throwable initCause(Throwable causeExc)

61). What is Throwable?
Throwable is a class that represents all errors and exceptions which may occur in Java.
62). What is the difference between an exception and an error?
An exception is an error which can be handled. It means when an exception happens, the programmer can do something to avoid any harm. But an error is an error which cannot be handled, it happens and the programmer cannot do any thing.
63). What is the difference between throws and throw ?
throws clause is used when the programmer does not want to handle the exception and throw it out of a method. throw clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block. Hence, throws and throw are contradictory.

 General Questions

64) Why pointers are eliminated from java?
1.   Pointers lead to confusion for a programmer.
2.   Pointers may crash a program easily, for example, when we add two pointers, the program crashers immediately. 
3.   Pointers break security. Using pointers, harmful programs like Virus and other hacking programs can be developed. Because of the above reasons, pointers have been eliminated from java.
65) What is the difference between a function and a method?
 method is a function that is written in a class. We do not have functions in java; instead we have methods. This means whenever a function is written in java, it should be written inside the class only. But if we take C++, we can write the functions inside as well as outside the class. So in C++, they are called member functions and not methods.
66) Which part of JVM will allocate the memory for a java program?
 Class loader subsystem of JVM will allocate the necessary memory needed by the java program.
67) Which algorithm is used by garbage collector to remove the unused variables or objects from memory?
Garbage collector uses many algorithms but the most commonly used algorithm is mark and sweep.
68) How can you call the garbage collector?
Garbage collector is automatically invoked when the program is being run. It can be also called by calling gc() method of Runtime class or System class in Java.
69) What is JIT Compiler?
 JIT compiler is the part of JVM which increases the speed of execution of a Java program.
 70) What is the difference between #include and import statement?
  #include directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result, the program size increases, thus wasting memory and processor’s time.
Import statement makes the JVM go to the Java standard library, execute the code there, and substitute the result into the program. Here, no code is copied and hence no waste of memory or processor’s time. So import is an efficient mechanism than #include.
71) What is the difference between print( ) and println( ) method?
 Both methods are used to display the results on the monitor. print() method displays the result and then retains the cursor in the same line, next to the end of the result. println( ) displays the result and then throws the cursor to the next line.
72) What happens if String args[] is not written in main( ) method ?
When main( ) method is written without String args[] as: Public static void main() The code will compile but JVM cannot run the code because it cannot recognize the main( ) as the method from where it should start execution of the Java program. Remember JVM always looks for main( ) method with string type array as parameter.
73) What is the difference between return and System.exit(0) ?
Return statement is used inside a method to come out of it.  System.exit(0) is used in any method to come of the program.
74) What is the difference between System.out.exit(0) and System.exit(1) ?
System.exit(0) terminates the program normally. Whereas System.exit(1)
 terminates the program because of some error encountered in the program.
75) What is the difference between System.out ,System.err and System.in?
System.out and System.err both represent the monitor by default and hence can be used to send data or results to the monitor. But System.out is used to display normal messages and results whereas System.err is used to display error messages and System.in represents InputStream object, which by default represents standard input device, i.e., keyboard.
76) On which memory, arrays are created in Java?
Arrays are created on dynamic memory by JVM. There is no question of static memory in Java; every thing( variables, array, object etc.) is created on dynamic memory only.
77) What is the difference between C++ and Java?
Both C++ and Java use similar syntax and are Object Oriented, but:
  • Java does not support pointers. Pointers are inherently tricky to use and troublesome.
  • Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface inheritance, which allows an object to inherit many method signatures from different interfaces with the condition that the inheriting object must implement those inherited methods. The multiple interface inheritance also allows an object to behave polymorphically on those methods.
  • Java does not support destructors but adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means you do not know when the objects are going to be finalized. Avoid using finalize() method to release non memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these resources through the finalize() method.
  • Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework
78) What is object reference?
 Object reference is a unique hexadecimal number representing the memory address of the object. It is useful to access the members of the object.
79) What is difference between == and equals () while comparing strings ? which one is reliable ?
 = = operator compares the references of the sting objects. It does not compare the contents of the objects. equals ( ) method compares the contents. While comparing the strings, equals( ) method should be used as it yields the correct result.
80) What is a string constant pool?
 String constant pool is a separate block of memory where the string objects are held by JVM. If a sting object is created directly, using assignment operator as: 
String s1 = “Hello”, then it is stored in string constant pool.
81) Explain the difference between the following two statements:
1. String s=”Hello”
2. String s = new String (“Hello”);
In the first statement, assignment operator is used to assign the string literal to the String variable s. In this case, JVM first of all checks whether the same object is already available in the string constant pol. If it is available, then it creates another reference to it. If the same object is not available, then it creates another object with the content “Hello “and stores it into the string constant pool.

In the second statement, new operator is used to create the string object; in this case, JVM always creates a new object without looking in the string constant pool.
82) What is the difference between String and StringBuffer classes?
String class objects are immutable and hence their contents cannot be modified. StringBuffer class objects are mutable, so they can be modified. Moreover the methods that directly manipulate data of the object are not available in String class. Such methods are available in StringBuffer class.
83) Are there any other classes whose objects are immutalbe ?
Yes, classes like Character, Byte, Integer, Float, Double, Long..called ‘wrapper classes’ are created as ‘immutable’. Classes like Class, BigInteger, Big Decimal are also immutable.
84) What is the difference between StringBuffer and StringBuilder classes?
StringBuffer class is synchronized and StringBuilder is not. When the programmer wants to use several threads, he should use StringBuffer as it gives reliable results . If only one thread is used. StringBuilder is preferred, as it improves execution time.
85) What is object oriented approach?
Object oriented programming approach is a programming methodology to design computer programs using classes and objects.
86) What is the difference between a class and an object?
class is a model for creating objects and does not exist physically. An object is
any thing that exists physically. Both the classes and objects contain variables and methods.
87) What is encapsulation?
Encapsulation is a mechanism where the data(varialbes) and the code(methods) that act on the data will bind together. Ex:suppose we are writing one bean. we declaring two private variables. we are providing setters and getters methods of two variables. These variables are accessed in that class.
88) What is abstraction?
Hiding the unnecessary data from the user and expose only needed data is of interest to the user. 
Abstraction is a way to remove the association of the behavior of an object with the actual details behind the scenes which implement that object's behavior. This  abstraction is usually accomplished through the use of base classes with virtual functions; each derived function provides the details that implement the behavior behind that abstraction.
A good example for abstraction is a car. Any car will have some parts like engine, radiator, mechanical and electrical equipment etc. The user of the ca r (driver) should know how to drive the car and does not require any knowledge of these parts. For example driver is never bothered about how the engine is designed and the internal parts of the engine. This is why, the car manufacturers hide these parts from the driver in a separate panel, generally at the front.
89) What is Inheritance?
It creates new classes from existing classes, so that the new classes will acquire all the features of the existing classes is called inheritance. (or) Acquiring the all properties from base class to child class .
90) What is Polymorphism?
The word ‘Polymorphism’ came from two Greek words ‘poly’ meaning ‘many’ and ‘morphs’ meaning ‘forms’. Thus, polymorphism represents the ability to assume several different forms. In programming, we can use a single variable to refer to objects of different types and thus, using that variable we can call the methods of the different objects. Thus a method call can perform different tasks depending on the type of the object.
91) What is the difference between object oriented programming languages and object based programming languages?
Object oriented programming languages follow all the features of Object Oriented Programming System (OOPS). Smalltalk, Simula-67,C++, Java are examples for OOPS languages.
Object based programming languages follow all the features of OOPS except Inheritance. For example, JavaScript and VBScript will come under object based programming languages.
92) What is hash code?
Hash code is unique identification number allotted to the objects by the JVM. This hash code number is also called reference number which is created based on the location of the object in memory, and is unique for all objects, except for String objects.
93) How can you find the hash code of an object?
The hashCode( ) method of ‘Object’ class in java.lang.package is useful to find the hash code of an object.
94) Can you declare a class as ‘private’?
No, if we declare a class as private, then it is not available to java compiler and hence a compile time error occurs, but inner classes can be declared as private.
95) What are instance methods ?
Instance methods are the methods which act on the instance variables of the class. To call the instance methods, we should use the object name;  objectname.methodname( ).
 Ex: double x = obj.sum( );
96) What are static methods?
Static methods are the methods which do not act upon the instance variables of a class. Static methods are declared as ‘static’.
97) What is the difference between instance variables and class variables(static variables)?
  1. An Instance variable is a variable whose separate copy is available to each object. A class variable is a variable whose single copy in memory is shared by all objects.
  2. Instance variables are created in the objects on heap memory. Class variables are stored on method area.
98) Why instance Variables are not available to static methods?
After executing static methods, JVM creates the objects. So the instance variables of the objects are not available to static methods.
99) Is it possible to compile and run a Java program without writing main( ) method?
Yes, it is possible by using a static block in the Java program.
100) How are objects are passed to methods in Java?
Premitive data types, objects, even object references – every thing is passed to methods using ‘pass by value’ or ‘call by value’ concept. This means their bit by bit copy is passes to the methods.
101) What are factory methods?
factory method is a method that creates and returns an object to the class to which it belongs. A single factory method replaces several constructors in the class by accepting different options from the user, while creating the object.
102) In how many ways can you create an object in Java ?
There are four ways of creating objects in Java: 
1.   Using new operator
          Employee obj = new Employee( );
Here , we are creating Employee class object ‘obj’ using new operator. 
2.   Using factory methods:
Number Format obj = NumberFormat. getNumberInstance( );
 Here, we are creating NumberFormatobject using the factory method getNumberInstance( )
3.   Using newInstance( ) method
 Here we should follow tow steps, as:
(a) First, store the class name ‘Employee’ as a string into an object. For this purpose, factory metod forName( ) of the class ‘Class’ will be useful:
                   Class c = Class.forName(“Employee”);
                   We should note that there is a class with the name ‘Class’ in java.lang package.
(b) Next, create another object to the class whose name is in the object c. For this purpose , we need newInstance( ) method of the class ‘Class’ as:
Employee obj = ( Employee)c.newInstance( );
4.    By cloning an already available object, we can create another object. Creating exact copy of an existing object is called ‘cloning’.
Employee obj1 = new Employee ( );
Employee obj2 = (Employee)obj1.clone( );
 Earlier, we created obj2 by cloning the Employee object obj1.clone( ) method of Object class is used to clone object.We should note that there is a class by the name ‘Object’ in java.lang package.
103) What is the advantage of inheritance?
In inheritance a programmer reuses the super class code without rewriting it, in creation of sub classes, so developing the classes becomes very easy. Hence, the programmer’s productivity is increased.
104) Why multiple inheritance is not available in Java ?
Multiple inheritance is not available in Java for the following reasons:
         1. It leads to confusion for a Java program.
         2. The programmer can achieve multiple inheritance by using interfaces.
          3. The programmer can achieve multiple inheritance by repeatedly using single inheritance.
105) How many types of inheritance are there ?
There are two types of inheritances single and multiple. All other types are mere combinations of these two. However, Java supports only single inheritance.
106) What is coercion?
Coercion is the automatic conversion between different data types done by the compiler.
107) What is the difference between method overloading and method overriding ?
OverLoading:
1.   Writing two or more methods with the same name but with different signatures is called method overloading.
2.    Method overloading is done in the same class.
3.    In method overloading, method return type can be same or different.
4.    JVM decides which method is called depending on the difference in the method signatures.
5.    Method overloading is done when the programmer wants to extend the already available features.
6.    Method overloading is code refinement. Same method is refined to perform a different task.
OverRiding:
1.    Writing two or more methods with the same name and same signatures is called method overriding.
2.    Method overriding is done in super and sub classes.
3.    In method overriding method return type should also be same.
4.    JVM decides which method is called depending on the data type (class) of the object used to call the method.
5.    Method overriding is done when the programmer wants to provide a different implementation (body) for the same feature.
6.    Method overriding is code replacement. The sub class method overrides(replaces) the super class method.
108) What is the difference between dynamic polymorphism and static polymorphism ?
Dynamic polymorphism is the polymorphism existed at runtime. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at runtime. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism.
Static polymorphism is the polymorphism exhibited at compile time. Here, Java compiler knows which method is called. Method overloading and method overriding using static methods; method overriding using private or final methods are examples for static polymorphism.
109) Explain static vs dynamic class loading?
Static Class loading:
1.    Classes are statically loased with Java’s new operator.
                   Car car = new Car();
2.    NoClassDefFoundException is thrown, if a class is referenced with java’s new operator, but the run time system cannot find the referenced class.
Dynamic Class loading:
1.    Dynamically loading is a technique for programitically invoking the functions of a class loader at run time.
          Class.forName(String className);
          The above static method returns the class object associated with the class    name. The string className can be supplied dynamically at run time.
          Once the classes is dynamically loaded the flowing method returns an instance        of the loaded class. Its just like creating a class object with no arguments.
          Class.newInstance();
2.    ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definitions for the class with the specified name could not found.
          The forName(..) – Class
          The findSystemClass(..) – ClassLoader
The loadClass(..) – ClassLoader
110) What is implicit casting ?
Automatic casting done by the Java compiler internally is called implicit casting . Implicit casting is done to converty a lower data type into a higher data type.
111) What is explicit casting ?
The casting done by the programmer is called explicit cating. Explicit casting is compulsory while converting from a higher data type to a lower data type.
112) What is the difference between an abstract class and an interface? 
Abstract Class
1.    An abstract class is written when there are some common features shared by all the objects.
2.    When an abstract class is written, it is the duty of the programmer to provide sub classes to it.
3.    An abstract class contains some abstract methods and also some concrete methods.
4.    An abstract class contains instance variables also.
5.    All the abstract methods of the abstract class should be implemented in its sub classes.
6.    Abstract class is declared by using the keyword abstract.
Interfaces
1.    An interface is written when all the features are implemented differently in different objects
2.    An interface is written when the programmer wants to leave the implementation to the third party vendors.
3.    An interface contains only abstract methods.
4.    An interface cannot contain instance variables. It contains only constants.
5.    All the (abstract) methods of the interface should be implemented in its implementation classes.
6.    Interface is declared using the keyword interface.


1 comment:

  1. hi vardhan this isjagan.only thing i can say you is thanQ very much you have done good job.

    ReplyDelete