Core Java Interview Questions and Answers
Experienced / Expert level questions & answers
Ques 1. What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.
Ques 2. How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable.
Example:
int a=5,b=10;a=a+b; b=a-b; a=a-b;
Ques 3. Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.
Ques 4. Why String is immutable or final in Java?
1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as stirng , you can pass database URL as string for opening database connection, you can open any file by passing name of file as argument to File I/O classes.
In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file.
3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java.
4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below.
5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.
Ques 5. In Java, you can create a String object as below : String str = "abc"; & String str = new String("abc"); Why cant a button object be created as : Button bt = "abc"? Why is it compulsory to create a button object as: Button bt = new Button("abc"); Why this is not compulsory in String's case?
Button bt1= "abc"; It is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. That simple. The only object in Java that can be assigned a literal String is java.lang.String. Important to not that you are NOT calling a java.lang.String constuctor when you type String s = "abc";
For example String x = "abc"; String y = "abc"; refer to the same object. While String x1 = new String("abc");
String x2 = new String("abc"); refer to two different objects.
Ques 6. Can you call one constructor from another if a class has multiple constructors?
Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; }
Ques 7. What are some alternatives to inheritance?
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
Ques 8. When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.
Ques 9. What is the algorithm used in Thread scheduling?
Fixed priority scheduling.
Ques 10. What are the threads will start, when you start the java program?
Finalizer/DestroyJavaVM, Main, Reference Handler, Signal Dispatcher
Ques 11. What are the approaches that you will follow for making a program very efficient?
By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
Ques 12. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
Ques 13. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
Ques 14. What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.
Ques 15. Can an inner class declared inside of a method access local variables of this method?
It is possible if these variables are final.
Ques 16. When you think about optimization, what is the best way to findout the time/memory consuming process?
Using profiler
Ques 17. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
String hostname = InetAddress.getByName("192.18.97.39").getHostName();
Ques 18. What is the advantage of the event-delegation model over the earlier event-inheritance model?
The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.
Ques 19. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why?
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
Ques 20. What is reflection API? How are they implemented?
What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.
Ques 21. When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.
Ques 22. What is reason of NoClassDefFoundError in Java?
NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time. for example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError. It’s important to understand that this is different than ClassNotFoundException which comes while trying to load a class at run-time only and name was provided during runtime not on compile time. Most of the java developer mingle this two Error and gets confused.
Ques 23. How to resolve NoClassDefFoundError?
Obvious reason of NoClassDefFoundError is that a particular class is not available in Classpath, so we need to add that into Classpath or we need to check why it’s not available in Classpath if we are expecting it to be. There could be multiple reasons like:
1) Class is not available in Java Classpath.
2) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
3) Any startup script is overriding Classpath environment variable.
Ques 24. Difference between ClassNotFoundException and NoClassDefFoundError in Java?
Many a times we confused ourselves with ClassNotFoundException and NoClassDefFoundError, though both of them related to Java Classpath they are completely different to each other. ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws ClassNotFoundException. While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason. NoClassDefFoundError is easier to solve than ClassNotFoundException in my opinion because here we know that Class was present during build time.
Let me know how exactly you are facing NoClassDefFoundError and I will guide you how to troubleshoot it, if you are facing with something new way than I listed above we will probably document if for benefit of others and again don’t afraid with Exception in thread "main" java.lang.NoClassDefFoundError
Ques 25. What is java.lang.OutOfMemoryError in Java?
OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when it ran out of memory in heap. OutOfMemoryError in Java can come any time in heap mostly while you try to create an object and there is not enough space in heap to allocate that object. javavdoc of OutOfMemoryError is not very informative about this though.
Ques 26. Types of OutOfMemoryError in Java.
I have seen mainly two types of OutOfMemoryError in Java:
1) Java.lang.OutOfMemoryError: Java heap space
2) Java.lang.OutOfMemoryError: PermGen space
Though both of them occur because JVM ran out of memory they are quite different to each other and there solutions are independent to each other.
Ques 27. Difference between "java.lang.OutOfMemoryError: Java heap space" and "java.lang.OutOfMemoryError: PermGen space"
If you are familiar with different generations on heap and How garbage collection works in java and aware of new, old and permanent generation of heap space then you would have easily figured out this OutOfMemoryError in Java. Permanent generation of heap is used to store String pool and various Meta data required by JVM related to Class, method and other java primitives. Since in most of JVM default size of Perm Space is around "64MB" you can easily ran out of memory if you have too many classes or huge number of Strings in your project. Important point to remember is that it doesn't depends on –Xmx value so no matter how big your total heap size you can ran OutOfMemory in perm space. Good think is you can specify size of permanent generation using JVM options "-XX:PermSize" and "-XX:MaxPermSize" based on your project need.
One small thing to remember is that "=" is used to separate parameter and value while specifying size of perm space in heap while "=" is not required while setting maximum heap size in java, as shown in below example.
export JVM_ARGS="-Xmx1024m -XX:MaxPermSize=256m"
Another reason of "java.lang.OutOfMemoryError: PermGen" is memory leak through Classloaders and it’s very often surfaced in WebServer and application server like tomcat, webshere, glassfish or weblogic. In Application server different classloaders are used to load different web application so that you can deploy and undeploy one application without affecting other application on same server, but while undeploying if container some how keeps reference of any class loaded by application class loader than that class and all other related class will not be garbage collected and can quickly fill the PermGen space if you deploy and undeploy your application many times. "java.lang.OutOfMemoryError: PermGen” has been observed many times in tomcat in our last project but solution of this problem are really tricky because first you need to know which class is causing memory leak and then you need to fix that. Another reason of OutOfMemoryError in PermGen space is if any thread started by application doesn't exit when you undeploy your application.
These are just some example of infamous classloader leaks, anybody who is writing code for loading and unloading classes have to be very careful to avoid this. You can also use visualgc for monitoring PermGen space, this tool will show graph of PermGen space and you can see how and when Permanent space getting increased. I suggest using this tool before reaching to any conclusion.
Another rather unknown but interesting cause of "java.lang.OutOfMemoryError: PermGen" we found is introduction of JVM options "-Xnoclassgc". This option sometime used to avoid loading and unloading of classes when there is no further live references of it just to avoid performance hit due to frequent loading and unloading, but using this option is J2EE environment can be very dangerous because many framework e.g. Struts, spring etc uses reflection to create classes and with frequent deployment and undeployment you can easily ran out of space in PermGen if earlier references was not cleaned up. This instance also points out that some time bad JVM arguments or configuration can cause OutOfMemoryError in Java.
Ques 28. How HashMap works in Java?
"How does get () method of HashMap works in Java"
And then you get answers like I don't bother its standard Java API, you better look code on java; I can find it out in Google at any time etc.
But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls
hashcode() method hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java.
But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap ->
"What will happen if two different objects have same hashcode?"
Now from here confusion starts some time interviewer will say that since Hashcode is equal objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them about equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say "Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list." great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap does follow this.
"How will you retreive if two different objects have same hashcode?"
Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retrieves object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify value object because you don't value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won't be able to resolve this issue and will try and fail.
But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer.
In many cases interviewee fails at this stage because they get confused between hashcode () and equals () and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap.
Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.
Now if you clear all this java hashmap interview question you will be surprised by this very interesting question "What happens On HashMap in Java if the size of the Hashmap exceeds a given threshold defined by load factor ?". Until you know how hashmap works exactly you won't be able to answer this question.
if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location.
If you manage to answer this question on hashmap in java you will be greeted by "do you see any problem with resizing of hashmap in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java.
So the answer is Yes there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java hashmap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. if race condition happens then you will end up with an infinite loop. though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer.
Ques 29. What is the difference between Synchronized Collection classes and Concurrent Collection Classes ? When to use what ?
The synchronized collections classes, Hashtable and Vector, and the synchronized wrapper classes, Collections.synchronizedMap and Collections.synchronizedList, provide a basic conditionally thread-safe implementation of Map and List.
However, several factors make them unsuitable for use in highly concurrent applications -- their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationExceptions.
The ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher concurrency while preserving thread safety, with some minor compromises in their promises to callers. ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList, but are designed to optimize specific common situations. Many concurrent applications will benefit from their use.
So what is the difference between hashtable and ConcurrentHashMap , both can be used in multithreaded environment but once the size of hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.
Since ConcurrentHashMap indroduced concept of segmentation , how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.
In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.
Ques 30. How to use Comparator and Comparable in Java? With example.
Comparators and comparable in Java are two of fundamental interface of Java API which is very important to understand to implement sorting in Java. It’s often required to sort objects stored in any collection class or in Array and that time we need to use compare () and compare To () method defined in java.util.Comparator and java.lang.Comparable class. Let’s see some important points about both Comparable and Comparator in Java before moving ahead
Difference between Comparator and Comparable in Java
1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.
2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.
4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.
5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.
6)Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.
Ques 31. What is dead lock in thread?
A special type of error that you need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects.
For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete.
Ques 32. What is thread pool in java?
A thread pool is a group of threads initially created that waits for jobs and executes them. The idea is to have the threads always existing, so that we won't have to pay overhead time for creating them every time. They are appropriate when we know there's a stream of jobs to process, even though there could be some time when there are no jobs.
Ques 33. What is concurrency in java?
Concurrency is the ability to run several programs or several parts of a program in parallel. If a time consuming task can be performed asynchronously or in parallel, this improve the throughput and the interactivity of the program.
A modern computer has several CPU's or several cores within one CPU. The ability to leverage these multi-cores can be the key for a successful high-volume application.
Concurrency Issues:
Threads have their own call stack, but can also access shared data. Therefore you have two basic problems, visibility and access problems.
A visibility problem occurs if thread A reads shared data which is later changed by thread B and thread A is unaware of this change.
An access problem can occur if several thread access and change the same shared data at the same time.
Visibility and access problem can lead to
Liveness failure: The program does not react anymore due to problems in the concurrent access of data, e.g. deadlocks.
Safety failure: The program creates incorrect data.
Ques 34. What is Dictionary Class in Java?
Dictionary is an abstract class that represents a key/value storage repository and operates much like Map.
Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value pairs.
The Dictionary class is obsolete. You should implement the Map interface to obtain key/value storage functionality.
Ques 35. What is Reference Handler Thread in Java?
- I suspect it handles running finalizers for the JVM. It's an implementation detail and as such not specified in the JVM spec.
- This only means that the java.lang.ref.Reference$Lock was locked in the method mentioned in the line preceding it (i.e in ReferenceHandler.run().
- "Native Method" simply means that the method is implemented in native (i.e. non-Java) code (think JNI).
- Unknown Source only means that the .class file doesn't contain any source code location information (at least for this specific point). This can happen either when the method is a synthetic one (doesn't look like it here), or the class was compiled without debug information.
- When a thread waits on some object, then it must have locked that object at some point down the call trace, so you can't really have a waiting on without a corresponding locked.
Ques 36. What is Main thread in Java?
3191 // Attach the main thread to this os thread 3192 JavaThread* main_thread = new JavaThread(); 3193 main_thread->set_thread_state(_thread_in_vm); 3194 // must do this before set_active_handles and initialize_thread_local_storage 3195 // Note: on solaris initialize_thread_local_storage() will (indirectly) 3196 // change the stack size recorded here to one based on the java thread 3197 // stacksize. This adjusted size is what is used to figure the placement 3198 // of the guard pages. 3199 main_thread->record_stack_base_and_size(); 3200 main_thread->initialize_thread_local_storage();
3335 // Initialize java_lang.System (needed before creating the thread) 3336 if (InitializeJavaLangSystem) { 3337 initialize_class(vmSymbols::java_lang_System(), CHECK_0); 3338 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0); 3339 Handle thread_group = create_initial_thread_group(CHECK_0); 3340 Universe::set_main_thread_group(thread_group()); 3341 initialize_class(vmSymbols::java_lang_Thread(), CHECK_0); 3342 oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0); 3343 main_thread->set_threadObj(thread_object); 3344 // Set thread status to running since main thread has 3345 // been started and running. 3346 java_lang_Thread::set_thread_status(thread_object, 3347 java_lang_Thread::RUNNABLE);
967 // Creates the initial Thread 968 static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) { 969 klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_ NULL); 970 instanceKlassHandle klass (THREAD, k); 971 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL); 972 973 java_lang_Thread::set_thread(thread_oop(), thread); 974 java_lang_Thread::set_priority(thread_oop(), NormPriority); 975 thread->set_threadObj(thread_oop()); 976 977 Handle string = java_lang_String::create_from_str("main", CHECK_NULL); 978 979 JavaValue result(T_VOID); 980 JavaCalls::call_special(&result, thread_oop, 981 klass, 982 vmSymbols::object_initializer_name(), 983 vmSymbols::threadgroup_string_void_signature(), 984 thread_group, 985 string, 986 CHECK_NULL); 987 return thread_oop(); 988 }
Ques 37. What is Signal Dispatcher thread in Java?
Signal Dispatcher is a thread that handles the native signals sent by the OS to your JVM.
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()?