Monday, March 27, 2023

Top 40 Core Java Interview Questions Answers from Telephonic Round [UPDATED]

Hello guys, here is another post about preparing for Java Interviews, this time we will take a look at 40 core Java questions from the telephonic round of Java Programming interviews. Phone interviews are usually the first step to screen a candidate after selecting his resume. Since it's easy to call a candidate than to schedule a face-to-face interview, book rooms, and arrange for a meeting, a telephonic round of interviews is quite popular nowadays. There were days only one telephonic round of interviews was enough but nowadays, it's almost two and three rounds of phone interviews with different team members before you get a chance for face-to-face interviews. 

The key to success in a telephonic interview is to the point and concise answer. Since the Interviewer wants to cover a lot of things on a telephonic round, they appreciate the point answer instead of blah blah and dragging the answer for sake of time. 

Always remember, it's your time to make an impression also so make sure you have a good phone, are fully charged, and use voice modulation technique to be as clear as possible. Even if you don't know the answer, think aloud, the interviewer appreciates the ability to think, and sometimes that proves to be decisive as well.

By the way, a good knowledge of Java Programming language goes a long way in doing well on Java interviews. If you struggle to answer any of these questions then I suggest you join a comprehensive Java course like The Complete Java Masterclass by Tim Buchalaka on Udemy. This 80-hour long course is the most comprehensive and up-to-date course to learn Java and you can get it for just $10 on Udemy. 




40 Core Java Interview Questions with Answers

Here is my list of 40 core Java-based questions which frequently appear on a telephonic round of Interviews. These questions touch-based on important core java concepts like String, Thread basics, multi-threading, inter-thread communication, Java Collection framework, Serialization, Object-oriented programming concepts, and Exception handling. 

If you have faced a couple of Java interviews, you will surely have seen some of these questions already. I have provided just enough answers for the sake of a telephonic interview, but if you want to know more, you can always check the detailed answer link.



1) Difference between String, StringBuffer, and StringBuilder in Java? (detailed answer)
String is immutable while both StringBuffer and StringBuilder are mutable, which means any change e.g. converting String to upper case or trimming white space will produce another instance rather than changing the same instance. In later two, StringBuffer is synchronized while StringBuilder is not, in fact, it's a ditto replacement of StringBuffer added in Java 1.5.


2) Difference between extending Thread vs implementing Runnable in Java? (detailed answer)
The difference comes from the fact that you can only extend one class in Java, which means if you extend the Thread class you lose your opportunity to extend another class, on the other hand, if you implement Runnable, you can still extend another class.


3) Difference between Runnable and Callable interface in Java? (detailed answer)
Runnable was the only way to implement a task in Java that can be executed in parallel before JDK 1.5 adds Callable. Just like Runnable, Callable also defines a single call() method but unlike run() it can return values and throw exceptions.

If you want to learn more about multithreading and concurrency in Java, I highly recommend you to check out Java Multithreading, Concurrency & Performance Optimization course by Michael Pogrebinsky on Udemy. 

Top 40 Core Java Interview Questions Answers from Telephonic Round [UPDATED]





4) Difference between ArrayList and LinkedList in Java? (detailed answer)
In short, ArrayList is backed by an array in Java, while LinkedList is just a collection of nodes, similar to a linked list data structure. ArrayList also provides a random search if you know the index, while LinkedList only allows a sequential search. On other hand, adding and removing an element from the middle is efficient in LinkedList as compared to ArrayList because it only requires modifying links, and no other element is rearranged.


5) What is the difference between wait and notify in Java? (detailed answer)
Both wait and notify methods are used for inter-thread communication, where the wait is used to pause the thread on a condition, and notify is used to send a notification to waiting threads. Both must be called from synchronized context e.g. synchronized method or block.


6) Difference between HashMap and Hashtable in Java? (detailed answer)
Though both HashMap and Hashtable are based upon hash table data structure, there are subtle differences between them. HashMap is non-synchronized while Hashtable is synchronized and because of that HashMap is faster than Hashtable, as there is no cost of synchronization associated with it. One more minor difference is that HashMap allows a null key but Hashtable doesn't.




7) Difference between TreeSet and TreeMap in Java? (detailed answer)
Though both are sorted collections, TreeSet is essentially a Set data structure that doesn't allow duplicate, and TreeMap is an implementation of Map interface. In reality, TreeSet is implemented via a TreeMap, much like how HashSet is implemented using HashMap.


8) Write a Java program to print the Fibonacci series? (solution)
Fibonacci series is a series of number on which a number is equal to sum of previous two numbers i.e. f(n) = f(n-1) + f(n-2). This program is used to teach recursion to students but you can also solve it without recursion.  

You can check out the solution for both iterative and recursive solutions to this problem. In a telephonic interview, this question is not that common but sometimes the interviewer also wants to check your problem-solving skill using such questions. 

And, if you want to improve your problem-solving skills for coding questions, I highly recommend you to checkout Grokking the Coding Interview: Patterns for Coding Questions course from Educative, an interactive learning platform that allows you to practice on a browser.  This course will teach 15 essential coding patterns like sliding window, merge interval, two pointers, etc which can be used to solved 100+ Leetcode problems and help you in real coding interviews. 

Java interview questions for 2 to 4 years experienced programmers




9) Write a Java program to check if a number is Prime or not? (solution)
A number is said prime if it is not divisible by any other number except itself. 1 is not considered prime, so your check must start with 2. The simplest solution of this is to check every number until the number itself to see if it's divisible or not. 

When the Interviewer will ask you to improve, you can say that check until the square root of the number. If you can further improve the algorithm, you will more impress your interviewer. check out the solution for how to do this in Java


10) How to Swap two numbers without using the temp variable? (solution)
This question is ages old. I have first seen this question way back in 2005 but I am sure it's even older than that. The good thing about this problem is that except XOR trick all solution has some flaws, which is used to test whether the candidate really knows his stuff or not. Check out the solution for all three possible solutions and drawbacks of each.


11) How to check if the linked list contains a loop in Java? (solution)
This is another problem-solving question which is very popular in telephonic and screening rounds. This is a great question to test the problem-solving skills of the candidate, especially if he has not seen this question before. It also has a nice little follow-up to find the starting of the loop. See the solution for a Java program that finds loops in singly linked.


12) Write a Java program to reverse String without using API? (solution)
One more question to test the problem-solving skill of the candidate. You wouldn't expect these kinds of questions in the telephonic round of Java interviews but these questions have now become norms. All interviewer is looking it for logic, you don't need to write the code but you should be able to think of a solution.


13) Difference between Serializable and Externalizable in Java? (detailed answer)
Serializable is a marker interface with no methods defined it but Externalizable interface has two methods defined on it e.g. readExternal() and writeExternal() which allows you to control the serialization process. Serializable uses a default serialization process which can be very slow for some applications.



14) Difference between transient and volatile in Java? (detailed answer)
the transient keyword is used in Serialization while volatile is used in multi-threading. If you want to exclude a variable from the serialization process then mark that variable transient. Similar to the static variable, transient variables are not serialized. 

On the other hand, volatile variables are signal to the compiler that multiple threads are interested in this variable and it shouldn't reorder its access. the volatile variable also follows the happens-before relationship, which means any write happens before any read in a volatile variable. You can also make non-atomic access of double and long variable atomic using volatile.


15) Difference between abstract class and interface? (detailed answer)
From Java 8 onwards difference between abstract class and interface in Java has been minimized, now even the interface can have an implementation in terms of default and static method. BTW, in Java, you can still extend just one class but can extend multiple inheritances. An abstract class is used to provide default implementation with just something left to customize, while an interface is used heavily in API to define the contract of a class.


16) Difference between Association, Composition, and Aggregation? (detailed answer)
Between association, composition, and aggregation, the composition is strongest. If the part can exist without a whole then the relationship between two classes is known as aggregation but if the part cannot exist without a whole then the relationship between two classes is known as composition. Between Inheritance and composition, later provides a more flexible design.


17) What is the difference between FileInputStream and FileReader in Java? (detailed answer)
The main difference between FileInputStream and FileReader is that the former is used to read binary data while the latter is used to read text data, which means later also consider character encoding while converting bytes to text in Java.

Core Java Interview Questions answers from telephonic Interview



18) How do you convert bytes to characters in Java? (detailed answer)
Bytes are converted to character or text data using character encoding. When you read binary data from a file or network endpoint, you provide a character encoding to convert those bytes to equivalent characters. Incorrect choice of character encoding may alter the meaning of the message by interpreting it differently.


19) Can we have a return statement in the finally clause? What will happen? (detailed answer)
Yes, you can use the return statement in finally block, but it will not prevent finally block from being executed. BTW, if you also used the return statement in the try block then return the value from the finally block with override whatever is returned from the try block.


20) Can you override the static method in Java? (detailed answer)
No, you cannot override static methods in Java because they are resolved at compile time rather than runtime. Though you can declare and define a static method of the same name and signature in the child class, this will hide the static method from the parent class, that's why it is also known as method hiding in Java.


21) Difference between the private, public, package, and protected in Java? (detailed answer)
All four are access modifiers in Java but only private, public, and protected are modifier keywords. There is no keyword for package access, it's the default in Java. This means if you don't specify any access modifier then by default that will be accessible inside the same package. 

Private variables are only accessible in the class they are declared, protected are accessible inside all classes in the same package but only on subclass outside package and public variables e.g. method, class or variables are accessible anywhere. This is the highest level of access modifier and provides the lowest form of encapsulation.


22) 5 Coding best practices you learned in Java? (detailed answer)
If you are developing a programming language for a couple of years, you sure know lots of best practices, by asking a couple of them, the Interviewer just checks that you know your trade well. Here are my 5 Java best practices :
- Always name your thread, this will help immensely in debugging.
- Use StringBuilder for string concatenation
- Always specify the size of the Collection, this will save a lot of time spent on resizing
- Always declare variable private and final unless you have a good reason.
- Always code on interfaces instead of implementation
- Provide dependency to method instead they get it by themselves, this will make your code unit testable.



23) Write a Program to find the maximum and minimum number in the array? (solution)
This is another coding question that test the problem-solving ability of the candidate. Be ready for a couple of follow up as well depending upon how you answer this question. The simplest way which comes to mind is to sort the array and then pick the top and bottom elements. For a better answer see the solution.


24) Write a program to reverse Array in place? (solution)
Another problem-solving question for Java programmers. The key point here is that you need to reverse the array in place, which means you cannot use an additional buffer, one or two variables will be fine. Note you cannot use any library code, you need to create your own logic.


25) Write a program to reverse a number in Java? (solution)
This is an interesting program for a very junior programmer, right from the college but can sometimes puzzle developers with a couple of years of experience as well. Most of these developer does very little coding so they found these kind of questions challenging. Here the trick is to get the last digit of the number by using the modulus operator (%) and reducing the number in each go by using the division operator (/). See the solution for how to do that in Java.


26) Write a Program to calculate factorial in Java? (solution)
Another beginner's coding problem, is good for a telephonic interview because you can differentiate a guy who can write a program from a guy who can't. It's also good to see if the developer is familiar with both recursive and iterative algorithms and the pros and cons of each. 

You can also ask lots of follow up like how to improve the performance of the algorithm? Since the factorial of a number is equal to the number multiplied by the factorial of the previous number, you can cache those values instead of recalculating them, this will impress your interviewer a bit. See the solution for a full code example.




27) What is the difference between the calling start() and run() method of Thread? (detailed answer)
You might have heard this question before, if calling the start() method calls the run() method eventually then why not just call the run() method? Well, the difference is, the start method also starts a new thread. If you call the run method directly then it will run on the same thread, not on a different thread, which is what the original intention would be.


28) Write a Program to solve the Producer-Consumer problem in Java? (solution)
A very good question to check if the candidate can write an inter-thread communication code or not. If a guy can write producer-consumer solutions by hand and point out critical sections and how to protect, how to communicate with thread then he is good enough to write and maintain your concurrent Java program. 

This is the very minimum requirement for a Java developer and that's why I love this question, it also has several solutions e.g. by using concurrent collections like blocking queue, by using wait and notify, and by using other synchronizers of Java 5 e.g. semaphores.


29) How to find the middle element of the linked list in one pass? (solution)
Another simple problem-solving question for warm-up. In a singly linked list, you can only traverse in one direction and if you don't know the size then you cannot write a loop to exactly find out the middle element, that is the crux of the problem. 

One solution is by using two pointers, fast and slow. The slower pointer moves 1 step when the faster pointer moves to 2 steps, causing slow to point to the middle when fast is pointing to the end of the list i.e. null. Check out the solution for the Java code sample. 

If you want to learn more about essential data structures like arrays and linked lists in Java then I highly recommend you to check out Data Structures and Algorithms: Deep Dive Using Java course on Udemy. It's a great course to master data structure and algorithms in Java. 

frequently asked java interview questions with answers




30) What is equals() and hashCode() contract in Java? Where does it use it? (detailed answer)
One of the must-ask questions in the Java telephonic interview. If a guy doesn't know about equals() and hashCode() then he is probably not worth pursuing further because it's the core of the Java fundamentals. 

The key point of the contract is that if two objects are equal by the equals() method then they must have the same hashcode, but unequal objects can also have the same hashcode, which is the cause of collision on the hash table based collection e.g HashMap. When you override equals() you must remember to override the hashCode() method to keep the contract valid.


31) Why wait and notify methods are declared in the Object class? (detailed answer)
This question is more to find out how much experience you really have and what is your thinking about Java API and its design decision. A similar question is why String is immutable in Java? Well, a true answer can only be given by Java designers but you can reason something. 

For example, wait and notify methods are associated with locks that are owned by the object, not thread, and that's why it makes sense to keep those methods on java.lang.Object class. See the detailed answer for more discussion and reasoning.




32) How does HashSet works in Java? (detailed answer)
HashSet is internally implemented using HashMap in Java and this is what your interviewer wants to hear. He could then quiz you with some common sense-based questions e.g. how can you use HashMap because it needs two object keys and value? what is the value in the case of HashSet? 

Well, in the case of HashSet a dummy object is used as a value and key objects are the actual element on Set point of view. Since HashMap doesn't allow duplicate keys it also follows the contract of set data structure to not allow duplicates. See detailed answers for more analysis and explanation.


33) What is the difference between synchronized and concurrent Collection in Java? (detailed answer)
There was a time, before Java 1.5 when you only have synchronized collections if you need them in a multi-threaded Java program. Those classes were plagued with several issues most importantly performance because they lock the whole collection or map whenever a thread reads or writes. To address those issues, Java released a couple of Concurrent collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, and BlockingQueue to provide more scalability and performance.


34) What is the difference between Iterator and Enumeration in Java? (detailed answer)
The main difference is that Iterator was introduced in place of Enumeration. It also allows you to remove elements from the collection while traversing which was not possible with Enumeration. 

The methods of Iterator e.g. hasNext() and next() are also more concise then corresponding methods in Enumeration e.g. hasMoreElements(). You should always use Iterator in your Java code as Enumeration may get deprecated and removed in future Java releases.


35) What is the difference between Overloading and Overriding in Java? (detailed answer)
Another frequently asked question from the telephonic round of Java interviews. Though both overloading and overriding are related with methods of the same names they have different characteristics e.g.overloaded methods must have a different method signature than the original method but the overridden method must have the same signature. Also, overloaded methods are resolved at a compiled time while overridden methods are resolved at runtime. See the detailed answer for more analysis and differences.


36) Difference between static and dynamic binding in Java? (detailed answer)
This is usually asked as a follow-up of the previous question, static binding is related to an overloaded method and dynamic binding is related to the overridden method. A method like private, final, and static are resolved using static binding at compile time but virtual methods that can be overridden are resolved using dynamic binding at runtime.



37) Difference between Comparator and Comparable in Java? (detailed answer)
This is one more basic concept, I expect every Java candidate to know. You will deal with them on every Java project. Several core classes in Java e.g. String, Integer implement Comparable to define their natural sorting order and if you define a value class or a domain object then you should also implement Comparable and define the natural ordering of your object. 

The main difference between these two is that you could create multiple Comparators to define multiple sorting orders based upon different attributes of an object. 

Also, In order to implement Comparable, you must have access to the class or code, but you can use Comparator without having the source code of a class, all you need is the JAR file of a particular object. That's why Comparator is very powerful to implement custom sorting order and from Java 8 you can do it even more elegantly, as seen here.


38) How do you sort ArrayList in descending order? (solution)
You can use Collections.sort() method with reverse Comparator, which can sort elements in the reverse order of their natural order e.g.
List<String> listOfString = Arrays.asList("London", "Tokyo", "NewYork");
Collections.sort(listOfString, Collections.reverseOrder());
System.out.println(listOfString); //[Tokyo, NewYork, London]


39) What is the difference between PATH and CLASSPATH in Java? (detailed answer)
PATH is an environment variable that points to Java binary which is used to run Java programs. CLASSPATH is another environment variable that points to Java class files or JAR files. If a class is not found in CLASSPATH then Java throws ClassNotFoundException.


40) What is the difference between Checked and Unchecked Exception in Java? (detailed answer)
Checked exception ensures that handling of the exception is provided and it's verified by compiler also, while for throwing unchecked exception no special provision is needed e.g. throws clause. A method can throw unchecked exceptions without any throw clause.


That's all about 40 Core Java Interview Questions from the telephonic round. Don't take a phone interview lightly, it's your first chance to impress your prospective employer. Given that you are not seeing your interviewer and just communicating with your voice, it's a little bit different than a face-to-face interview.

So always be calm, relaxed and answer questions to the point and precisely, speak slowly and make sure you are not in a place where your sound echoes like on a close staircase. Having a good phone, headset and being in a good reception area is also very important. 

I have seen it many times where candidates lost on the interview because not able to hear it properly or were not able to understand questions before answering them. I know some people take telephonic interviews on those secret places but if you do make sure your phone connectivity is enough.


If you like this tutorial and looking for some more interview questions for preparation checkout my amazing collection :
  • 10 Advanced Core Java Interview Questions for Programmers (see here)
  • 15 Java Enum based Interview Questions with Answers (check here)
  • 21 Frequently asked Java Questions with Answers (see here)
  • Top 10 Linux and UNIX Interview Questions for Java Programmers (check here)
  • Top 20 SQL Query Interview Questions (see list)
  • Java Interview Questions for 2 to 3 Years Experienced Programmers (see here)
  • 12 Multithreading and Concurrency Questions for Java Developers (check here)
  • 10 Tough Java Questions from Interviews (see list)
  • Top 11 Coding Questions from Java Interviews with Answers (see here)
  • 18 Java Design Pattern Questions for Senior Developers (see here)
  • 15 Tricky Questions from Java Interviews with Answers (check here)
  • 100+ Data Structure and Algorithms Interview Questions (list)
  • 75 Programming Interview Questions for Beginners (list)
  • 21 String Coding Problem from Java Interviews with Solution (list)
  • 21+ Spring MVC Interview Questions with Answers (questions)
  • 15 Spring Boot Interview Questions for Java Developers (spring boot)

Thanks for reading this article so far. If you like these core Java interview questions or have seen them on your telephonic round of interviews, then please share this post with your friends and colleagues on Facebook, Twitter, Email, etc. If you have any questions or feedback, please drop a note.

All the best for your interview.

P. S. - If you are new to the Java Programming world and looking for a free online course to learn Java then you can also check out Java Tutorial for Complete Beginners(FREE) on Udemy. It's completely free and more than 1.5 million people have joined this course.

23 comments:

  1. Very Nice set of questions and answers. Thanks for sharing!!

    ReplyDelete
    Replies
    1. @Anonymous, thanks. Glad to hear that you find these Java Interview questions helpful.

      Delete
  2. I am thinking to take this course - https://www.udemy.com/java-interview-guide/

    ReplyDelete
  3. Very nice collection of questions.. Thanks Javin Paul for publishing this!!

    ReplyDelete
  4. Thanks for the stuff.
    Nicely compiled and explained.

    ReplyDelete
  5. Very nice collections of Q&A. Keep your updates frequently with verity of topics...

    ReplyDelete
  6. These core Java questions are good from freshers point of view but experienced professionals probably face more challenging questions than mentioned here. I love to ask questions from multi-threading, concurrency and JVM internals, GC to check how much a Java developer knows about areas which are tricky. You can use this list to test only basic knowledge of Java for college graduates and junior developer, you need a different list for more senior candidates.

    ReplyDelete
    Replies
    1. @Anonymous, on screening round e.g. phone interviews these types of questions are quite popular which check your breadth of knowledge rather than the depth.

      Delete
  7. Thanks for posting that information.

    ReplyDelete
  8. Replies
    1. Hello @Ashtapathy PS, glad that you like this core Java Interview Questions

      Delete
  9. Cool stuff & well done..

    ReplyDelete
    Replies
    1. Thanks @Prankit, glad that you like this core Java Interview Questions from telephonic round.

      Delete
  10. Thank you. It's really helpful.

    ReplyDelete
    Replies
    1. Thank you Soumik, great that this article helped you on interview.

      Delete
  11. I've been in a couple of interviews and all the questions that was there are included in this tutorial. Thank you very much!

    ReplyDelete
    Replies
    1. Thank you Ariel, glad that this article help you to do well on your Java interview.

      Delete
  12. Q26: You can calculate factorial by simple iteration, recursion is just a waste of memory. There is also no room or reason for memorization when calculating factorial.

    ReplyDelete
    Replies
    1. @Anonymous, yes, you can, iterative solution is often better than recursive one except in some cases where you are dealing with recursive data structure like linked list or binary tree. But, what do you do when interviewer will ask for a recursive solution? you should be able to solve the problem by using both iteration and recursion and can explain/convince interviewer which one is better and why?

      Delete
  13. I found a very good book for a quick and detailed check of what might be asked in the interview. I decided to change the firm after couple of years being in one place, so it was good to have all possible questions regarding Java coding in one book. "TOP 30 Java Interview Coding Tasks" by Matthew Urban.

    Written very concisely and easy to read, with good exercises.

    Bought on Amazon, didn't cost a fortune )
    https://www.amazon.com/TOP-Java-Interview-Coding-Tasks-ebook/dp/B07F8CKS2S

    ReplyDelete
  14. Hello, Javin

    I was searching a few days ago for some articles about Java Interview Questions For Fresher and I came across this page

    Great Stuff!

    I really loved this Questions Resource page.

    In fact, it inspired me to create a more thorough and up-to date version.
    If you want see my article please inform me.

    It might be worth a mention in your article.

    Either way, Keep up the awesome work!

    Prince Das

    ReplyDelete
    Replies
    1. Hello Prince, yes, love to see your article, if you want you can also contribute to our medium channel http://medium.com/javarevisited.

      Delete

Feel free to comment, ask questions if you have any doubt.