40 Core Java Interview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Write a program to reverse Array in place? (solution)

Key point here is that you need to reverse the array in place, which means you cannot use additional buffer, one or two variables will be fine. Sol: Use two variables; one for start, one for end. Loop through half of the length of array and swap the values at the variables. If length is even, subtract one.

How to Swap two numbers without using temp variable? (solution)

One of three ways 1. Use addition and subtraction 2. Use the XOR (^) operator 3. Use multiplication and division Note: Both 1 and 3 can cause arithmetic overflow

Difference between TreeSet and TreeMap in Java? (detailed answer)

Though both are sorted collection, TreeSet is essentially a Set data structure which 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.

How to check if linked list contains loop in Java? (solution)

1. Use two pointers: 'fast' and 'slow' 2. Move 'fast' two nodes and 'slow' one node in each iteration 3. If 'fast' and 'slow' meet, the linked list contains a cycle 4. If 'fast' points to null or 'fast.next' points to null then the linked list is not cyclic

Difference between abstract class and interface? (detailed answer)

Java interfaces are implicitly abstract and can't have implementations. Abstract classes can have instance methods.

What is difference between Iterator and Enumeration in Java? (detailed answer)

Main difference is that Iterator was introduced in place of Enumeration. It also allows you to remove elements from 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 release.

What does the synchronized keyword do?

Used when you only want a single thread to complete the function at a time

Write a Java program to print Fibonacci series (solution)

public static int fib(int n){ // fib add prev values together // first is 0, then 1 // fib == 0 1 1 2 3 5 8 13 if(n == 0){ return 0; } else if (n == 1){ return 1; } else { return fib(n - 2) + fib(n - 1); } }

Difference between Association, Composition and Aggregation? (detailed answer)

* Association is between two separate classes and can be 1 to *, * to 1, 1 to 1, etc. * Aggregation is a form of Association that is unidirectional. Both classes can exist without the other. * Composition is a form of Aggregation in which both classes depend on the other.

Difference between Runnable and Callable interface in Java?

* Runnable needs run() method to be implemented, Callable needs call() method * run() doesn't return anything, call() returns a result on completion * a thread can't be created with a Callable, it can only be created with a Runnable * call() can throw an exception, run() can't

Difference between transient and volatile in Java? (detailed answer)

* Transient keyword is used in Serialization while volatile is used in multi-threading. * If you want to exclude a variable from serialization process then mark that variable transient, similar to a static variable. * Volatile makes sure that a shared variable is immediately updated in main memory so that all threads that use the variable have the updated variable * Volatile "happens-before" relationship guarantees that statements before volatile write, and statements after volatile read, will be in main memory

Write Java program to reverse String without using API? (solution)

1. Loop through source string backwards, adding each character (using charAt) to another string 2. Use StringBuffer or StringBuilder's built-in reverse() method with toString(). 3. Create a recursive function that returns if str length is less than 2, and returns a recursive call with a substring at 1 and the first character added at the end

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. Get the square root of the number and then use a loop to check if all the numbers less than the square root are divisible.

Write a Program to solve Producer Consumer problem in Java? (solution)

A very good question to check if candidate can write inter thread communication code or not. If a guy can write producer consumer solution by hand and point out critical section 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 solution 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.

Difference between 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, its default in Java. Which means if you don't specify any access modifier than 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 same package but only on sub class outside package and public variables e.g. method, class or variables are accessible anywhere. This is highest level of access modifier and provide lowest form of encapsulation.

What is an atomic operation?

An operation that cannot be broken up into smaller parts that could be performed by different processors.

What is difference between Overloading and Overriding in Java? (detailed answer)

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

29) How to find middle element of 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 middle element, that is the crux of the problem. One solution is by using two pointers, fast and slow. Slower pointer moves 1 step when faster pointer move to 2 steps, causing slow to point to middle when fast is pointing to end of the list i.e. null. Check out solution for Java code sample.

What is difference between wait and notify in Java? (detailed answer)

Both wait and notify methods are used for inter thread communication, where wait is used to pause the thread on a condition and notify is used to send notification to waiting threads. Both must be called from synchronized context e.g. synchronized method or block.

How do you convert bytes to character 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 character. Incorrect choice of character encoding may alter meaning of message by interpreting it differently. i.e. String str = new String(bytes, "UTF-8")

What is the difference between Checked and Unchecked Exception in Java? (detailed answer)

Checked exception ensures that handling of the exception is provided and its 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.

Write a program to reverse a number in Java? (solution)

Convert to a string, then use charAt to reverse the string into a new string. Cast the string into an int and you're done.

Write a Program to find maximum and minimum number in array? (solution)

Create min and max variables using the bounds and then loop through the array and set each based on the values in the array.

Difference between extends Thread vs implements Runnable in Java?

Difference comes from the fact that you can only extend one class in Java, which means if you extend Thread class you lose your opportunity to extend another class, on the other hand if you implement Runnable, you can still extend another class

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 question e.g. how can you use HashMap because its needs two object key and value? what is the value in case of HashSet? Well, in case of HashSet a dummy object is used as value and key objects are the actual element on Set point of view. Since HashMap doesn't allow duplicate key it also follows contract of set data structure to not allow duplicates. See detailed answer for more analysis and explanation.

5 Coding best practices you learned in Java? (return to this)

If you are developing on a programming language for couple of years, you sure knows lots of best practices, by asking couple of them, Interviewer just checking 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 size of Collection, this will save lot of time spent on resizing - Always declare variable private and final unless you have 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.

Difference between ArrayList and LinkedList in Java? (detailed answer)

In short, ArrayList is backed by array in Java, while LinkedList is just collection of nodes, similar to linked list data structure. ArrayList also provides random search if you know the index, while LinkedList only allows sequential search. On other hand, adding and removing element from middle is efficient in LinkedList as compared to ArrayList because it only require to modify links and no other element is rearranged.

What is difference between FileInputStream and FileReader in Java? (detailed answer)

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. This means that the latter engages in character encoding while converting bytes to text in Java.

Can you override static method in Java? (detailed answer)

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

What is equlas() and hashCode() contract in Java? Where does it used? (detailed answer)

One of the must ask question in Java telephonic interview. If a guy doesn't know about equals() and hashCode() then he is probably not worth pursuing further because its the core of the Java fundamentals. The key point of contract is that if two objects are equal by equals() method then they must have same hashcode, but unequal object can also have same hashcode, which is the cause of collision on hash table based collection e.g HashMap. When you override equals() you must remember to override hashCode() method to keep the contract valid.

What is the difference between PATH and CLASSPATH in Java? (detailed answer)

PATH is an environment variable which points to Java binary which is used to run Java programs. CLASSPATH is another environment variable which points to Java class files or JAR files. If a class is not found in CLASSPATH then Java throws ClassNotFoundException.

Write a Program to calculate factorial in Java? (solution)

Pretty easy. Know both iterative and recursive methods. Also know that the recursive method can lead to a stackOverFlowError. Since factorial of a number is equal to number multiplied by factorial of previous number, you can cache those value instead of recalculating them, this will impress your interviewer a bit.

Difference between Serializable and Externalizable in Java? (detailed answer)

Serializable is a marker interface with no methods defined while Externalizable is an interface that has two methods defined in it (e.g. readExternal() and writeExternal()) which allow you to control the serialization process. Serializable uses a default serialization process which can be very slow for some application.

Difference between String, StringBuffer and StringBuilder in Java?

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. On later two, StringBuffer is synchronized while StringBuilder is not, in fact its a drop-in replacement of StringBuffer.

What is difference between calling start() and run() method of Thread? (detailed answer)

The only difference between start() and run() method in Thread, is that start creates a new thread while run doesn't create any threads and simply executes in the current thread like a normal method call.

What is difference between synchronize and concurrent Collection in Java? (detailed answer)

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

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 implements 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 natural ordering of your object. Main difference between these two is that, you could create multiple Comparator to define multiple sorting order based upon different attribute of object. Also, In order to implement Comparable you must have access of the class or code, but you can use Comparator without having source code of class, all you need is the JAR file of 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.

Difference between static and dynamic binding in Java? (detailed answer)

This is usually asked as follow-up of previous question, static binding is related to overloaded method and dynamic binding is related to overridden method. Method like private, final and static are resolved using static binding at compile time but virtual methods which can be overridden are resolved using dynamic binding at runtime.

Why wait and notify methods are declared in Object class? (detailed answer)

This question is more to find out how much experience you really have and what is your thinking towards Java API and its design decision. Similar question is why String is immutable in Java? Well, true answer can only be given by Java designers but you can reason something. For example, wait and notify methods are associated with locks which is owned by object not thread, and that's why it make sense to keep those method on java.lang.Object class. See the detailed answer for more discussion and reasoning.

Difference between HashMap and Hashtable in Java? (detailed answer)

Though both HashMap and Hashtable are based upon hash table data structure, there are subtle difference 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.

Can we have return statement in finally clause? What will happen? (detailed answer)

Yes, you can use return statement in finally block, but it will not prevent finally block from being executed. BTW, if you also used return statement in try block then return value from finally block with override whatever is returned from try block.

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]


Ensembles d'études connexes

Chapter 5 Test (5-1 through 5-8)

View Set

Review practice problems for exam 2

View Set

Human Physiology Exam 2 Questions (Chapters 5 & 6)

View Set

HORT 200E - Module 5-8 Questions

View Set

Chapter 53 Disorders of the Female Repro System

View Set

Morality Final (Test: Sin and Forgiveness)

View Set