Sie sind auf Seite 1von 32

JAVA INTERVIEW QUESTIONS

INDEX
1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

Threads Object Serialization Java Exceptions: Abstract Class and Interface Classes and Objects OOPs String Java Garbage Collection Java Collections Cloning in Java

TOP

JAVA INTERVIEW QUESTIONS

THREADS
1. What is a thread? Can the run() method be called directly to start a thread?

A thread is a single sequential flow of control within a program. The thread behaviors include starting, sleeping, running, yielding, and having a priority. There are a number of situations where you might want to explicitly use threads to improve the performance, responsiveness, or organization of your programs. There are two ways to create a thread. One is to subclass Thread and override the run() method; The other one is to implement the Runnable interface.

Subclassing Thread and overriding run() Method


The following is an example of creating a thread by subclassing the Thread class:
import java.lang.*; public class MyThread extends Thread { public MyThread (int count) { this.count = count; } private int count = 0; public void run() { .... /*put all the code here that you want this thread to accomplish */ } }

The run() method is where the meat is, it contains the code to implement the logic that this thread class is designed to do. The proper way to start this kind of threads is to call the start() method of the class: MyThread t = new MyThread(5); t.start();

Implementing the Runnable interface


The following is an example of creating a thread by implementing the Runnable interface:
class MyRunnable implements Runnable { public MyThread (int count) { this.count = count;

TOP

JAVA INTERVIEW QUESTIONS


} private int count = 0; public void run() { .... /*put all the code here that you want this thread to accomplish */ } }

The proper way to start this kind of threads is to create an instance of the Runnable class, and pass the reference to the Thread constructor, then call the start() method of the Thread: MyRunnable r = new MyRunnable(5); new Thread(r).start(); 2. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? In both the above examples, the run() method is the most important method in the thread classes, it is also the only method that we need to implement in both cases. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? Because the run() method is not a regular class method. It should only be called by the JVM. Writing thread classes is not about a single sequential thread, it's about the use of multiple threads running at the same time and performing different tasks in a single program. The JVM needs to work closely with the underneath operating system for the actual implementation of concurrent operations. This is how the performance can be improved, and all other benefits mentioned above can be achieved. You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller's thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. Especially for the computers have a single processor, it is impossible to run all running threads at the same time. The JVM must implement a scheduling scheme that shares the processor among all running threads. This is why when you call the start() methods from more than one thread, the sequence of execution of the corresponding run() methods is random, controlled only by the JVM. 3. What are three ways in which a thread can enter the waiting state? Or What are different ways in which a thread can enter the waiting state? A thread can enter the waiting state by the following ways: 1. Invoking its sleep() method, 2. By blocking on I/O 3. By unsuccessfully attempting to acquire an objects lock
TOP

JAVA INTERVIEW QUESTIONS

4. By invoking an objects wait() method. 5. It can also enter the waiting state by invoking its (deprecated) suspend() method. 4. What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state. 5. How to create multithreaded program? Explain different ways of using thread? When a thread is created and started, what is its initial state? Or Extending Thread class or implementing Runnable Interface. Which is better? 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. 6. What is mutual exclusion? How can you take care of mutual exclusion using Java threads? Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object. 7. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. 8. What invokes a threads run() method? After a thread is started, via its start() method of the Thread class, the JVM invokes the threads run() method when the thread is initially executed. 9. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(), notify() and notifyAll() methods are used to provide an efficient way for thread intercommunication. 10. What is thread? What are the high-level thread states? Or What are the states associated in the thread? A thread is an independent path of execution in a system. The high-level thread states are ready, running, waiting and dead. 11. What is deadlock? When two threads are waiting for each other and cant proceed until the first thread obtains a lock on the other thread or vice versa, the program is said to be in a deadlock. 12. How does multithreading take place on a computer with a single CPU?

TOP

JAVA INTERVIEW QUESTIONS

The operating systems task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. 13. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the methods object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. 14. Can Java object be locked down for exclusive use by a given thread? Or What happens when a thread cannot acquire a lock on an object? Yes. You can lock an object by putting it in a synchronized block. The locked object is inaccessible to any thread other than the one that explicitly claimed it. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an objects lock, it enters the waiting state until the lock becomes available. 15. Whats the difference between the methods sleep() and wait()? The sleep method is used when the thread has to be put aside for a fixed amount of time. Ex: sleep(1000), puts the thread aside for exactly one second. The wait method is used to put the thread aside for up to the specified time. It could wait for much lesser time if it receives a notify() or notifyAll() call. Ex: wait(1000), causes a wait of up to one second. The method wait() is defined in the Object and the method sleep() is defined in the class Thread. 16. What is the difference between process and thread? A thread is a separate path of execution in a program. A Process is a program in execution. 17. What is daemon thread and which method is used to create the daemon thread? Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon() When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads. 18. What do you understand by Synchronization? Or What is synchronization and why is it important? Or Describe synchronization in respect to multithreading? Or What is 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 objects 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:
TOP

JAVA INTERVIEW QUESTIONS

public Method2 (){ synchronized (this) { // synchronized code here. } } 19. If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously? No. Only one thread can hold the lock of the object. And then it's only that thread that can enter the synchronized methods on that object. The thread can however release the lock without returning from the method, by calling Object.wait(). If not, what would be the state of t2 ? It would sit tight and wait for t1 to release the lock (return from the method or invoke Object.wait()). Specifically, it will be in a BLOCKED state. 20. When you will synchronize a piece of your code? When you expect that your shared code will be accessed by different threads and these threads may change a particular data causing data corruption, then they are placed in a synchronized construct or a synchronized method. 21. Why would you use a synchronized block vs. synchronized method? Synchronized blocks place locks for shorter periods than synchronized methods. 22. What is an objects lock and which objects have locks? Answer: An objects 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 objects lock. All objects and classes have locks. A classs lock is acquired on the classs Class object. 23. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the classs Class object. 24. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state. 24. 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. 25. 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.

Object Serialization:
26. How many methods in the Serializable interface? Which methods of Serializable interface should I implement?
TOP

JAVA INTERVIEW QUESTIONS

There is no method in the Serializable interface. Its an empty interface which does not contain any methods. The Serializable interface acts as a marker, telling the object serialization tools that the class is serializable. So we do not implement any methods. 27. What is the difference between Serializalble and Externalizable interface? How can you control over the serialization process i.e. how can you customize the seralization process? When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process. How to make a class or a bean serializable? How do I serialize an object to a file? Or 28. What interface must an object implement before it can be written to a stream as an object? An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file. 29. What happens to the object references included in the object? The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original object. 30. What is serialization? The serialization is a kind of mechanism that makes a class or a bean persistent by having its properties or fields and state information saved and restored to and from storage. That is, it is a mechanism with which you can save the state of an object by converting it to a byte stream. 31. Common Usage of serialization. Whenever an object is to be sent over the network or saved in a file, objects are serialized. 32. What happens to the static fields of a class during serialization? There are three exceptions in which serialization doesnt necessarily read and write to the stream. These are 1. Serialization ignores static fields, because they are not part of any particular state. 2. Base class fields are only handled if the base class itself is serializable. 3. Transient fields. 33. What one should take care of while serializing the object? One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException. 34. What is a transient variable? Or Explain the usage of the keyword transient? Or What are Transient and Volatile Modifiers A transient variable is a variable that may not be serialized i.e. the value of the variable cant be written to the stream in a Serializable class. If you don't want some field to be serialized, you can mark that field transient or static. In such a case when the class is retrieved from the ObjectStream the value of the variable is null.

TOP

JAVA INTERVIEW QUESTIONS

Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program. 35. What is Serialization and deserialization? Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. 36. What is Externalizable? Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

Java Exceptions:
35.
Explain the user defined Exceptions?

User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions. Example: class CustomException extends Exception { } 36.
What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions 37. What is the difference between exception and error?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.) Error: Any departure from the expected behavior of the system or program, which stops the working of the system is an error. Exception:Any error or problem which one can handle and continue to work normally. Note that in Java a compile time error is normally called an "error," while a runtime error is called an "exception." Errors don't have subclasses while exception has two subclasses, they are compile time exception or checked exception (ClassNotFound Exception, IOException, SQLException etc.) and runtime or unchecked exception(ArrayIndexOutOfBounds Exception, NumberFormat Exception).
TOP

JAVA INTERVIEW QUESTIONS

38.

What is the difference between throw and throws keywords?

The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as an argument. The exception will be caught by an enclosing try-catch block or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method. An exception can be rethrown. 39.
What class of exceptions are generated by the Java run-time system?

The Java runtime system generates Runtime Exceptions and Errors. 40.
What is the base class for Error and Exception?

Throwable 41.
What are Checked and Unchecked Exceptions?

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the exception may be thrown. Checked exceptions must be caught at compile time. Example: IOException. Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions. 42.
Does the code in finally block get executed if there is an exception and a return statement in a catch block? Or What is the purpose of the finally clause of a trycatch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(0) statement is executed earlier or on system shut down earlier or the memory is used up earlier before the thread goes to finally block. try{ //some statements } catch{ //statements when exception is caught } finally{ //statements executed whether exception occurs or not } 43.
Does the order of placing catch statements matter in the catch block?

TOP

JAVA INTERVIEW QUESTIONS

Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is caught before IOException. Exceptions subclasses have to be caught first before the General Exception

Abstract Class and Interface:


44.
What is the difference between Abstract class and Interface Or When should you use an abstract class, when an interface, when both? Or What is similarities/difference between an Abstract class and Interface? OrWhat is the difference between interface and an abstract class?

Abstract class is a class which contains one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present. All variables in an Interface are by default - public static final while an abstract class can have instance variables. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance. An Interface can only have public members whereas an abstract class can contain private as well as protected members. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast

Note: There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an interface. Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface. Similarities: Neither Abstract classes nor Interface can be instantiated. 45.
What does it mean that a method or class is abstract?

An abstract class cannot be instantiated. Only its subclasses can be instantiated. A class that has one or more abstract methods must be declared abstract. A subclass that does not provide an implementation for its inherited abstract methods must also be declared abstract. You indicate that a class is abstract with the abstract keyword like this: public abstract class AbstractClass Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the class. It exists only to be overridden in subclasses. Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each
TOP

JAVA INTERVIEW QUESTIONS

subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract. Only the methods prototype is provided in the class definition. Also, a final method can not be abstract and vice versa. Methods specified in an interface are implicitly abstract. . It has no body. For example, public abstract float getInfo() 46.
What must a class do to implement an interface?

The class must provide all of the methods in the interface and identify the interface in its implements clause. 47.
What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass. 48. Or What is a cloneable interface and how many methods does it contain? An Interface are implicitly abstract and public. Interfaces with empty bodies are called marker interfaces having certain property or behavior. Examples:java.lang.Cloneable,java.io.Serializable,java.util.EventListener. An interface body can contain constant declarations, method prototype declarations, nested class declarations, and nested interface declarations. Interfaces provide support for multiple inheritance in Java. A class that implements the interfaces is bound to implement all the methods defined in Interface. Example of Interface: public interface sampleInterface { public void functionOne(); public long CONSTANT_ONE = 1000; } 49.
What is an abstract class? Or Can you make an instance of an abstract class? What is interface? How to support multiple inhertance in Java?

Abstract classes can contain abstract and concrete methods. Abstract classes cannot be instantiated directly i.e. we cannot call the constructor of an abstract class directly nor we can create an instance of an abstract class by using Class.forName().newInstance() (Here we get java.lang.InstantiationException). However, if we create an instance of a class that extends an Abstract class, compiler will initialize both the classes. Here compiler will implicitly call the constructor of the Abstract class. Any class that contain an abstract method must be declared abstract and abstract methods can have definitions only in child classes. By overriding and customizing the abstract methods in more than one subclass makes Polymorphism and through Inheritance we define body to the abstract methods. Basically an abstract class serves as a template. Abstract class must be
TOP

JAVA INTERVIEW QUESTIONS

extended/subclassed for it to be implemented. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. Abstract class is a class that provides some general functionality but leaves specific implementation to its inheriting classes. Example of Abstract class: abstract class AbstractClassExample{ protected String name; public String getname() { return name; } public abstract void function(); } Example: Vehicle is an abstract class and Bus Truck, car etc are specific implementations No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method. 50.
What is meant by "Abstract Interface"?

Firstly, an interface is abstract. That means you cannot have any implementation in an interface. All the methods declared in an interface are abstract methods or signatures of the methods. 51.
How to define an Interface?

In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface. Example of Interface: public interface SampleInterface { public void functionOne(); public long CONSTANT_ONE = 1000; } 52.
Can Abstract Class have constructors? Can interfaces have constructors?

Abstract class's can have a constructor, but you cannot access it through the object, since you cannot instantiate abstract class. To access the constructor create a sub class and extend the abstract class which is having the constructor. Example public abstract class AbstractExample { public AbstractExample(){
TOP

JAVA INTERVIEW QUESTIONS

System.out.println("In AbstractExample()"); } } public class Test extends AbstractExample{ public static void main(String args[]){ Test obj=new Test(); } } 53.
If interface & abstract class have same methods and those methods contain no implementation, which one would you prefer?

Obviously one should ideally go for an interface, as we can only extend one class. Implementing an interface for a class is very much effective rather than extending an abstract class because we can extend some other useful class for this subclass

Classes and Objects:


54.
why java have Object Class? The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class

55.

What restrictions are placed on method overloading? Two methods may not have the same

name and argument list but different return types. 56. What is the difference between String and StringBuffer?

String objects are immutable whereas StringBuffer objects are not. StringBuffer unlike Strings support growable and modifiable strings. 57.
Can a private method of a superclass be declared within a subclass?

Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features. 58.
What is the default value of an object reference declared as an instance variable?

null unless we define it explicitly. 59. Or 60.


How can a subclass call a method or a constructor defined in a superclass? What is the difference between a constructor and a method?

TOP

JAVA INTERVIEW QUESTIONS

A constructor is a member function of a class that is used to create objects of that class, invoked using the new operator. It has the same name as the class and has no return type. They are only called once, whereas member functions can be called many times. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. super.method(); is used to call a super class method from a sub class. To call a constructor of the super class, we use the super(); statement as the first line of the subclasss constructor. 61.
Can a top-level class be private or protected?

No. A top-level class cannot be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access. If a top level class is declared as private/protected the compiler will complain that the "modifier private is not allowed here. 62.
Why Java does not support multiple inheritance?

Java does support multiple inheritance via interface implementation. 63.


Where and how can you use a private constructor?

Private constructor can be used if you do not want any other class to instantiate the class. This concept is generally used in Singleton Design Pattern. The instantiation of such classes is done from a static public method. 64.
How are this() and super() used with constructors? This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. What is Method Overriding? What restrictions are placed on method overriding?

When a class defines a method using the same name, return type, and argument list as that of a method in its superclass, the method in the subclass is said to override the method present in the Superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Restrictions placed on method overriding Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. Methods may be overridden to be more public, not more private. The overriding method may not throw any exceptions that may not be thrown by the overridden method. 65.
What are the Object and Class classes used for? Which class should you use to obtain design information about an object? Differentiate between a Class and an Object?

TOP

JAVA INTERVIEW QUESTIONS

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. The Class class is used to obtain information about an object's design. A Class is only a definition or prototype of real life object. Whereas an object is an instance or living representation of real life object. Every object belongs to a class and every class contains one or more related objects. 66. Or What is singleton pattern? This design pattern is used by an application to ensure that at any time there is only one instance of a class created. You can achieve this by having the private constructor in the class and having a getter method which returns an object of the class and creates one for the first time if its null. 67. Or 68.
What is difference between overloading and overriding? What is method overloading and method overriding? What is a singleton class?

Method overloading: When 2 or more methods in a class have the same method names with different arguments, it is said to be method overloading. Overloading does not block inheritance from the superclass. Overloaded methods must have different method signatures Method overriding : When a method in a class has the same method name with same arguments as that of the superclass,it is said to be method overriding. Overriding blocks inheritance from the superclass. Overridden methods must have same signature. Basically overloading and overriding are different aspects of polymorphism. static/early binding polymorphism: overloading dynamic/late binding polymorphism: overriding 69.
If a class is declared without any access modifiers, where may the class be accessed?

A class that is declared without any access modifiers is said to have package or default access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. 70.
Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its super classes. 71.
TOP Which java.util classes and interfaces support event handling?

JAVA INTERVIEW QUESTIONS

The EventObject class and the EventListener interface support event processing 72.
Can an object's finalize() method be invoked while it is reachable?

An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects. 73.
What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system. It returns the runtime information like memory availability. * Runtime.freeMemory() --> Returns JVM Free Memory * Runtime.maxMemory() --> Returns the maximum amount of memory that the JVM will attempt to use. It also helps to run the garbage collector * Runtime.gc() 74.
What is the purpose of the System class?

The purpose of the System class is to provide access to system resources. 75.
Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable object. 76.
What is a bean? Where can it be used?

A Bean is a reusable and self-contained software component. Beans created using java take advantage of all the security and platform independent features of java. Bean can be plugged into any software application. Bean is a simple class which has set and get methods. It could be used within a JSP using JSP tags to use them. 77.
What is the functionality of instanceOf() ? instanceOf opertaor is used to check whether an object can be cast to a specific type without throwing ClassCastException. 78. What would happen if you say this = null?

It will come up with Error Message "The left-hand side of an assignment must be a variable". 79.
I want to create two instances of a class ,But when trying for creating third instance it should not allow me to create . What i have to do for making this?

One way of doing this would be:

TOP

JAVA INTERVIEW QUESTIONS

public class test1 { static int cntr=0; test1() { cntr++; if(cntr>2) throw new NullPointerException();//u can define a new exception // for this } public static void main(String args[]) { test1 t1= new test1(); System.out.println("hello 1"); test1 t2= new test1(); System.out.println("hello 2"); test1 t3= new test1(); } } 80. What is the difference between an object and an instance? An Object May not have a class definition. eg int a[] where a is an array. An Instance should have a class definition. eg MyClass my=new MyClass(); my is an instance. 81.
What is heap in Java?

It is a memory area which stores all the objects created by an executing program. 82.
Why default constructor of base class will be called first in java?

A subclass inherits all the methods and fields (eligible one) from the base class, so base class is constructed in the process of creation of subclass object (subclass is also an object of superclass). Hence before initializing the default value of sub class the super class should be initialized using the default constructor. 83. What are the other ways to create an object other than creating as new object? We can create object in different ways; 1.new operator 2.class.forName: Classname obj = Class.forName("Fully Qualified class Name").newInstance(); 3.newInstance 4.object.clone 84. What is the difference between instance, object, reference and a class? Class: A class is a user defined data type with set of data members & member functions Object: An Object is an instance of a class
TOP

JAVA INTERVIEW QUESTIONS

Reference: A reference is just like a pointer pointing to an object Instance: This represents the values of data members of a class at a particular time

Strings
85. What is String literal pool? How to create a String There are two ways to create a String object in Java:
Using the new operator. For example, String str = new String("Hello");. Using a string literal or constant expression). For example, String str="Hello"; (string literal) or String str="Hel" + "lo"; (string constant expression).

What is difference between these String's creations? In Java, the equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares the content of two objects rather than two objects' references. The == operator with reference types (i.e., Objects) evaluates as true if the references are identical - point to the same object. With value types (i.e., primitives) it evaluates as true if the value is identical. The equals method is to return true if two objects have identical content - however, the equals method in the java.lang.Object class - the default equals method if a class does not override it - returns true only if both references point to the same object. Let's use the following example to see what difference between these creations of string:
public class DemoStringCreation { public static void main (String args[]) { String str1 = "Hello"; String str2 = "Hello"; System.out.println("str1 and str2 are created by using string literal."); System.out.println(" str1 == str2 is " + (str1 == str2)); System.out.println(" str1.equals(str2) is " + str1.equals(str2)); String str3 = new String("Hello"); String str4 = new String("Hello"); System.out.println("str3 and str4 are created by using new operator."); System.out.println(" str3 == str4 is " + (str3 == str4)); System.out.println(" str3.equals(str4) is " + str3.equals(str4)); String str5 = "Hel"+ "lo"; String str6 = "He" + "llo"; System.out.println("str5 and str6 are created by using string constant expression."); System.out.println(" str5 == str6 is " + (str5 == str6)); System.out.println(" str5.equals(str6) is " + str5.equals(str6)); String s = "lo"; String str7 = "Hel"+ s; String str8 = "He" + "llo"; System.out.println("str7 is computed at runtime."); System.out.println("str8 is created by using string constant

TOP

JAVA INTERVIEW QUESTIONS


expression."); System.out.println(" System.out.println(" } } str7 == str8 is " + (str7 == str8)); str7.equals(str8) is " + str7.equals(str8));

The output result is:


str1 and str2 are created by using string literal. str1 == str2 is true str1.equals(str2) is true str3 and str4 are created by using new operator. str3 == str4 is false str3.equals(str4) is true str5 and str6 are created by using string constant expression. str5 == str6 is true str5.equals(str6) is true str7 is computed at runtime. str8 is created by using string constant expression. str7 == str8 is false str7.equals(str8) is true

The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String literal pool. The String literal pool is a way Java conserves resources.

String Literal Pool


String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example
public class Program { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; System.out.print(str1 == str2); } }

The result is
true

Unfortunately, when you use


TOP

JAVA INTERVIEW QUESTIONS


String a=new String("Hello");

a String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example
public class Program { public static void main(String[] args) { String str1 = "Hello"; String str2 = new String("Hello"); System.out.print(str1 == str2 + " "); System.out.print(str1.equals(str2)); } }

The result is
false true

A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool but can be made to using String's intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added. For example
public class Program { public static void main(String[] args) { // Create three strings in three different ways. String s1 = "Hello"; String s2 = new StringBuffer("He").append("llo").toString(); String s3 = s2.intern(); // Determine which strings are equivalent using the == // operator System.out.println("s1 == s2? " + (s1 == s2)); System.out.println("s1 == s3? " + (s1 == s3));

} }

The output is
s1 == s2? false s1 == s3? true

There is a table always maintaining a single reference to each unique String object in the global string literal pool ever created by an instance of the runtime in order to optimize space. That means that they always have a reference to String objects in string literal pool, therefore, the string objects in the string literal pool not eligible for garbage collection.

TOP

JAVA INTERVIEW QUESTIONS

String Literals in the Java Language Specification Third Edition


Each string literal is a reference to an instance of class String. String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions-are "interned" so as to share unique instances, using the method String.intern. Thus, the test program consisting of the compilation unit:
package testPackage; class Test { public static void main(String[] args) { String hello = "Hello", lo = "lo"; System.out.print((hello == "Hello") + " "); System.out.print((Other.hello == hello) + " "); System.out.print((other.Other.hello == hello) + " "); System.out.print((hello == ("Hel"+"lo")) + " "); System.out.print((hello == ("Hel"+lo)) + " "); System.out.println(hello == ("Hel"+lo).intern()); } } class Other { static String hello = "Hello"; }

and the compilation unit:


package other; public class Other { static String hello = "Hello"; }

produces the output:


true true true true false true

This example illustrates six points:


Literal strings within the same class in the same package represent references to the same String object. Literal strings within different classes in the same package represent references to the same String object. Literal strings within different classes in different packages likewise represent references to the same String object. Strings computed by constant expressions are computed at compile time and then treated as if they were literals. Strings computed by concatenation at run time are newly created and therefore distinct.

The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

Object Oriented Programming Concept


86. What is polymorphism?

TOP

JAVA INTERVIEW QUESTIONS

Polymorphism gives us the ultimate flexibility in extensibility. 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 programs 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
int add(int a,int b) float add(float a,int b) float add(int a ,float b) void add(float a) int add(int a) void add(int a)

Example of Overloading

//error conflict with the method int add(int a)

Example: Overloading
Class BookDetails{ String title; String publisher; float price; setBook(String title){ } setBook(String title, String publisher){ } setBook(String title, String publisher,float price){ } }

Example: Overriding

class BookDetails{ String title; setBook(String title){ } } class ScienceBook extends BookDetails{ setBook(String title){} //overriding setBook(String title, String publisher,float price){ } }

//overloading

87.

In Java, a variable declared type of class A can hold a reference to an object of class A or an object belonging to any subclasses of class A. The program is able to resolve the correct TOP

What is runtime polymorphism in Java?

JAVA INTERVIEW QUESTIONS method related to the subclass object at runtime. This is called the runtime polymorphism in Java. This provides the ability to override functionality already available in the class hierarchy tree. At runtime, which version of the method will be invoked is based on the type of actual object stored in that reference variable and not on the type of the reference variable.
class RuntimePolymorphismDemo { public static void main(String[] args) { Animal ref1 = new Animal(); Animal ref2 = new Dog(); Animal ref3 = new Cow(); Animal ref4 = new Snake(); ref1.whoAmI(); ref2.whoAmI(); ref3.whoAmI(); ref4.whoAmI(); } }

The output is
I I I I am am am am a a a a generic Animal. Dog. Cow. Snake.

88.

Run time binding or compile time binding?

Only overridden instance methods are bound at run time; and this kind of binding depends on the instance object type. For example:
public class Parent { public void writeName() { System.out.println("Parent"); } } public class Child extends Parent { public void writeName() { System.out.println("Child"); } public static void main(String [] args) { Parent p = new Child(); p.writeName(); } }

The output is : Child

TOP

JAVA INTERVIEW QUESTIONS

Instance variables, static variables, static overridden methods (it looks like it's an override, but actually hidden), and overloaded methods are all bound at compile time; and this kind of binding depends on the type of the reference variable and not on the object. For Example:
public class Parent { private static String age = "50"; private String hairColor = "grey"; public void writeName() { System.out.println("Parent"); } } public class Child { private static String age = "20"; private String hairColor = "brown"; public void writeName() { System.out.println("Child"); } public void writeName(String order) { System.out.println(order + " Child"); } public static void main(String [] args) { Parent p = new Child(); System.out.println("age: " + p.age); System.out.println("hairColor: " + p.hairColor); Child c = new Child(); c.writeName("first"); } }

The output is:


age: 50 hairColor: grey first Child

Java Garbage Collection:


89. Explain Garbage collection mechanism in Java? Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic process and can't be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc().
TOP

JAVA INTERVIEW QUESTIONS

90.

What kind of thread is the Garbage collector thread?

It is a daemon thread. 91.


Can an objects finalize() method be invoked while it is reachable?

An objects finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an objects finalize() method may be invoked by other objects. 92.
Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. 93.
What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the object gets garbage collected. For example, closing an opened database Connection. 94.
If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, It can no longer become reachable again.

Java Collections
95.
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 96.
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 doesnt 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.

TOP

JAVA INTERVIEW QUESTIONS

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 doesnt 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); 97.
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements. 2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)

What is the difference between set and list?

98.

A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException. HashSet is based on hashMap and can contain null element 99. How to make a List (ArrayList,Vector,LinkedList) read only?

Can a null element added to a Treeset or HashSet?

Ans) A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown. 100. What is ConcurrentHashMap? Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance. 101. Which is faster to iterate LinkedHashSet or LinkedList? Ans) LinkedList. 102. Which data structure HashSet implements Ans) HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value. 103. Arrange in the order of speed - HashMap,HashTable,
Collections.synchronizedMap , concurrentHashmap

Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable. 104. What is identityHashMap?


TOP

JAVA INTERVIEW QUESTIONS

Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another. 105. What is WeakHashMap? Ans) A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations. 106. How to sort list of strings - case insensitive? Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER); 107. Which all classes implement Set interface? A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface. SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface. 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. 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; in particular, it does not guarantee that the order will remain constant over time. 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

108. What are the classes implementing List interface? There are three classes that implement List interface: 1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe. 2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
TOP

JAVA INTERVIEW QUESTIONS

3) LinkedList: the 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. 109. Consider a scenario. If an ArrayList has to be iterate to read data only, what
are the possible ways and which is the fastest?

It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index. 110. Now another question with respect to above question is if accessing through
iterator is slow then why do we need it and when to use it.

For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

111. Difference between Vector and ArrayList? What is the Vector class? Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. 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. ArrayList has no default size while vector has a default size of 10. 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. 112. What is difference between iterator access and index access? Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the 'n' location and get the element. It doesnot traverse through n-1 elements. In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements. Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure. Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure. Traversal or search in index based datastructure is faster. ArrayList is index access and LinkedList is iterator access. 113. How to sort list in reverse order? To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
TOP

JAVA INTERVIEW QUESTIONS

List list = new ArrayList(); Comparator comp = Collections.reverseOrder(); Collections.sort(list, comp) 114. What is an Iterator interface? Is Iterator a Class or Interface? What is its use? The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator. 115. What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map. 116. What is the List interface? The List interface provides support for ordered collections of objects. 117. How can we access elements of a collection? We can access the elements of a collection using the following ways: 1.Every collection object has get(index) method to get the element of the object. This method will return Object. 2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one. 118. What is the Set interface? The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. 119. Whats the difference between a queue and a stack? Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-firstout (FIFO) rule. 120. What is the Map interface? The Map interface is used associate keys with values. 121. What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used. 122. Which implementation of the List interface provides for the fastest insertion of
a new element into the middle of the list? TOP

JAVA INTERVIEW QUESTIONS

a. Vector b. ArrayList c. LinkedList d. None of the above ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions. 123. How can we use hashset in collection interface? 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; in particular, it does not guarantee that the order will remain constant over time. 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. 124. What are differences between Enumeration, ArrayList, Hashtable and
Collections and Collection? Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or

values of a hashtable. You can not remove elements from Enumeration.


ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements,

including null. It is not thread -safe.


Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in

collection.
Collections: It implements Polymorphic algorithms which operate on collections. Collection: It is the root interface in the collection hierarchy.

125. What is difference between array & arraylist? An ArrayList is resizable, where as, 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 Array: fix size ArrayList: Stores object only ArrayList: resizable

Array: can have multi dimensional


TOP

JAVA INTERVIEW QUESTIONS

Array: lang

ArrayList: Collection framework

126. 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) 127. What method should the key class of Hashmap override? The methods to override are equals() and hashCode(). 128. 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 when ever we want to make Collection objects as Read-only.

Cloning in Java:
129. What are different types of cloning in Java? Ans) Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in Java. Object class has a method clone() which does shallow cloning. 130. What is Shallow copy? Ans) In shallow copy the object is copied without its contained objects. Shallow clone only copies the top level structure of the object not the lower levels. It is an exact bit copy of all the attributes.

Figure 1: Original java object obj The shallow copy is done for obj and new object obj1 is created but contained objects of obj are not copied.

TOP

JAVA INTERVIEW QUESTIONS

Figure 2: Shallow copy object obj1 It can be seen that no new objects are created for obj1 and it is referring to the same old contained objects. If either of the containedObj contain any other object no new reference is created

TOP

Das könnte Ihnen auch gefallen