Loading, please wait...

A to Z Full Forms and Acronyms

Java Interview Questions And Answers: Part-4

Java, Java Interview Questions And Answers, java interview questions and answers for freshers and experienced.

 

For More Java Interview Questions: Part-3  Click here.

 

151. Is String a keyword in java?

No. String is not a keyword in java. String is a final class in java.lang package which is used to represent the set of characters in java.

 

152. Is String a primitive type or derived type?

String is a derived type.

 

153. In how many ways you can create string objects in java?

There are two ways to create string objects in java. One is using new operator and another one is using string literals.

NOTE: - The objects created using new operator are stored in the heap memory and objects created using string literals are stored in string constant pool.

String s1 = new String ("abc");    //Creating string object using new operator
String s2 = "abc";        //Creating string object using string literal

 

154. What is string constant pool?

String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content.

Whenever you create a string object using string literal, JVM first checks the content of the object to be created. If there exist an object in the string constant pool with the same content, then it returns the reference of that object. It doesn’t create a new object. If the content is different from the existing objects then only it creates new object.

 

155. What is special about string objects as compared to objects of other derived types?

1. You can create string objects without using new operator, i.e. using string literals. This is not possible with other derived types (except wrapper classes).

2. You can concatenate two string objects using ‘+’. This is the relaxation java gives to string objects as they will be used most of the time while coding. And also java provides string constant pool to store the string objects.

 

156. What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can’t modify them once they are created. They are final in nature.

Mutable objects are modifiable, you can perform modifications to them.

 

157. Which is the final class in these three classes – String, StringBuffer and StringBuilder?

All three are final.

 

158. What is the difference between String, StringBuffer and StringBuilder?

1. String objects created using java.lang.String class are immutable. Once they are created, they cannot be modified. If you try to modify them, a new string object will be created with modified content. This property of String class may cause some memory issues for applications which need frequent modification of string objects. To overcome this behavior of String class, two more classes are introduced in Java to represent the strings. They are StringBuffer and StringBuilder. Both these classes are also members of java.langpackage same as String class and make String object as mutable.

2. As objects of String class are immutable, objects of StringBuffer and StringBuilder class are mutable. You can change the contents of StringBuffer and StringBuider objects at any time of execution. When you change the content, new objects are not created.

3. As objects of StringBuffer and StringBuilder are created using only new operator, they are stored in heap memory. Whereas objects of String class are created using both string literals and new operator, they are stored in string constant pool as well as heap memory.

4. Any immutable object in java is thread safe. Because they are unchangeable once they are created. Any type of thread can’t change the content of immutable object. This applies to objects of String class also. StringBuffer objects are thread safe. All necessary methods in StringBuffer class are synchronized so that only one thread can enter into its object at any point of time. Whereas StringBuilder objects are not thread safe.

5. Because of thread safety property of String and StringBuffer classes, they reduces the performance of multithreaded applications. Because, multiple threads can’t enter into objects of these classes simultaneously. One thread has to wait until another thread is finished with them. But, you will not find performance problems if you use StringBuilder class. Because, multiple threads can enter into objects of this class. But, remember that StringBuilder is not thread safety.

6. There will be serious performance issues when you are performing lots of string concatenation using String class. This is because, each time you perform string concatenation using string class, a new object will be created with the concatenated string. This slows down an application. But, if you use either StringBuffer or StringBuilder instead of String class, your application will perform better.

7. In StringBuffer and StringBuilder classes, equals() and hashCode() methods are not overrided. Where as in String class they are overrided.

8. toString() method is overrided in all three classes. You can also convert StringBuffer and StringBuilder objects to String type by calling toString() method on them.

 

159. Why StringBuffer and StringBuilder classes are introduced in java when there already exist String class to represent the set of characters?

The objects of String class are immutable in nature, i.e. you can’t modify them once they are created. If you try to modify them, a new object will be created with modified content. This may cause memory and performance issues if you are performing lots of string modifications in your code. To overcome these issues, StingBuffer and StringBuilder classes are introduced in java.

 

160. How many objects will be created in the following code and where they will be stored in the memory?

String s1 = "abc";
String s2 = "abc";

 

161. How do you create mutable string objects?Only one object will be created and this object will be stored in the string constant pool.

Using StringBuffer and StringBuilder classes. These classes provide mutable string objects.

 

162. Which one will you prefer among “==” and equals() method to compare two string objects?

Prefer equals() method because it compares two string objects based on their content. That provides more logical comparison of two string objects. If you use “==” operator, it checks only references of two objects are equal or not. It may not be suitable in all situations.

 

163. Which class will you recommend among String, StringBuffer and StringBuilder classes if I want mutable and thread safe objects?

StringBuffer

 

164. How do you convert given string to char array?

Using toCharArray() method.

 

165. How many objects will be created in the following code and where they will be stored?

String s1 = new String("abc");
String s2 = "abc";

 

166. Where exactly string constant pool is located in the memory?Here, two string objects will be created. Object created using new operator (s1) will be stored in the heap memory. The object created using string literal (s2) is stored in the string constant pool.

Inside the heap memory. JVM reserves some part of the heap memory to store string objects created using string literals.

 

167. If there is lots of string concatenation and string modification in code. Which class among string, StringBuffer and StringBuilder improves the performance of my code. Remember, also want thread safe code?

StringBuffer class gives better performance in this scenario. As String class is immutable, if you use this class, a new object will be created after every string concatenation or string modification. This will lower the performance of the code. You can use StringBuilder also, but it is not thread safe. So, StringBuffer will be optimal choice here.

 

168. What is String intern?

String object in the string constant pool is called as String Intern. You can create an exact copy of heap memory string object in string constant pool. This process of creating an exact copy of heap memory string object in the string constant pool is called interning. intern() method is used for interning.

 

169. What is the main difference between Java strings and C, C++ strings?

In C and C++, strings are terminated with null character. But in java, strings are not terminated with null character. Strings are treated as objects in java.

 

170. Can we call String class methods using String literals?

Yes, we can call String class methods using string literals. For e.g. "abc".charAt(0);

 

171. Why strings have been made immutable in java?

1. Immutable strings increase security. As they can’t be modified once they are created, so we can use them to store sensitive data like username, password etc.

2. Immutable strings are thread safe. So, we can use them in a multi-threaded code without synchronization.

3. String objects are used in class loading. If strings are mutable, it is possible that wrong class is being loaded as mutable objects are modifiable.

 

172. What is string constant pool? Why they have provided this pool as we can store string objects in the heap memory itself?

String constant pool increases the reusability of existing string objects. When you are creating a string object using string literal, JVM first checks string constant pool. If that object is available, it returns reference of that object rather creating a new object. This will also speed up your application as only reference is returned and also saves the memory as no two objects with same content are created.

 

173. What is the similarity and difference between String and StringBuffer class?

The main similarity between String and StringBuffer class is that both are thread safe. The main difference between them is that String objects are immutable whereas StringBuffer objects are mutable.

 

174. What is the similarity and difference between StringBuffer and StringBuilder class?

The main similarity between StringBuffer and StringBuilder class is that both produces mutable string objects. The main difference between them is that StringBuffer class is thread safe whereas StringBuilder class is not thread safe.

 

175. Differences between wait () and sleep ()?

wait() and sleep() methods in java, are used to pause the execution of a particular thread in a multi-threaded environment. Whenever a thread calls wait() method, it releases the lock or monitor it holds and whenever a thread calls sleep() method, it doesn’t release the lock or monitor it holds.

wait()

sleep()

The thread which calls wait() method releases the lock it holds.

The thread which calls sleep() method doesn’t release the lock it holds.

The thread regains the lock after other threads call either notify() or notifyAll() methods on the same lock.

No question of regaining the lock as thread doesn’t release the lock.

wait() method must be called within the synchronized block.

sleep() method can be called within or outside the synchronized block.

wait() method is a member of java.lang.Object class.

sleep() method is a member of java.lang.Thread class.

wait() method is always called on objects.

sleep() method is always called on threads.

wait() is a non-static method of Object class.

sleep() is a static method of Thread class.

Waiting threads can be woken up by other threads by calling notify() or notifyAll() methods.

Sleeping threads cannot be woken up by other threads. If done so, thread will throw InterruptedException.

 To call wait() method, thread must have object lock.

 To call sleep() method, thread need not to have object lock.

 

176. What is the difference between Collection and Collections?

Collection Interface:

Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this interface. JDK doesn’t provide any direct implementations of this interface. But, it provides direct implementations of its sub interfaces. ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface. Collection interface is a member of java.util package.

Collections Class:

Collections is a utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. For example, it has the method to find the maximum element in a collection, it has the method to sort the collection, and it has the method to search for a particular element in a collection.

 

177. Difference between Shallow Copy vs. Deep Copy?

What Is Cloning?

Cloning is a process of creating an exact copy of an existing object in the memory. In java, clone() method of java.lang.Object class is used for cloning process. This method creates an exact copy of an object on which it is called through field-by-field assignment and returns the reference of that object. Not all the objects in java are eligible for cloning process. The objects which implement Cloneable interface are only eligible for cloning process. Cloneable interface is a marker interface which is used to provide the marker to cloning process

Both shallow copy and deep copy are related to this cloning process. The default version of clone() method creates the shallow copy of an object. To create the deep copy of an object, you have to override the clone() method. 

Shallow Copy

Deep Copy

Cloned Object and original object are not 100% disjoint.

Cloned Object and original object are 100% disjoint.

Any changes made to cloned object will be reflected in original object or vice versa.

Any changes made to cloned object will not be reflected in original object or vice versa.

Default version of clone method creates the shallow copy of an object.

To create the deep copy of an object, you have to override clone method.

Shallow copy is preferred if an object has only primitive fields.

Deep copy is preferred if an object has references to other objects as fields.

Shallow copy is fast and also less expensive.

Deep copy is slow and very expensive.

 

178. Difference between Program vs. Process vs. Threads

Program: - Program is an executable file containing the set of instructions written to perform a specific job on your computer. For example, Notepad.exe is an executable file containing the set of instructions which help us to edit and print the text files.

Programs are not stored on the primary memory in your computer. They are stored on a disk or a secondary memory on your computer. They are read into the primary memory and executed by the kernel. A program is sometimes referred as passive entity as it resides on a secondary memory.

Process:- Process is an executing instance of a program. For example, when you double click on a notepad icon on your computer, a process is started that will run the notepad program.

A process is sometimes referred as active entity as it resides on the primary memory and leaves the memory if the system is rebooted. Several processes may related to same program. For example, you can run multiple instances of a notepad program. Each instance is referred as a process.

Thread: - Thread is the smallest executable unit of a process. For example, when you run a notepad program, operating system creates a process and starts the execution of main thread of that process.

A process can have multiple threads. Each thread will have their own task and own path of execution in a process. For example, in a notepad program, one thread will be taking user inputs and another thread will be printing a document.

All threads of the same process share memory of that process. As threads of the same process share the same memory, communication between the threads is fast.

Process

Thread

Processes are heavy weight operations.

Threads are light weight operations.

Every process has its own memory space.

Threads use the memory of the process they belong to.

Inter process communication is slow as processes have different memory address.

Inter thread communication is fast as threads of the same process share the same memory address of the process they belong to.

Context switching between the processes is more expensive.

Context switching between threads of the same process is less expensive.

Processes don’t share the memory with other processes.

Threads share the memory with other threads of the same process.

 

179. Difference between User Thread vs. Daemon Thread?

User Threads

Daemon Threads

JVM waits for user threads to finish their work. It will not exit until all user threads finish their work.

JVM will not wait for daemon threads to finish their work. It will exit as soon as all user threads finish their work.

User threads are foreground threads.

Daemon threads are background threads.

User threads are high priority threads.

Daemon threads are low priority threads.

User threads are created by the application.

Daemon threads, in most of time, are created by the JVM.

User threads are mainly designed to do some specific task.

Daemon threads are designed to support the user threads.

JVM will not force the user threads to terminate. It will wait for user threads to terminate themselves.

JVM will force the daemon threads to terminate if all user threads have finished their work.

 

180. Difference between Statement vs. PreparedStatement vs. CallableStatement?

Statement

PreparedStatement

CallableStatement

It is used to execute normal SQL queries.

It is used to execute parameterized or dynamic SQL queries.

It is used to call the stored procedures.

It is preferred when a particular SQL query is to be executed only once.

It is preferred when a particular query is to be executed multiple times.

It is preferred when the stored procedures are to be executed.

You cannot pass the parameters to SQL query using this interface.

You can pass the parameters to SQL query at run time using this interface.

You can pass 3 types of parameters using this interface. They are – IN, OUT and IN OUT.

This interface is mainly used for DDL statements like CREATE, ALTER, DROP etc.

It is used for any kind of SQL queries which are to be executed multiple times.

It is used to execute stored procedures and functions.

The performance of this interface is very low.

The performance of this interface is better than the Statement interface (when used for multiple execution of same query).

The performance of this interface is high.

 

181. Which is better use Thread class or Runnable interface?

Implements Runnable

Extends Thread

You can extend any other class.

You can’t extend any other class.

No overhead of additional methods.

Overhead of additional methods from Thread class.

Separates the task from the runner.

Doesn’t separate the task from the runner.

Best object oriented programming practice.

Not a good object oriented programming practice.

Loosely coupled.

Tightly coupled.

Improves the reusability of the code.

Doesn’t improve the reusability of the code.

More generalized task.

Thread specific task.

Maintenance of the code will be easy.

Maintenance of the code will be time consuming.

 

182. Fail Fast vs. Fail Safe Iterator?

Fail-Fast Iterators

Fail-Safe Iterators

Fail-Fast iterators doesn’t allow modifications of a collection while iterating over it.

Fail-Safe iterators allow modifications of a collection while iterating over it.

These iterators throw ConcurrentModificationException if a collection is modified while iterating over it.

These iterators don’t throw any exceptions if a collection is modified while iterating over it.

They use original collection to traverse over the elements of the collection.

They use copy of the original collection to traverse over the elements of the collection.

These iterators don’t require extra memory.

These iterators require extra memory to clone the collection.

Ex: Iterators returned by ArrayList, Vector, HashMap.

Ex: Iterator returned by ConcurrentHashMap.

 

183. Difference between Blocked vs. Waiting states of Thread?

WAITING

BLOCKED

The thread will be in this state when it calls wait() or join() method. The thread will remain in WAITING state until any other thread calls notify() or notifyAll().

The thread will be in this state when it is notified by other thread but has not got the object lock yet.

The WAITING thread is waiting for notification from other threads.

The BLOCKED thread is waiting for other thread to release the lock.

The WAITING thread can be interrupted.

The BLOCKED thread can’t be interrupted.

 

184. Difference between Class Variables and Instance Variables? 

Class Variables

Instance Variables

Class variables are declared with keyword static.

Instance variables are declared without static keyword.

Class variables are common to all instances of a class. These variables are shared between the objects of a class.

Instance variables are not shared between the objects of a class. Each instance will have their own copy of instance variables.

As class variables are common to all objects of a class, changes made to these variables through one object will reflect in another.

As each object will have its own copy of instance variables, changes made to these variables through one object will not reflect in another object.

Class variables can be accessed using either class name or object reference.

Instance variables can be accessed only through object reference.

 

 

185. What is the difference between start() and run() method of Thread class?

start() method is used to start newly created thread, while start() internally calls run() method, there is difference calling run() method directly. When you invoke run() as normal method, it’s called in the same thread, no new thread is started, which is the case when you call start() method.

 

186. What is the difference between Runnable and Callable in Java?

Both Runnable and Callable represent task which is intended to be executed in a separate thread. Runnable is there from JDK 1.0 while Callable was added on JDK 1.5. Main difference between these two is that Callable'scall()method can return value and throw Exception, which was not possible with Runnable's run() method. Callable return Future object, which can hold the result of computation.

 

187. What is volatile in Java? 

volatile is a non-access modifier, which can only be used with instance variables. In concurrent Java programs, changes made by multiple threads on instance variables is not visible to other in absence of any synchronizers e.g. synchronized keyword or locks. Volatile variable guarantees that a write will happen before any subsequent read: as stated:"volatile variable rule".

 

188. What happens when an Exception occurs in a thread?

If Exception occurs in a thread and not caught thread will die, if an uncaught exception handler is registered then it will get a call back. Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException() method, passing the thread and the exception as arguments.

 

189. How do you share data between two thread in Java?

You can share data between threads by using shared object, or concurrent data structure like BlockingQueue.

 

190. What is the difference between notify() and notifyAll() in Java?

Since multiple threads can wait on single monitor lock, Java API designer provides method to inform only one of them or all of them, once waiting condition changes, but they provide half implementation. There notify()method doesn't provide any way to choose a particular thread, that's why it’s only useful when you know that there is only one thread is waiting. On the other hand, notifyAll() sends notification to all threads and allows them to compete for locks, which ensures that at-least one thread will proceed further.

 

191. Why wait(), notify() and notifyAll() are not inside thread class?

Java provides lock at object level not at thread level. Every object has lock, which is acquired by thread. Now if thread needs to wait for certain lock it make sense to call wait() on that object rather than on that thread. Had wait() method declared on Thread class, it was not clear that for which lock thread was waiting. In short, since wait, notify and notifyAll operate at lock level, it make sense to define it on object class because lock belongs to object.

 

192. What is FutureTask in Java?

FutureTask is in java.util.concurrent package and it represents a cancellable asynchronous computation in concurrent Java application. This class provides a base implementation of java.util.concurrent.Future interface, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. AFutureTask object can be used to wrap an interface java.util.concurrent.Callable or interface java.lang.Runnable object. Since FutureTask also implements Runnable, it can be submitted to an Executor for execution.

 

193. What is Busy Spinning? Why will you use Busy Spinning as wait strategy?

The busy waiting is a wait strategy, where one thread wait for a condition to become true, but instead of calling wait or sleep method and releasing CPU, it just spins. This is particularly useful if the condition is going to be true quite quickly i.e. in a millisecond or microsecond.

The advantage of not releasing CPU is that all cached data and instruction remain unaffected, which may be lost, had this thread is suspended on one core and brought back to another thread.

 

194. What is the difference between execute() method of Executor and submit() method of ExecutorService interface in Java?

Both methods are ways to submit a task to thread pools but there is a slight difference between them. execute(Runnable command) is defined in Executor interface and executes given task in future, but more importantly, it does not return anything. Its return type is void. On other hand submit() is an overloaded method, it can take either Runnable or Callable task and can return Future object which can hold the pending result of computation. This method is defined on ExecutorService interface, which extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods.

 

195. What is the difference between synchronized and ReentrantLock in Java?

Mutual exclusion in Java is achieved by synchronized keyword, but it has some limitations e.g. you cannot extend lock beyond a method or block boundary, you cannot give up trying for a lock etc. Java 5 solves this problem by providing more sophisticated control via Lock interface. Reentrant Lock is a common implementation of Lock interface and provides re-entrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities. Reentrant lock is tryLock() method. ReentrantLock provides convenient tryLock() method, which acquires lock only if its available or not held by any other thread. This reduce blocking of thread waiting for lock in Java application.

 

196. What is thread starvation?

In a multi-threaded environment thread starvation occurs if a low priority thread is not able to run or get a lock on the resource because of presence of many high priority threads. This is mainly possible by setting thread priorities inappropriately.

 

197. What is threadLocal variable?

ThreadLocal is a class. If a variable is declared as threadLocal then each thread will have its own copy of variable and would not interfere with the other's thread copy. Typical scenario to use this would be giving JDBC connection to each thread so that there is no conflict.

 

198. Is it possible to start a thread twice?

No, after having started a thread by invoking its start() method, a second invocation of start() will throw an IllegalThreadStateException.

 

199. Can the start() method of the Thread class be overridden? If yes should it be overridden?

Yes the start() method can be overridden. But it should not be overridden as its implementation in thread class has the code to create a new executable thread and is specialized.

 

200. Can two threads call two different static synchronized methods of the same class?

No. The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time.

 

 

 

A to Z Full Forms and Acronyms

Related Article