Core Java Interview Questions and Answers
Intermediate / 1 to 5 years experienced level questions & answers
Ques 1. What is Cloneable Interface in Core Java?
A clone of an object is an object with distinct identity and equal contents. To define clone, a class must implement cloneable interface and must override Object’s clone method with a public modifier. At this point, it is worth nothing that cloneable interface does not contain the clone method, and Object’s clone method is protected.
Ques 2. What is abstraction?
something which is not concrete , something which is imcomplete.
java has concept of abstract classes , abstract method but a variable can not be abstract.
an abstract class is something which is incomplete and you can not create instance of it for using it.if you want to use it you need to make it complete by extending it.
an abstract method in java doesn't have body , its just a declaration.
so when do you use abstraction ? ( most important in my view )
when I know something needs to be there but I am not sure how exactly it should look like.
e.g. when I am creating a class called Vehicle, I know there should be methods like start() and Stop() but don't know start and stop mechanism of every vehicle since they could have different start and stop mechanism e..g some can be started by kick or some can be by pressing buttons .
the same concept apply to interface also , which we will discuss in some other post.
so implementation of those start() and stop() methods should be left to there concrete implementation e.g. Scooter , MotorBike , Car etc.
In Java Interface is an another way of providing abstraction, Interfaces are by default abstract and only contains public static final constant or abstract methods. Its very common interview question is that where should we use abstract class and where should we use Java Interfaces in my view this is important to understand to design better java application, you can go for java interface if you only know the name of methods your class should have e.g. for Server it should have start() and stop() method but we don't know how exactly these start and stop method will work. if you know some of the behavior while designing class and that would remain common across all subclasses add that into abstract class.
in Summary
1) Use abstraction if you know something needs to be in class but implementation of that varies.
2) In Java you can not create instance of abstract class , its compiler error.
3) abstract is a keyword in java.
4) a class automatically becomes abstract class when any of its method declared as abstract.
5) abstract method doesn't have method body.
6) variable can not be made abstract , its only behavior or methods which would be abstract.
Ques 3. String vs StringBuffer vs StringBuilder in Java
String in Java
1) String is immutable in Java: String is by design immutable in java you can check this post for reason. Immutability offers lot of benefit to the String class e.g. his hash code value can be cached which makes it a faster hashmap key; it can be safely shared between multithreaded applications without any extra synchronization. To know why strings are immutable in java see the link
2)when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools.
3) "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder.
4) Strings are backed up by Character Array and represented in UTF-16 format.
5) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method. To learn how to correctly override equals method in Java see the link.
7) toString() method provides string representation of any object and its declared in Object class and its recommended for other class to implement this and provide string representation.
8) String is represented using UTF-16 format in Java.
9) In Java you can create String from byte array, char array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.
Problem with String in Java
One of its biggest strength "immutability" is a biggest problem of Java String if not used correctly. many a times we create a String and then perform a lot of operation on them e.g. converting string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool. To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.
Differences between String and StringBuffer in Java
Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular interview questions for either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.
Difference between StringBuilder and StringBuffer in Java
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilders vs String.
Summary
1) String is immutable while StringBuffer and StringBuilder is mutable object.
2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
4) Use String if you require immutability, use Stringbuffer in java if you need mutable + threadsafety and use StringBuilder in Java if you require mutable + without thread-safety.
Ques 4. What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ?
The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation
Ques 5. What is JIT and its use?
Really, just a very fast compiler' In this incarnation, pretty much a one-pass compiler '?? no offline computations. So you can'??t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it'??s an on-line problem.
Ques 6. How will you get the platform dependent values like line separator, path separator, etc., ?
Using Sytem.getProperty(') (line.separator, path.separator, ')
Ques 7. What comes to mind when someone mentions a shallow copy and deep copy in Java?
Object cloning.
Java provides a mechanism for creating copies of objects called cloning. There are two ways to make a copy of an object called shallow copy and deep copy.
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.
Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.
Java supports shallow and deep copy with the Cloneable interface to create copies of objects. To make a clone of a Java object, you declare that an object implements Cloneable, and then provide an override of the clone method of the standard Java Object base class. Implementing Cloneable tells the java compiler that your object is Cloneable. The cloning is actually done by the clone method.
Ques 8. Why are there no global variables in Java?
Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.
Ques 9. Which Java operator is right associative?
The = operator is right associative.
Ques 10. Describe what happens when an object is created in Java?
Several things happen in a particular order to ensure the object is constructed properly:
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
Ques 11. How are commas used in the intialization and iteration parts of a for statement?
Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.
Ques 12. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
Ques 13. How many methods in the Serializable interface?
There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.
Ques 14. How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().
Ques 15. What is the difference between Serializalble and Externalizable interface?
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.
Ques 16. What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.
Ques 17. What is reflection?
Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
Ques 18. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
Ques 19. Why isn't there operator overloading?
Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn't even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
Ques 20. What does the keyword "synchronize" mean in java. When do you use it? What are the disadvantages of synchronization?
Synchronize is used when you want to make your methods thread safe. The disadvantage of synchronize is it will end up in slowing down the program. Also if not handled properly it will end up in dead lock.
Ques 21. What synchronization constructs does Java provide? How do they work?
The two common features that are used are:
1. Synchronized keyword - Used to synchronize a method or a block of code. When you synchronize a method, you are in effect synchronizing the code within the method using the monitor of the current object for the lock.
The following have the same effect.
synchronized void foo() {
}
and
void foo() {
synchronized(this) {
}
If you synchronize a static method, then you are synchronizing across all objects of the same class, i.e. the monitor you are using for the lock is one per class, not one per object.
2. wait/notify. wait() needs to be called from within a synchronized block. It will first release the lock acquired from the synchronization and then wait for a signal. In Posix C, this part is equivalent to the pthread_cond_wait method, which waits for an OS signal to continue. When somebody calls notify() on the object, this will signal the code which has been waiting, and the code will continue from that point. If there are several sections of code that are in the wait state, you can call notifyAll() which will notify all threads that are waiting on the monitor for the current object. Remember that both wait() and notify() have to be called from blocks of code that are synchronized on the monitor for the current object.
Ques 22. Do I need to use synchronized on setValue(int)?
It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues.
Ques 23. Which class is the wait() method defined in? I get incompatible return type for my thread getState( ) method!
It sounds like your application was built for a Java software development kit before Java 1.5. The Java API Thread class method getState() was introduced in version 1.5. Your thread method has the same name but different return type. The compiler assumes your application code is attempting to override the API method with a different return type, which is not allowed, hence the compilation error.
Ques 24. What is a working thread?
A working thread, more commonly known as a worker thread is the key part of a design pattern that allocates one thread to execute one task. When the task is complete, the thread may return to a thread pool for later use. In this scheme a thread may execute arbitrary tasks, which are passed in the form of a Runnable method argument, typically execute(Runnable). The runnable tasks are usually stored in a queue until a thread host is available to run them. The worker thread design pattern is usually used to handle many concurrent tasks where it is not important which finishes first and no single task needs to be coordinated with another. The task queue controls how many threads run concurrently to improve the overall performance of the system. However, a worker thread framework requires relatively complex programming to set up, so should not be used where simpler threading techniques can achieve similar results.
Ques 25. What is a green thread?
A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If the Java program has any concurrent threads, the JVM manages multi-threading internally rather than using other operating system threads. There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. Current JVM implementations make more efficient use of native operating system threads.
Ques 26. What are the different level lockings using the synchronization keyword?
Ques 27. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
Ques 28. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.
Ques 29. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
Ques 30. What is a daemon thread?
These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
Ques 31. If an object is garbage collected, can it become reachable again?
Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
Ques 32. What is garbage collection? What is the process that is responsible for doing that in java?
Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
Ques 33. What is the finalize method do?
Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
Ques 34. What is the implementation of destroy method in java.. is it native or java code?
This method is not implemented.
Ques 35. How many times may an object's finalize() method be invoked by the garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.
Ques 36. How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.
Pooling basically means utilizing the resources efficiently, by limiting access of the objects to only the period the client requires it.
Increasing utilization through pooling usually increases system performance.
Object pooling is a way to manage access to a finite set of objects among competing clients. in other words,
object pooling is nothing but sharing of objects between different clients.
Since object pooling allows sharing of objects ,the other clients/processes need to re-instantiate the object(which decreases the load time), instead they can use an existing object. After the usage , the objects are returned to the pool.
Ques 37. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
Ques 38. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Lets say a class Employee belongs to a package com.xyz.hr; and is located in the file c:/dev/com.xyz.hr.Employee.java. In this case, you'd need to add c:/dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:>java com.xyz.hr.Employee
Ques 39. What interface do you implement to do the sorting?
Ques 40. What is the significance of ListIterator?
You can iterate back and forth.
Ques 41. What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
Ques 42. What is nested class?
If all the methods of a inner class is static then it is a nested class.
Ques 43. Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.
Ques 44. What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
Ques 45. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.
Ques 46. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
Ques 47. How will you invoke any external process in Java?
Runtime.getRuntime().exec('.)
Ques 48. What is skeleton and stub? what is the purpose of those?
Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use' it is deprecated long before in JDK.
Ques 49. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
import java.awt.*; import java.applet.*; import java.util.*; public class AppApp extends Applet { public void init() { add(new TextArea("Welcome to withoutbook.com")); String ar[]=new String[2]; ar[0]="Welcome to withoutbook.com"; main(ar); } public void main(String args[]) { System.out.println(args[0]); } }
Ques 50. What is a DatabaseMetaData?
Comprehensive information about the database as a whole.
Ques 51. In a statement, I am executing a batch. What is the result of the execution?
It returns the int array. The array contains the affected row count in the corresponding index of the SQL.
Ques 52. In which case, do we need abstract classes with no abstract methods?
An abstract class without any abstract methods should be a rare thing and you should always question your application design if this case arises. Normally you should refactor to use a concrete superclass in this scenario.
One specific case where abstract class may justifiably have no abstract methods is where it partially implements an interface, with the intention that its subclasses must complete the interface.
Ques 53. What's the use of concrete methods in abstract classes?
One of the design principles of Java inheritance is to create superclass methods that can be used by one or more subclasses, this avoids duplication of code and makes it easier to amend. The same principle holds with abstract classes that are fulfilled by numerous subclasses.
One useful technique with abstract classes is that a concrete method may be defined in anticipation of abstract methods being fulfilled in its subclasses. In the example below the AbstractShape class has a concrete printArea() method that calls the abstract getArea() method. Subclasses inherit the printArea() method and must implement the getArea() method to stand as concrete classes.
Ques 54. Can a method be static and synchronized?
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang. Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) { }
Ques 55. What is Encapsulation in Java and OOPS with Example?
Encapsulation is nothing but protecting anything which is prone to change. rational behind encapsulation is that if any functionality which is well encapsulated in code i.e maintained in just one place and not scattered around code is easy to change. this can be better explained with a simple example of encapsulation in Java. we all know that constructor is used to create object in Java and constructor can accept argument.
Advantage of Encapsulation in Java and OOPS
Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:
1. Encapsulated Code is more flexible and easy to change with new requirements.
2. Encapsulation in Java makes unit testing easy.
3. Encapsulation in Java allows you to control who can access what.
4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading
environment.
5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing
are encapsulated in one place.
6. Encapsulation allows you to change one part of code without affecting other part of code.
What should you encapsulate in code
Anythign which can be change and more likely to change in near future is candidate of Encapsulation. This also helps to write more specific and cohesive code. Example of this is object creation code, code which can be improved in future like sorting and searching logic.
Design Pattern based on Encapsulation in Java
Many design pattern in Java uses encapsulation concept, one of them is Factory pattern which is used to create objects. Factory pattern is better choice than new operator for creating object of those classes whose creation logic can vary and also for creating different implementation of same interface. BorderFactory class of JDK is a good example of encapsulation in Java which creates different types of Border and encapsulate creation logic of Border. Singleton pattern in Java also encpasulate how you create instance by providing getInstance() method. since object
is created inside one class and not from any other place in code you can easily change how you create object without
affect other part of code.
Ques 56. Difference between Thread and Runnable interface in Java?
Here are some of my thoughts on whether I should use Thread or Runnable for implementing task in Java, though you have another choice as "Callable" for implementing thread which we will discuss later.
1) Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.
2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.
3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.
4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.
5) Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.
6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.
Ques 57. Difference between Wait and Sleep , Yield in Java
Difference between Wait and Sleep in Java
Main difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting. Also wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method. Another difference is Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object. also in case of sleep, sleeping thread immediately goes to Runnable state after waking up while in case of wait, waiting thread first acquires the lock and then goes into Runnable state. So based upon your need if you require a specified second of pause use sleep() method or if you want to implement inter-thread communication use wait method.
here is list of difference between wait and sleep in Java :
1) wait is called from synchronized context only while sleep can be called without synchronized block. see Why wait and notify needs to call from synchronized method for more detail.
2) wait is called on Object while sleep is called on Thread. see Why wait and notify are defined in object class instead of Thread.
3) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awaken by calling notify method.
4) wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread on sleep.
5) wait release lock on object while waiting while sleep doesn’t release lock while waiting.
Difference between yield and sleep in java
Major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee that current thread will pause or stop but it guarantee that CPU will be relinquish by current Thread as a result of call to Thread.yield() method in java.
Sleep method in Java has two variants one which takes millisecond as sleeping time while other which takes both mill and nano second for sleeping duration.
sleep(long millis)
or
sleep(long millis,int nanos)
Cause the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.
10 points about Thread sleep() method in Java
I have listed down some important and worth to remember points about Sleep() method of Thread Class in Java:
1) Thread.sleep() method is used to pause the execution, relinquish the CPU and return it to thread scheduler.
2) Thread.sleep() method is a static method and always puts current thread on sleep.
3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as duration for sleep and other method with two arguments one is millisecond and other is nanosecond.
4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.
5) sleep() method throws Interrupted Exception if another thread interrupt a sleeping thread in java.
6) With sleep() in Java its not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.
7) There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put current thread into Sleeping state and not thread "t".
That’s all on Sleep method in Java. We have seen difference between sleep and wait along with sleep and yield in Java. In Summary just keep in mind that both sleep() and yield() operate on current thread.
Ques 58. Difference between Vector and ArrayList in Java
1) Vector and ArrayList are index based and backed up by an array internally.
2) Both ArrayList and Vector maintains the insertion order of element. Means you can assume that you will get the object in the order you have inserted if you iterate over ArrayList or Vector.
3) Both iterator and ListIterator returned by ArrayList and Vector are fail-fast.
Key Differences between Vector and ArrayList in Java
1) First and foremost difference is Vector is synchronized and ArrayList is not, what it means is that all the method which structurally modifies Vector e.g. add () or remove () are synchronized which makes it thread-safe and allows it to be used safely in a multi-threaded environment. On the other hand ArrayList methods are not synchronized thus not suitable for use in multi-threaded environment.
2) ArrayList is faster than Vector. Since Vector is synchronized it pays price of synchronization which makes it little slow. On the other hand ArrayList is not synchronized and fast which makes it obvious choice in a single-threaded access environment. You can also use ArrayList in a multi-threaded environment if multiple threads are only reading values from ArrayList.
3) Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of arrayList by calling ensureCapacity () method.
4) Vector can return enumeration of items it hold by calling elements () method which is not fail-fast as opposed to iterator and ListIterator returned by ArrayList.
5) Another point worth to remember is Vector is one of those classes which comes with JDK 1.0 and initially not part of Collection framework but in later version it's been re-factored to implement List interface so that it could become part of collection framework
Conclusion is use ArrayList wherever possible and avoids use of Vector until you have no choice.
Ques 59. Difference between wait, notify and notifyAll in Core Java.
Ques 60. What is Checked Exception and its use in java?
- IOException
- SQLException
- DataAccessException
- ClassNotFoundException
- InvocationTargetException
Ques 61. What is Unchecked Exception in java?
Ques 62. What is Anonymous (inner) Class in java?
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // do something. } });
Most helpful rated by users:
- How could Java classes direct program messages to the system console, but error messages, say to a file?
- What are the differences between an interface and an abstract class?
- Why would you use a synchronized block vs. synchronized method?
- How can you force garbage collection?
- What are the differences between the methods sleep() and wait()?