Java Interview Questions and Answers
Practice Java interview questions and answers organized by difficulty, with revealable explanations and related topics.
Entry questions
6 questions- Question 1Entry
What is the Difference between JDK and JRE?
- Java
Reveal answerHide answer
**The Java Runtime Environment (JRE) **is basically the Java Virtual Machine (JVM) where your Javaprograms are being executed. It also includes browser plugins for applet execution. The Java Development Kit (JDK) is the full featured Software Development Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java Debugger), in order for a user to develop, compile and execute Java applications.
- Question 2Entry
What is JVM? Why is Java called the "Platform Independent Programming Language”?
- Java
Reveal answerHide answer
A Java virtual machine (JVM) is a process virtual machine that can execute Java bytecode. Each Java source file is compiled into a bytecode file, which is executed by the JVM. Java was designed to allow application programs to be built that could be run on any platform, without having to be rewritten or recompiled by the programmer for each separate platform. A Java virtual machine makes this possible, because it is aware of the specific instruction lengths and other particularities of the underlying hardware platform.
- Question 3Entry
What is a Servlet?
- Java
Reveal answerHide answer
The servlet is a Java programming language class used to process client requests and generate dynamic web content. Servlets are mostly used to process or store data submitted by an HTML form, provide dynamic content and manage state information that does not exist in the stateless HTTP protocol.
- Question 4Entry
What is a JSP Page?
- Java
Reveal answerHide answer
A Java Server Page (JSP) is a text document that contains two types of text: static data and JSP elements.
Static data can be expressed in any text-based format, such as HTML or XML. JSP is a technology that mixes static content with dynamically-generated content.
- Question 5Entry
What is the difference between an Applet and a Java Application?
- Java
Reveal answerHide answer
Applets are executed within a Java enabled browser, but a Java application is a standalone Java program that can be executed outside of a browser. However, they both require the existence of a Java Virtual Machine (JVM). Furthermore, a Java application requires a main method with a specific signature, in order to start its execution. Java applets don’t need such a method to start their execution. Finally, Java applets typically use a restrictive security policy, while Java applications usually use more relaxed security policies.
- Question 6Entry
What are the two types of Exceptions in Java? Which are the differences between them?
- Java
Reveal answerHide answer
Java has two types of exceptions: checked exceptions and unchecked exceptions.
- **Unchecked exceptions **do not need to be declared in a method or a constructor’s throws clause, if they can be thrown by the execution of the method or the constructor, and propagate outside the method or constructor boundary.
- On the other hand, checked exceptions must be declared in a method or a constructor’s throws clause.
Junior questions
37 questions- Question 1Junior
What are Expressions?
- Java
Reveal answerHide answer
A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client, by the web server. Expressions are defined between <% = and %> tags.
- Question 1Junior
What are JSP Actions?
- Java
Reveal answerHide answer
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. JSP actions are executed when a JSP page is requested. They can be dynamically inserted into a file, re-use JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.Some of the available actions are listed below: jsp:include – includes a file, when the JSP page is requested. jsp:useBean – finds or instantiates a JavaBean. jsp:setProperty – sets the property of a JavaBean. jsp:getProperty – gets the property of a JavaBean. jsp:forward – forwards the requester to a new page. jsp:plugin – generates browser-specific code.
- Question 1Junior
What differences exist between HashMap and Hashtable ?
- Java
Reveal answerHide answer
There are several differences between HashMap and Hashtable in Java:
- Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
- Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
- One of HashMap's subclasses is LinkedHashMap , so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn't be as easy if you were using Hashtable .
- Question 2Junior
Explain the architechure of a Servlet.
- Java
Reveal answerHide answer
The core abstraction that must be implemented by all servlets is the javax.servlet.Servlet interface. Each servlet must implement it either directly or indirectly, either by extending javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet. Finally, each servlet is able to serve multiple requests in parallel using multithreading.
- Question 2Junior
What does System.gc() and Runtime.gc() methods do?
- Java
Reveal answerHide answer
These methods can be used as a hint to the JVM, in order to start a garbage collection. However, this it is up to the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time.
- Question 3Junior
Explain what is Binary Search
- Searching Java JavaScript
Reveal answerHide answer
When the list is sorted we can use the binary search (also known as half-interval search, logarithmic search, or binary chop) technique to find items on the list. Here's a step-by-step description of using binary search:
- Let min = 1 and max = n .
- Guess the average of max and min rounded down so that it is an integer.
- If you guessed the number, stop. You found it!
- If the guess was too low, set min to be one larger than the guess.
- If the guess was too high, set max to be one smaller than the guess.
- Go back to step two. In this example we looking for array item with value 4 : When you do one operation in binary search we reduce the size of the problem by half (look at the picture below how do we reduce the size of the problem area) hence the complexity of binary search is
O( log n) . The binarysearch algorithm can be written either recursively or iteratively. Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n) Implementation: JS
var binarySearch = function(array, value) { var guess, min = 0, max = array.length - 1; while(min <= max){ guess = Math.floor((min + max) /2); if(array[guess] === value) return guess; else if(array[guess] < value) min = guess + 1; else max = guess - 1; } return -1; } Java // binary search example in Java /* here Arr is an of integer type, n is size of arrayand target is element to be found */ int binarySearch(int Arr[], int n, int target) {//set stating and ending index
int start = 0, ending = n-1; while(start <= ending) { // take mid of the list int mid = (start + end) / 2; // we found a match if(Arr[mid] == target) { return mid; } // go on right side else if(Arr[mid] < target) { start = mid + 1; } // go on left side else { end = mid - 1; } } // element is not present in list return -1; } PY def BinarySearch(lys, val): first = 0 last = len(lys)-1 index = -1 while (first <= last) and (index == -1): mid = (first+last)//2 if lys[mid] == val: index = mid else: if val<lys[mid]: last = mid -1 else: first = mid +1return index
- Question 3Junior
How to reverse a singly Linked List using only two pointers?
- Linked Lists Java
Reveal answerHide answer
Nothing faster than
O( n) can be done. You need to traverse the list and alter pointers on every node, so timewill be proportional to the number of elements. Implementation: Java
public void reverse(Node head) { Node curr = head, prev = null; while (head.next != null) { head = head.next; // move the head to next node curr.next = prev; // break the link to the next node and assign it to previous prev = curr; // we are done with previous, move it to next node curr = head; // current moves along with head } head.next = prev; //for last node } - Question 4Junior
Return the N-th value of the Fibonacci sequence Recursively
- Fibonacci Series Data Structures Java JavaScript
Reveal answerHide answer
Recursive solution looks pretty simple (see code). Let’s look at the diagram that will help you understand what’s going on here with the rest of our code. Function fib is called with argument 5: Basically our fib function will continue to recursively call itself creating more and more branches of the tree until it hits the base case, from which it will start summing up each branch’s return values bottom up, until it finally sums them all up and returns an integer equal to 5. Complexity Analysis:
Time Complexity: O(2^n)In case of recursion the solution take exponential time, that can be explained by the fact that the size of the tree exponentially grows when n increases. So for every additional element in the Fibonacci sequence we get an increase in function calls. Big O in this case is equal to
O( 2n) . Exponential Time complexity denotes an algorithmwhose growth doubles with each addition to the input data set. Implementation: JS
function fib(n) { if (n < 2){return n
} return fib(n - 1) + fib (n - 2) } Java public int fibonacci(int n) { if (n < 2) return n; return fibonacci(n - 1) + fibonacci(n - 2); } PY def F(n): if n == 0: return 0 elif n == 1: return 1 else: return F(n-1)+F(n-2) - Question 6Junior
What is reflection and why is it useful?
- Java
Reveal answerHide answer
The name reflection is used to describe code which is able to inspect other code in the same system (or itself) and to make modifications at runtime. For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.
Method method = foo.getClass().getMethod("doSomething", null); method.invoke(foo, null); - Question 7Junior
How does Garbage Collection prevent a Java application from going out of memory?
- Java
Reveal answerHide answer
It doesn’t! Garbage Collection simply cleans up unused memory when an object goes out of scope and is no longer needed. However an application could create a huge number of large objects that causes an OutOfMemoryError .
- Question 7Junior
How do I efficiently iterate over each entry in a Java Map ?
- Java
Reveal answerHide answer
Consider: Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); }In Java 8 you can do it clean and fast using the new lambdas features:
final long[] i = {0}; map.forEach((k, v) -> i[0] += k + v); - Question 8Junior
What is JDBC?
- Java
Reveal answerHide answer
JDBC is an abstraction layer that allows users to choose between databases. JDBC enables developers to write database applications in Java, without having to concern themselves with the underlying details of a particular database.
- Question 8Junior
Explain Serialization and Deserialization.
- Java
Reveal answerHide answer
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes and includes the object’s data, as well as information about the object’s type, and the types of data stored in the object. Thus, serialization can be seen as a way of flattening objects, in order to be stored on disk, and later, read back and reconstituted. Deserialisation is the reverse process of converting an object from its flattened state to a live object.
- Question 9Junior
What is an Java Applet?
- Java
Reveal answerHide answer
A Java Applet is program that can be included in a HTML page and be executed in a java enabled client browser. Applets are used for creating dynamic and interactive web applications.
- Question 9Junior
What’s the difference between sendRedirect and forward methods?
- Java
Reveal answerHide answer
The sendRedirect method creates a new request, while the forward method just forwards a request to a new target. The previous request scope objects are not available after a redirect, because it results in a new request. On the other hand, the previous request scope objects are available after forwarding. FInally, in general, the sendRedirect method is considered to be slower compare to the forward method.
- Question 10Junior
What is the importance of finally block in exception handling?
- Java
Reveal answerHide answer
A finally block will always be executed, whether or not an exception is actually thrown. Even in the case where the catch statement is missing and an exception is thrown, the finally block will still be executed. Last thing to mention is that the finally block is used to release resources like I/O buffers, database connections, etc.
- Question 10Junior
Explain the architechure of a Servlet.
- Java
Reveal answerHide answer
The core abstraction that must be implemented by all servlets is the javax.servlet.Servlet interface. Each servlet must implement it either directly or indirectly, either by extending javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet. Finally, each servlet is able to serve multiple requests in parallel using multithreading.
- Question 11Junior
What is the difference between Exception and Error in Java?
- Java
Reveal answerHide answer
An Error "indicates serious problems that a reasonable application should not try to catch." An Exception "indicates conditions that a reasonable application might want to catch."
- Question 11Junior
What is Function Overriding and Overloading in Java?
- Java
Reveal answerHide answer
Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters.
class Dog{ public void bark(){ System.out.println("woof "); }//overloading method public void bark(int num){ for(int i=0; i<num; i++) System.out.println("woof "); } }On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.
class Dog{ public void bark(){ System.out.println("woof "); } } class Hound extends Dog{ public void sniff(){ System.out.println("sniff "); } public void bark(){ System.out.println("bowl"); } } public class OverridingTest{ public static void main(String [] args){ Dog dog = new Hound(); dog.bark(); } } - Question 12Junior
When does an Object becomes eligible for Garbage Collection in Java ?
- Java
Reveal answerHide answer
A Java object is subject to garbage collection when it becomes unreachable to the program in which it is currently used.
- Question 12Junior
What are Decalarations?
- Java
Reveal answerHide answer
Declarations are similar to variable declarations in Java. Declarations are used to declare variables for subsequent use in expressions or scriptlets. To add a declaration, you must use the sequences to enclose your declarations.
- Question 13Junior
What is the purpose of Garbage Collection in Java, and when is it used?
- Java
Reveal answerHide answer
The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application, in order for the resources to be reclaimed and reused.
- Question 13Junior
What are JSP Actions?
- Java
Reveal answerHide answer
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. JSP actions are executed when a JSP page is requested. They can be dynamically inserted into a file, re-use JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.Some of the available actions are listed below:
jsp:include – includes a file, when the JSP page is requested. jsp:useBean – finds or instantiates a JavaBean. jsp:setProperty – sets the property of a JavaBean. jsp:getProperty – gets the property of a JavaBean. jsp:forward – forwards the requester to a new page. jsp:plugin – generates browser-specific code.
- Question 14Junior
How HashMap works in Java?
- Java
Reveal answerHide answer
A HashMap in Java stores key-value pairs. The HashMap requires a hash function and uses hashCode and equals methods, in order to put and retrieve elements to and from the collection respectively. When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection. If the key exists, its value is updated with the new value. Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.
- Question 14Junior
What are Directives?
- Java
Reveal answerHide answer
What are the different types of Directives available in JSP ? Directives are instructions that are processed by the JSP engine, when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined between < %@ and % >.The different types of directives are shown below: Include directive: it is used to include a file and merges the content of the file with the current page. Page directive: it is used to define specific attributes in the JSP page, like error page and buffer. Taglib: it is used to declare a custom tag library which is used in the page.
- Question 15Junior
What is an Iterator?
- Java
Reveal answerHide answer
The Iterator interface provides a number of methods that are able to iterate over any Collection. Each Java Collection contains the Iterator method that returns an Iterator instance. Iterators are capable of removing elements from the underlying collection during the iteration.
- Question 15Junior
How are the JSP requests handled?
- Java
Reveal answerHide answer
On the arrival of a JSP request, the browser first requests a page with a .jsp extension. Then, the Web server reads the request and using the JSP compiler, the Web server converts the JSP page into a servlet class. Notice that the JSP file is compiled only on the first request of the page, or if the JSP file has changed.The generated servlet class is invoked, in order to handle the browser’s request. Once the execution of the request is over, the servlet sends a response back to the client. See how to get Request parameters in a JSP.
- Question 16Junior
What are the basic interfaces of Java Collections Framework?
- Java
Reveal answerHide answer
Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are: Collection, which represents a group of objects known as its elements. Set, which is a collection that cannot contain duplicate elements. List, which is an ordered collection and can contain duplicate elements. Map, which is an object that maps keys to values and cannot contain duplicate keys.
- Question 16Junior
What is the purpose Class.forName method?
- Java
Reveal answerHide answer
This method is used to method is used to load the driver that will establish a connection to the database.
- Question 17Junior
What is the difference between processes and threads?
- Java
Reveal answerHide answer
The main difference between them is that a Process is a program which is executing some code and a Thread is an independent path of execution in the process. A process can have more than one thread for doing independent task e.g. a thread for reading data from disk, a thread for processing that data and another thread for sending that data over the network.
- Question 17Junior
What is the design pattern that Java uses for all Swing components?
- Java
Reveal answerHide answer
The design pattern used by Java for all Swing components is the Model View Controller (MVC) pattern.
- Question 18Junior
What are pass by reference and pass by value?
- Java
Reveal answerHide answer
When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.
- Question 18Junior
What will happen to the Exception object after exception handling?
- Java
Reveal answerHide answer
The Exception object will be garbage collected in the next garbage collection.
- Question 19Junior
What are the Data Types supported by Java? What isAutoboxing and Unboxing?
- Java
Reveal answerHide answer
The eight primitive data types supported by the Java programming language are: byte short int long float double boolean char Autoboxing is the automatic conversion made by the Java compiler between the primitive types and their corresponding object wrapper classes. If the conversion goes the other way, this operation is called unboxing.
- Question 19Junior
What do you know about the Big-O notation and can you give some examples with respect to different data structures?
- Java
Reveal answerHide answer
The Big-O notation simply describes how well an algorithm scales or performs in the worst case scenario as the number of elements in a data structure increases. The Big-O notation can also be used to describe other behavior such as memory consumption. Since the collection classes are actually data structures, we usually use the Big-O notation to chose the best implementation to use, based on time, memory and performance. Big-O notation can give a good indication about performance for large amounts of data.
- Question 20Junior
What does the static keyword mean? Can you override private or static method in Java?
- Java
Reveal answerHide answer
The static keyword denotes that a member variable or method can be accessed, without requiring an instantiation of the class to which it belongs. A user cannot override static methods in Java, because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. A static method is not associated with any instance of a class so the concept is not applicable.
- Question 20Junior
What is the difference between an Interface and an Abstract class?
- Java
Reveal answerHide answer
Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common characteristics, but they differ in the following features: All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods. A class may implement a number of Interfaces, but can extend only one abstract class. In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract. Abstract classes can implement interfaces without even providing the implementation of interface methods. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public. An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.
Mid questions
71 questions- Question 1Mid
What is the difference between HashMap , LinkedHashMap and TreeMap in Java?
- Java
Reveal answerHide answer
All three classes implement the Map interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen: HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added. TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo() method (or an externally supplied Comparator ). Additionally, it implements the SortedMap interface, which contains methods that depend on this sort order. LinkedHashMap will iterate in the order in which the entries were put into the map
- Question 1Mid
What are untrusted applets?
- Java
Reveal answerHide answer
Untrusted applets are those Java applets that cannot access or execute local system files. By default, all downloaded applets are considered as untrusted.
- Question 1Mid
Does Java support multiple inheritance?
- Java
Reveal answerHide answer
No, Java does not support multiple inheritance. Each class is able to extend only on one class, but is able to implement more than one interfaces.
- Question 2Mid
What’s the difference between a ClassNotFoundException and NoClassDefFoundError ?
- Java
Reveal answerHide answer
A ClassNotFoundException means the class file for a requested class is not on the classpath of the application. A NoClassDefFoundErrormeans that the class file existed at runtime, but for some reason the class could not be turned into a Class definition. A common cause is an exception being thrown in static initialization blocks.
- Question 2Mid
What are the steps involved to make work a RMI program?
- Java
Reveal answerHide answer
The following steps must be involved in order for a RMI program to work properly: Compilation of all source files. Generatation of the stubs using rmic. Start the rmiregistry. Start the RMIServer. Run the client program.
- Question 3Mid
What is the difference between public , protected , package- private and private in Java?
- Java
Reveal answerHide answer
Private - Like you'd think, only the class in which it is declared can see it Package Private - Can only be seen and used by the package in which it was declared. This is the default in
Java (which some see as a mistake)Protected - Package Private + can be seen by subclasses or package member Public - Everyone can see it
| │ Class │ Package │ Subclass │ Subclass │ World |
| │ │ │(same pkg)│(diff pkg)│ | |───────────┼───────┼─────────┼──────────┼──────────┼────────| |public │ + │ + │ + │ + │ + | |───────────┼───────┼─────────┼──────────┼──────────┼────────| |protected │ + │ + │ + │ + │ | |───────────┼───────┼─────────┼──────────┼──────────┼────────| |no modifier│ + │ + │ + │ │ | |───────────┼───────┼─────────┼──────────┼──────────┼────────| |private │ + │ │ │ │ | |___________|_______|_________|__________|__________|________| + : accessible blank : not accessible - Question 3Mid
Floyd's Cycle Detect Algorithm: Explain how to find a starting node of a Cycle in a Linked List?
- Linked Lists Java
Reveal answerHide answer
This is Floyd's algorithm for cycle detection. Once you've found a node that's part of a cycle, how does one find the start of the cycle? In the first part of Floyd's algorithm, the hare moves two steps for every step of the tortoise. If the tortoise and hare ever meet, there is a cycle, and the meeting point is part of the cycle, but not necessarily the first node in the cycle. Once tortoise and hare meet, let's put tortoise back to the beginning of the list and keep hare where they met (which is k steps away from the cycle beginning). The hypothesis (see math explanation) is that if we let them move at the same speed (1 step for both), the first time they ever meet again will be the cycle beginning. Another solution to mention is Hash Map: Traverse the nodes list. For each node encountered, add it to the identity hash map If the node already existed in the identity map then the list has a circular link and the node which was prior to this conflict is known (either check before moving or keep the "last node")
Implementation: Java
public ListNode getLoopStartingPoint(ListNode head) { boolean isLoopExists = false; ListNode slowPtr = head, fastPtr = head; while (!Objects.isNull(fastPtr) && !Objects.isNull(fastPtr.getNext())) { slowPtr = slowPtr.getNext(); fastPtr = fastPtr.getNext().getNext(); if (slowPtr == fastPtr) { isLoopExists = true; break; } } if (!isLoopExists) return null; slowPtr = head; while (slowPtr != fastPtr) { slowPtr = slowPtr.getNext(); fastPtr = fastPtr.getNext(); } return slowPtr; } - Question 3Mid
What is the difference between final , finalize and finally ?
- Java
Reveal answerHide answer
final is a Java keyword used to indicate that either a method can not override in a subclass, or a class can not be extended or a field can not be modified. finalize is a method that gets called on an instance of an Object when it is garbage collected. finally is a Java keyword used in exception handling to indicate a block of code that should always be run whether an exception is thrown or not.
- Question 3Mid
What is a Server Side Include (SSI)?
- Java
Reveal answerHide answer
Server Side Includes (SSI) is a simple interpreted server-side scripting language, used almost exclusively for the Web, and is embedded with a servlet tag. The most frequent use of SSI is to include the contents of one or more files into a Web page on a Web server. When a Web page is accessed by a browser, the Web server replaces the servlet tag in that Web page with the hyper text generated by the corresponding servlet.
- Question 4Mid
What is the main difference between StringBuffer and StringBuilder ?
- Java
Reveal answerHide answer
StringBuffer is synchronized, StringBuilder is not. When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem. StringBuilder is faster than StringBuffer because it's not synchronized. Using synchronized methods in a single thread is overkill.
- Question 4Mid
What is the JIT?
- Java
Reveal answerHide answer
The JIT is the JVM’s mechanism by which it can optimize code at runtime. JIT means Just In Time. It is a central feature of any JVM. Among other optimizations, it can perform code inlining, lock coarsening or lock eliding, escape analysis etc. The main benefit of the JIT is on the programmer’s side: code should be written so that it just works; if the code can be optimized at runtime, more often than not, the JIT will find a way.
- Question 4Mid
What is the Java Classloader?
- Java
Reveal answerHide answer
The Java Classloader is the part of the Java runtime environment that loads classes on demand (lazy loading) into the JVM (Java Virtual Machine). Classes may be loaded from the local file system, a remote file system, or even the web.
- Question 4Mid
What is the role of stub in RMI?
- Java
Reveal answerHide answer
A stub for a remote object acts as a client’s local representative or proxy for the remote object. The caller invokes a method on the local stub, which is responsible for executing the method on the remote object. When a stub’s method is invoked, it undergoes the following steps: It initiates a connection to the remote JVM containing the remote object. It marshals the parameters to the remote JVM. It waits for the result of the method invocation and execution. It unmarshals the return value or an exception if the method has not been successfully executed.
It returns the value to the caller.
- Question 4Mid
What is the difference between an Applet and a Servlet?
- Java
Reveal answerHide answer
An Applet is a client side java program that runs within a Web browser on the client machine. On the other hand, a servlet is a server side component that runs on the web server.An applet can use the user interface classes, while a servlet does not have a user interface. Instead, a servlet waits for client’s HTTP requests and generates a response in every request.
- Question 5Mid
Check if parentheses are balanced using Stack
- Stacks Java Python JavaScript
Reveal answerHide answer
One of the most important applications of stacks is to check if the parentheses are balanced in a given expression. The compiler generates an error if the parentheses are not matched. Here are some of the balanced and unbalanced expressions: balanced parentheses Algorithm
- Declare a character stack which will hold an array of all the opening parenthesis.
- Now traverse the expression string exp.
- If the current character is a starting bracket ( ( or { or [ ) then push it to stack.
- If the current character is a closing bracket ( ) or } or ] ) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.
- After complete traversal, if there is some starting bracket left in stack then “not balanced” Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) We are traversing through each character of string, Time complexity
O( n) .We are storing the opposite parentheses characters in the stack, in the worst case there can be all the opposite characters in the string, Space complexity
O( n) . Implementation: JS let isMatchingBrackets = function (str) { let stack = []; let map = { '(': ')', '[': ']', '{': '}' } for (let i = 0; i < str.length; i++) { // If character is an opening brace add it to a stack if (str[i] === '(' || str[i] === '{' || str[i] === '[' ) { stack.push(str[i]); } // If that character is a closing brace, pop from the stack, which will also reduce the lengthof the stack each time a closing bracket is encountered.
else { let last = stack.pop(); //If the popped element from the stack, which is the last opening brace doesn’t match thecorresponding closing brace in the map, then return false
if (str[i] !== map[last]) {return false}; } } // By the completion of the for loop after checking all the brackets of the str, at the end, if thestack is not empty then fail
if (stack.length !== 0) {return false}; return true; } Java public static boolean balancedParenthensies(String s) { Stack<Character> stack = new Stack<Character>(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == '[' || c == '(' || c == '{' ) { stack.push(c); } else if(c == ']') { if(stack.isEmpty() || stack.pop() != '[') { return false; } } else if(c == ')') { if(stack.isEmpty() || stack.pop() != '(') { return false; } } else if(c == '}') { if(stack.isEmpty() || stack.pop() != '{') { return false; } } } return stack.isEmpty(); } PY open_list = ["[","{","("] close_list = ["]","}",")"]# Function to check parentheses def check(myStr): stack = [] for i in myStr: if i in open_list: stack.append(i) elif i in close_list: pos = close_list.index(i) if ((len(stack) > 0) and (open_list[pos] == stack[len(stack)-1])): stack.pop() else:return "Unbalanced"
if len(stack) == 0:return "Balanced" else: return "Unbalanced"
- Question 5Mid
How and where are Annotations used in Java?
- Java
Reveal answerHide answer
Annotations are meta-meta-objects which can be used to describe other meta-objects. Meta-objects are classes, fields and methods. Asking an object for its meta-object (e.g. anObj.getClass() ) is called introspection. The introspection can go further and we can ask a meta-object what are its annotations (e.g. aClass.getAnnotations ). Introspection and annotations belong to what is called reflection and meta- programming. Annotation processing is a very powerful mechanism and can be used in a lot of different ways: to describe constraints or usage of an element: e.g. @Deprecated, @Override, or @NotNull to describe the "nature" of an element, e.g. @Entity, @TestCase, @WebService to describe the behavior of an element: @Statefull, @Transaction to describe how to proce
- Question 5Mid
How threadsafe is enum in Java?
- Java
Reveal answerHide answer
Creation of an enum is guaranteed to be threadsafe. However, the methods on an enum type are not necessarily threadsafe.
- Question 5Mid
What is the difference between doGet() and doPost() ?
- Java
Reveal answerHide answer
doGET: The GET method appends the name-value pairs on the request’s URL. Thus, there is a limit on the number of characters and subsequently on the number of values that can be used in a client’s request. Furthermore, the values of the request are made visible and thus, sensitive information must not be passed in that way. doPOST: The POST method overcomes the limit imposed by the GET request, by sending the values of the request inside its body. Also, there is no limitations on the number of values to be sent across. Finally, the sensitive information passed through a POST request is not visible to an external client.
- Question 5Mid
What is the use of CallableStatement ? Name the method, which is used to prepare a CallableStatement .
- Java
Reveal answerHide answer
A CallableStatement is used to execute stored procedures. Stored procedures are stored and offered by a database. Stored procedures may take input values from the user and may return a result. The usage of stored procedures is highly encouraged, because it offers security and modularity.The method that prepares a CallableStatement is the following:
CallableStament.prepareCall(); - Question 6Mid
Write a program for Recursive Binary Search
- Searching Java Python JavaScript
Reveal answerHide answer
The first difference is that the while loop from iterative approach is replaced by a recursive call back to the same method with the new values of low and high passed to the next recursive invocation along with Array and key or target element. The second difference is that instead of returning false when the while loop exits in the iterative version, in case of the recursive version, the condition of low > high is checked at the beginning of the next level of recursion and acts as the boundary condition for stopping further recursive calls by returning false. Also, note that the recursive invocations of binarySearch() return back the search result up the recursive call stack so that true or false return value is passed back up the call stack without any further processing. To further optimize the solution, in term of running time, we could consider implement the tail-recursive solution, where the stack trace of the algorithm would not pile up, which leads to a less memory footprint during the running time. To have the tail-recursive solution, the trick is to simply return the result from the next recursive function instead of further processing. Implementation: JS
function binarySearch(sortedArray, searchValue, minIndex, maxIndex) { var currentIndex; var currentElement; while (minIndex <= maxIndex) { // Find the value of the middle of the array var middleIndex = (minIndex + maxIndex) / 2 | 0; currentElement = sortedArray[middleIndex]; // It's the same as the value in the middle - we can return! if (currentElement === searchValue) { return middleIndex; } // Is the value less than the value in the middle of the array if (currentElement < searchValue) { return binarySearch(sortedArray, searchValue, middleIndex + 1, maxIndex); } // Is the value greater than the value in the middle of the array if (currentElement > searchValue) { return binarySearch(sortedArray, searchValue, minIndex, middleIndex - 1); } } return -1; } Java // Find out if a key x exists in the sorted array // A[low..high] or not using binary search algorithm public static int binarySearch(int[] A, int low, int high, int x) { // Base condition (search space is exhausted) if (low > high) { return -1; }// we find the mid value in the search space and // compares it with key value int mid = (low + high) / 2;// overflow can happen. Use beleft // int mid = low + (high - low) / 2; // Base condition (key value is found) if (x == A[mid]) { return mid; }// discard all elements in the right search space // including the mid element else if (x < A[mid]) { return binarySearch(A, low, mid - 1, x); }// discard all elements in the left search space // including the mid element else { return binarySearch(A, mid + 1, high, x); } } PY class Solution: def searchInsert(self, nums, target): return self.tail_recursive_searchInsert(0, nums, target) def tail_recursive_searchInsert(self, start, nums, target): """ :type nums: List[int] :type target: int :rtype: intreturn the position to insert a new element into the sorted list. Note: the solution can be implemented in a recursive way. """
size = len(nums) if (size == 0): # empty input list, early exitreturn start
mid_index = int(size/2) if (nums[mid_index] == target):return start + mid_index
elif (nums[mid_index] > target): return self.tail_recursive_searchInsert( start, nums[0:mid_index], target) else: return self.tail_recursive_searchInsert( start+mid_index+1, nums[mid_index+1:], target) - Question 6Mid
What is the volatile keyword useful for?
- Java
Reveal answerHide answer
volatile has semantics for memory visibility. Basically, the value of a volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without volatile, readers could see some non-updated value.
- Question 6Mid
What is the volatile keyword useful for?
- Java
Reveal answerHide answer
volatile has semantics for memory visibility. Basically, the value of a volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without volatile, readers could see some non-updated value.
- Question 6Mid
Explain the life cycle of a Servlet.
- Java
Reveal answerHide answer
On every client’s request, the Servlet Engine loads the servlets and invokes its init methods, in order for the servlet to be initialized. Then, the Servlet object handles all subsequent requests coming from that client, by invoking the service method for each request separately. Finally, the servlet is removed by calling the server’s destroy method.
- Question 6Mid
What is the relationship between an event-listener interface and an event-adapter class?
- Java
Reveal answerHide answer
An event-listener interface defines the methods that must be implemented by an event handler for a particular event. An event adapter provides a default implementation of an event-listener interface.
- Question 7Mid
Find all the Permutations of a String
- Backtracking Strings Data Structures Java Python JavaScript
Reveal answerHide answer
A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself (or in simple english: permutation is each of several possible ways in which a set or number of things can be ordered or arranged). A string of length n has n! permutation: ABC
// original string (3)ABC ACB BAC BCA CBA CAB
// permutations 3! = 6To print all permutations of a string use backtracking implemented via recursion: Try each of the letters in turn as the first letter and then find all the permutations of the remaining letters using a recursive call. The base case is when the input is an empty string the only permutation is the empty string. In other words, you simply traverse the tree, and when you reach the leaf you print the permutation. Then you backtrack one level up, and try another option. Moving one level up the tree is what we call the backtracking in this case. Complexity Analysis: Time Complexity: O(n!) Space Complexity: O(n!) For any given string of length n there are n! possible permutations, and we need to print all of them so Time complexity is O(n * n!) . The function will be called recursively and will be stored in call stack for all n! permutations, so Space complexity is O(n!) . Implementation: JS
// using backtracking let permute = (str, left = 0, right = str.length - 1) => { //If left index is equal to right index //Print the string permutation if(left == right){ console.log(str); }else{ for(let i = left; i <= right; i++){ //Swap the letters of the string str = swap(str, left, i); //Generate the permutation with swapped letters permute(str, left+1, right); //Restore the letters back to their position, e.q. backtrack to prev state of the string str = swap(str, left, i); } } }//Function to swap the letters of the string let swap = (str, left, right) => { let arr = str.split(''); [arr[left], arr[right]] = [arr[right], arr[left]]; return arr.join(''); } Java public static void permutation(String str) { permutation("", str); } private static void permutation(String prefix, String str) { int n = str.length(); if (n == 0) System.out.println(prefix); else { for (int i = 0; i < n; i++) // take new prefix from string[i], put it as a first element and construct the rest of the string permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n)); } } PY # using backtracking def permute(a, l, r): if l==r: print toString(a) else: for i in xrange(l,r+1): a[l], a[i] = a[i], a[l] permute(a, l+1, r) a[l], a[i] = a[i], a[l] # backtrack # Driver program to test the above function string = "ABC" n = len(string) a = list(string) permute(a, 0, n-1) - Question 7Mid
Can an enum be extended?
- Java
Reveal answerHide answer
No. Enum types are final by design.
- Question 7Mid
Floyd's Cycle Detect Algorithm: Explain how to find a starting node of a Cycle in a Linked List?
- Linked Lists Java
Reveal answerHide answer
This is Floyd's algorithm for cycle detection. Once you've found a node that's part of a cycle, how does one find the start of the cycle? In the first part of Floyd's algorithm, the hare moves two steps for every step of the tortoise. If the tortoise and hare ever meet, there is a cycle, and the meeting point is part of the cycle, but not necessarily the first node in the cycle.
Once tortoise and hare meet, let's put tortoise back to the beginning of the list and keep hare where they met (which is k steps away from the cycle beginning). The hypothesis (see math explanation) is that if we let them move at the same speed (1 step for both), the first time they ever meet again will be the cycle beginning. Another solution to mention is Hash Map: Traverse the nodes list. For each node encountered, add it to the identity hash map If the node already existed in the identity map then the list has a circular link and the node which was prior to this conflict is known (either check before moving or keep the "last node") Implementation: Java
public ListNode getLoopStartingPoint(ListNode head) { boolean isLoopExists = false; ListNode slowPtr = head, fastPtr = head; while (!Objects.isNull(fastPtr) && !Objects.isNull(fastPtr.getNext())) { slowPtr = slowPtr.getNext(); fastPtr = fastPtr.getNext().getNext(); if (slowPtr == fastPtr) { isLoopExists = true; break; } } if (!isLoopExists) return null; slowPtr = head; while (slowPtr != fastPtr) { slowPtr = slowPtr.getNext(); fastPtr = fastPtr.getNext(); } return slowPtr; } - Question 7Mid
What is the difference between GenericServlet and HttpServlet ?
- Java
Reveal answerHide answer
GenericServlet is a generalized and protocol-independent servlet that implements the Servlet and ServletConfig interfaces. Those servlets extending the GenericServlet class shall override the service method. Finally, in order to develop an HTTP servlet for use on the Web that serves requests using the HTTP protocol, your servlet must extend the HttpServlet instead. Check Servlet examples here.
- Question 7Mid
What is the applet security manager, and what does it provide?
- Java
Reveal answerHide answer
The applet security manager is a mechanism to impose restrictions on Java applets. A browser may only have one security manager. The security manager is established at startup, and it cannot thereafter be replaced, overloaded, overridden, or extended.
- Question 8Mid
What is the JIT?
- Java
Reveal answerHide answer
The JIT is the JVM’s mechanism by which it can optimize code at runtime. JIT means Just In Time. It is a central feature of any JVM. Among other optimizations, it can perform code inlining, lock coarsening or lock eliding, escape analysis etc. The main benefit of the JIT is on the programmer’s side: code should be written so that it just works; if the code can be optimized at runtime, more often than not, the JIT will find a way.
- Question 8Mid
What are Scriptlets?
- Java
Reveal answerHide answer
In Java Server Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in a JSP page. The scriptlet is everything inside the tags. Between these tags, a user can add any valid scriplet.
- Question 8Mid
What happens when an Applet is loaded?
- Java
Reveal answerHide answer
First of all, an instance of the applet’s controlling class is created. Then, the applet initializes itself and finally, it starts running.
- Question 9Mid
How to merge two sorted Arrays into a Sorted Array?
- Arrays Data Structures Java JavaScript Python
Reveal answerHide answer
Let's look at the merge principle: Given two separate lists A and B ordered from least to greatest, construct a list C by: repeatedly comparing the least value of A to the least value of B, removing (or moving a pointer) the lesser value, and appending it onto C. when one list is exhausted, append the remaining items in the other list onto C in order. The list C is then also a sorted list.
Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) This problem will have O(n) complexity at best. Implementation: JS
function merge(a, b) { var result = []; var ai = 0; var bi = 0; while (true) { if ( ai < a.length && bi < b.length) { if (a[ai] < b[bi]) { result.push(a[ai]); ai++; } else if (a[ai] > b[bi]) { result.push(b[bi]); bi++; } else { result.push(a[ai]); result.push(b[bi]); ai++; bi++; } } else if (ai < a.length) { result.push.apply(result, a.slice(ai, a.length)); break; } else if (bi < b.length) { result.push.apply(result, b.slice(bi, b.length)); break; } else { break; } } return result; } Java public static int[] merge(int[] a, int[] b) { int[] answer = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) answer[k++] = a[i] < b[j] ? a[i++] : b[j++]; while (i < a.length) answer[k++] = a[i++]; while (j < b.length) answer[k++] = b[j++]; return answer; } PY def merge(left, right): result = [] i ,j = 0, 0 while i < len(left) and j < len(right): print('left[i]: {} right[j]: {}'.format(left[i],right[j])) if left[i] <= right[j]: print('Appending {} to the result'.format(left[i])) result.append(left[i]) print('result now is {}'.format(result)) i += 1 print('i now is {}'.format(i)) else: print('Appending {} to the result'.format(right[j])) result.append(right[j]) print('result now is {}'.format(result)) j += 1 print('j now is {}'.format(j)) print('One of the list is exhausted. Adding the rest of one of the lists.') result += left[i:] result += right[j:] print('result now is {}'.format(result))return result
- Question 9Mid
How can I synchornize two Java processes?
- Java
Reveal answerHide answer
It is not possible to do something like you want in Java. Different Java applications will use different JVM's fully separating themselves into different 'blackbox'es. However, you have 2 options: Use sockets (or channels). Basically one application will open the listening socket and start waiting until it receives some signal. The other application will connect there, and send signals when it had completed something. I'd say this is a preferred way used in 99.9% of applications. You can call winapi from Java (on windows).
- Question 9Mid
Explain the role of Driver in JDBC.
- Java
Reveal answerHide answer
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each driver must provide implementations for the following classes of the java.sql package: Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver.
- Question 9Mid
If an object reference is set to null , will the Garbage Collector immediately free the memory held by that object?
- Java
Reveal answerHide answer
No, the object will be available for garbage collection in the next cycle of the garbage collector.
- Question 10Mid
Compare the sleep() and wait() methods in Java
- Java
Reveal answerHide answer
sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds. wait() , on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.
sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll() , to achieve synchronization and avoid race conditions.
- Question 10Mid
Which Swing methods are thread-safe?
- Java
Reveal answerHide answer
There are only three thread-safe methods: repaint, revalidate, invalidate.
- Question 10Mid
When is the finalize() called? What is the purpose of finalization?
- Java
Reveal answerHide answer
The finalize method is called by the garbage collector, just before releasing the object’s memory. It is normally advised to release resources held by the object inside the finalize method.
- Question 11Mid
How threadsafe is enum in Java?
- Java
Reveal answerHide answer
Creation of an enum is guaranteed to be threadsafe. However, the methods on an enum type are not necessarily threadsafe.
- Question 11Mid
What are the advantages of JSP?
- Java
Reveal answerHide answer
The advantages of using the JSP technology are shown below: JSP pages are dynamically compiled into servlets and thus, the developers can easily make updates to presentation code. JSP pages can be pre-compiled. JSP pages can be easily combined to static templates, including HTML or XML fragments, with code that generates dynamic content. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax. Developers can make logic changes at the component level, without editing the individual pages that use the application’s logic.
- Question 11Mid
Can you access non static variable in static context?
- Java
Reveal answerHide answer
A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.
- Question 11Mid
What’s the difference between Enumeration and Iterator interfaces?
- Java
Reveal answerHide answer
Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object that is currently traversed by the iterator. Also, Iterators allow the caller to remove elements from the underlying collection, something which is not possible with Enumeration.
- Question 12Mid
Is there anything like static class in Java?
- Java
Reveal answerHide answer
Java has no way of making a top-level class static but you can simulate a static class like this: Declare your class final - Prevents extension of the class since extending a static class makes no sense Make the constructor private - Prevents instantiation by client code as it makes no sense to instantiate a static class Make all the members and functions of the class static - Since the class cannot be instantiated no instance methods can be called or instance fields accessed Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member
- Question 12Mid
What are the restrictions imposed on Java applets?
- Java
Reveal answerHide answer
Mostly due to security reasons, the following restrictions are imposed on Java applets: An applet cannot load libraries or define native methods. An applet cannot ordinarily read or write files on the execution host. An applet cannot read certain system properties. An applet cannot make network connections except to the host that it came from. An applet cannot start any program on the host that’s executing it.
- Question 12Mid
What is difference between ArrayList and LinkedList ?
- Java
Reveal answerHide answer
Both the ArrayList and LinkedList classes implement the List interface, but they differ on the following features: An ArrayList is an index based data structure backed by an Array. It provides random access to its elements with a performance equal to O(1). On the other hand, a LinkedList stores its data as list of elements and every element is linked to its previous and next element. In this case, the search operation for an element has execution time equal to O(n). The Insertion, addition and removal operations of an element are faster in a LinkedList compared to an ArrayList, because there is no need of resizing an array or updating the index when an element is added in some arbitrary position inside the collection. A LinkedList consumes more memory than an ArrayList, because every node in a LinkedList stores two references, one for its previous element and one for its next element.
- Question 13Mid
Explain different ways of creating a thread. Which one would you prefer and why?
- Java
Reveal answerHide answer
There are three ways that can be used in order for a Thread to be created: A class may extend the Thread class. A class may implement the Runnable interface. An application can use the Executor framework, in order to create a thread pool. The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily.
- Question 13Mid
Why does Java have transient fields?
- Java
Reveal answerHide answer
The transient keyword in Java is used to indicate that a field should not be part of the serialization. By default, all of object's variables get converted into a persistent state. In some cases, you may want to avoid persisting some variables because you don't have the need to persist those variables. So you can declare those variables as transient. If the variable is declared as transient, then it will not be persisted .
- Question 13Mid
Explain the life cycle of an Applet.
- Java
Reveal answerHide answer
An applet may undergo the following states: Init: An applet is initialized each time is loaded.
Start: Begin the execution of an applet. Stop: Stop the execution of an applet. Destroy: Perform a final cleanup, before unloading the applet.
- Question 13Mid
Why Collection doesn’t extend Cloneable and Serializable interfaces?
- Java
Reveal answerHide answer
The Collection interface specifies groups of objects known as elements. Each concrete implementation of a Collection can choose its own way of how to maintain and order its elements. Some collections allow duplicate keys, while some other collections don’t. The semantics and the implications of either cloning or serialization
come into play when dealing with actual implementations. Thus, the concrete implementations of collections should decide how they can be cloned or serialized.
- Question 14Mid
What are the differences between == and equals ?
- Java
Reveal answerHide answer
As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals . When it is, however (such as with enum), there are two important differences to consider:
1. == never throws NullPointerException enum Color { BLACK, WHITE }; Color nothing = null; if (nothing == Color.BLACK); // runs fine if (nothing.equals(Color.BLACK)); // throws NullPointerEx 2. == is subject to type compatibility check at compile time enum Color { BLACK, WHITE }; enum Chiral { LEFT, RIGHT }; if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine if (Color.BLACK == Chiral.LEFT); // DOESN'T COMPILE!!! Incompatible types! - Question 14Mid
What's the advantage of using getters and setters?
- Java
Reveal answerHide answer
There are some: Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later. Hiding the internal representation of the property while exposing a property using an alternative representation. Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers. Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C). Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages. Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind. Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods. Allowing the getter/setter to be passed around as lambda expressions rather than values. Getters and setters can allow different access levels - for example the get may be public, but the set could be protected. Allowing lazy loading. Allowing copy on write.
- Question 14Mid
How does finally block differ from finalize() method?
- Java
Reveal answerHide answer
A finally block will be executed whether or not an exception is thrown and is used to release those resources held by the application. Finalize is a protected method of the Object class, which is called by the Java Virtual
Machine (JVM) just before an object is garbage collected. - Question 14Mid
What is a Constructor, Constructor Overloading and Copy- Constructor in Java ?
- Java
Reveal answerHide answer
A constructor gets invoked when a new object is created. Every class has a constructor. In case the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class. The constructor overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list. Finally, Java does support copy constructors like C++, but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own.
- Question 15Mid
What is meant by JSP implicit objects and what are they?
- Java
Reveal answerHide answer
JSP implicit objects are those Java objects that the JSP Container makes available to developers in each page. A developer can call them directly, without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.The following objects are considered implicit in a JSP page: application page request response session exception out config pageContext
- Question 15Mid
Can == be used on enum ?
- Java
Reveal answerHide answer
Yes: enums have tight instance controls that allows you to use == to compare instances. Here's the guarantee provided by the language specification.
- Question 15Mid
What is the difference between throw and throws ?
- Java
Reveal answerHide answer
The throw keyword is used to explicitly raise a exception within the program. On the contrary, the throws clause is used to indicate those exceptions that are not handled by a method. Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. Finally, multiple exceptions are separated by a comma.
- Question 16Mid
What is the advantage of PreparedStatement over Statement ?
- Java
Reveal answerHide answer
PreparedStatements are precompiled and thus, their performance is much better. Also, PreparedStatement objects can be reused with different input values to their queries.
- Question 16Mid
What is a JavaBean exactly?
- Java
Reveal answerHide answer
Basically, a "Bean" follows the standart: is a serializable object (that is, it implements java.io.Serializable , and does so correctly), that has "properties" whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the "Foo" property), and has a public 0-arg constructor (so it can be created at will and configured by setting its properties). There is no syntactic difference between a JavaBean and another class - a class is a JavaBean if it follows the standards.
- Question 16Mid
What is structure of Java Heap ?
- Java
Reveal answerHide answer
The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.
- Question 17Mid
What is Java Priority Queue?
- Java
Reveal answerHide answer
The PriorityQueue is an unbounded queue, based on a priority heap and its elements are ordered in their natural order. At the time of its creation, we can provide a Comparator that is responsible for ordering the elements of the PriorityQueue. A PriorityQueue doesn’t allow null values, those objects that doesn’t provide natural ordering, or those objects that don’t have any comparator associated with them. Finally, the Java PriorityQueue is not thread-safe and it requires O(log(n)) time for its enqueing and dequeing operations.
- Question 17Mid
What is the tradeoff between using an unordered array versus an ordered array?
- Java
Reveal answerHide answer
The major advantage of an ordered array is that the search times have time complexity of O(log n), compared to that of an unordered array, which is O (n). The disadvantage of an ordered array is that the insertion operation has a time complexity of O(n), because the elements with higher values must be moved to make room for the new element. Instead, the insertion operation for an unordered array takes constant time of O(1).
- Question 18Mid
What is difference between Array and ArrayList ? When will you use Array over ArrayList ?
- Java
Reveal answerHide answer
The Array and ArrayList classes differ on the following features: Arrays can contain primitive or objects, while an ArrayList can contain only objects. Arrays have fixed size, while an ArrayList is dynamic. An ArrayList provides more methods and features, such as addAll, removeAll, iterator, etc. For a list of primitive data types, the collections use autoboxing to reduce the coding effort. However, this approach makes them slower when working on fixed size primitive data types.
- Question 18Mid
What is the difference between public , protected , package- private and private in Java?
- Java
Reveal answerHide answer
Private - Like you'd think, only the class in which it is declared can see it Package Private - Can only be seen and used by the package in which it was declared. This is the default in
Java (which some see as a mistake)Protected - Package Private + can be seen by subclasses or package member Public - Everyone can see it
| │ Class │ Package │ Subclass │ Subclass │ World |
| │ │ │(same pkg)│(diff pkg)│ | |───────────┼───────┼─────────┼──────────┼──────────┼────────| |public │ + │ + │ + │ + │ + | |───────────┼───────┼─────────┼──────────┼──────────┼────────| |protected │ + │ + │ + │ + │ | |───────────┼───────┼─────────┼──────────┼──────────┼────────| |no modifier│ + │ + │ + │ │ | |───────────┼───────┼─────────┼──────────┼──────────┼────────| |private │ + │ │ │ │ | |___________|_______|_________|__________|__________|________| + : accessible blank : not accessible - Question 18Mid
What is Comparable and Comparator interface? List their differences.
- Java
Reveal answerHide answer
Java provides the Comparable interface, which contains only one method, called compareTo. This method compares two objects, in order to impose an order between them. Specifically, it returns a negative integer, zero, or a positive integer to indicate that the input object is less than, equal or greater than the existing object. Java provides the Comparator interface, which contains two methods, called compare and equals. The first method compares its two input arguments and imposes an order between them. It returns a negative integer, zero, or a positive integer to indicate that the first argument is less than, equal to, or greater than the second. The second method requires an object as a parameter and aims to decide whether the input object is equal to the comparator. The method returns true, only if the specified object is also a comparator and it imposes the same ordering as the comparator.
- Question 19Mid
What is the importance of hashCode() and equals() methods?
- Java
Reveal answerHide answer
A HashMap in Java uses the hashCode and equals methods to determine the index of the key-value pair. These methods are also used when we request the value of a specific key. If these methods are not implemented correctly, two different keys might produce the same hash value and thus, will be considered as equal by the collection. Furthermore, these methods are also used to detect duplicates. Thus, the implementation of both methods is crucial to the accuracy and correctness of the HashMap.
- Question 19Mid
How do I read/convert an InputStream into a String in Java?
- Java
Reveal answerHide answer
A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter like:
tringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString();or
// NB: does not close inputStream, you'll have to use try-with-resources for that String theString = IOUtils.toString(inputStream, encoding); - Question 19Mid
What differences exist between Iterator and ListIterator ?
- Java
Reveal answerHide answer
The differences of these elements are listed below: An Iterator can be used to traverse the Set and List collections, while the ListIterator can be used to iterate only over List . The Iterator can traverse a collection only in forward direction, while the ListIterator can traverse a List in both directions. The ListIterator implements the Iterator interface and contains extra functionality, such as adding an element, replacing an element, getting the index position for previous and next elements, etc
- Question 20Mid
What is difference between fail-fast and fail-safe?
- Java
Reveal answerHide answer
The Iterator's fail-safe property works with the clone of the underlying collection and thus, it is not affected by any modification in the collection. All the collection classes in java.util package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw a ConcurrentModificationException, while fail- safe iterator never throws such an exception.
- Question 20Mid
Is Java pass-by-reference or pass-by-value?
- Java
Reveal answerHide answer
Java is always pass-by-value. Unfortunately, when we pass the value of an object, we are passing the reference to it. There is no such thing as "pass-by-reference" in Java. This is confusing to beginners. The key to understanding this is that something like
Dog myDog; is not a Dog; it's actually a pointer to a Dog.So when you have
Dog myDog = new Dog("Rover"); foo(myDog);you're essentially passing the address of the created Dog object to the foo method.
- Question 20Mid
What’s a deadlock?
- Java
Reveal answerHide answer
A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly.
Senior questions
36 questions- Question 1Senior
Explain Marshalling and Demarshalling.
- Java
Reveal answerHide answer
When an application wants to pass its memory objects across a network to another host or persist it to storage, the in-memory representation must be converted to a suitable format. This process is called marshalling and the revert operation is called demarshalling.
- Question 1Senior
What is the difference between a synchronized method and asynchronized block?
- Java
Reveal answerHide answer
In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock).
- Question 2Senior
Are there any differences between Protocol in Swift vs Interface in Java?
- Java Swift
Reveal answerHide answer
Essentially protocols are very similar to Java interfaces except for: Swift protocols can also specify properties that must be implemented (i.e. fields) Swift protocols need to deal with value/reference through the use of the mutating keyword (because protocols can be implemented by structures, enumerations or classes). you can combine protocols at any point using "Protocol Composition". This replaces the older swift protocol<A, B> way of protocol composition. For example, declaring a function parameter that must adhere to protocol Named and Aged as: func wishHappyBirthday(to celebrator: Named & Aged) {}
- Question 2Senior
Explain the available thread states in a high-level.
- Java
Reveal answerHide answer
During its execution, a thread can reside in one of the following states: Runnable: A thread becomes ready to run, but does not necessarily start running immediately. Running: The processor is actively executing the thread code. Waiting: A thread is in a blocked state waiting for some external processing to finish. Sleeping: The thread is forced to sleep. Blocked on I/O: Waiting for an I/O operation to complete. Blocked on Synchronization: Waiting to acquire a lock. Dead: The thread has finished its execution.
- Question 3Senior
Explain Boyer-Moore Algorithm with Example
- Strings Java
Reveal answerHide answer
The insight behind Boyer-Moore is that if you start searching for a pattern in a string starting with the last character in the pattern, you can jump your search forward multiple characters when you hit a mismatch. Let's say our pattern p is the sequence of characters p1 , p2 , ..., pn and we are searching a string s , currently with p aligned so that pn is at index i in s . E.g.: s = WHICH FINALLY HALTS. AT THAT POINT... p = AT THAT
i = ^The B-M paper makes the following observations: (1) if we try matching a character that is not in p then we can jump forward n characters: 'F' is not in p , hence we advance n characters: s = WHICH FINALLY HALTS. AT THAT POINT... p = AT THAT
i = ^ (2) if we try matching a character whose last position is k from the end of p then we can jump forward k characters:' 's last position in p is 4 from the end, hence we advance 4 characters: s = WHICH FINALLY HALTS. AT THAT POINT... p = AT THAT
i = ^ Now we scan backwards from i until we either succeed or we hit a mismatch. (3a) if the mismatch occurs k characters from the start of p and the mismatched character is not in p , then we can advance (at least) k characters. 'L' is not in p and the mismatch occurred against p6 , hence we can advance (at least) 6 characters: s = WHICH FINALLY HALTS. AT THAT POINT... p = AT THAT i = ^ However, we can actually do better than this. (3b) since we know that at the old i we'd already matched some characters (1 in this case). If the matched characters don't match the start of p , then we can actually jump forward a little more (this extra distance is called 'delta2' in the paper): s = WHICH FINALLY HALTS. AT THAT POINT... p = AT THAT i = ^ At this point, observation (2) applies again, giving s = WHICH FINALLY HALTS. AT THAT POINT... p = AT THAT i = ^and bingo! We're done. Implementation: Java
public static int[] makeD1(char[] pat) { int[] table = new int[255]; for (int i = 0; i < 255; i++) table[i] = pat.length; for (int i = 0; i < pat.length - 1; i++) table[pat[i]] = pat.length - 1 - i; return table; } public static boolean isPrefix(char[] word, int pos) { int suffixlen = word.length - pos; for (int i = 0; i < suffixlen; i++) if (word[i] != word[pos + i]) return false; return true; } public static int suffix_length(char[] word, int pos) { int i; for (i = 0; ((word[pos - i] == word[word.length - 1 - i]) && (i < pos)); i++) {} return i; } public static int[] makeD2(char[] pat) { int[] delta2 = new int[pat.length]; int p; int last_prefix_index = pat.length - 1; for (p = pat.length - 1; p >= 0; p--) { if (isPrefix(pat, p + 1)) last_prefix_index = p + 1; delta2[p] = last_prefix_index + (pat.length - 1 - p); } for (p = 0; p < pat.length - 1; p++) { int slen = suffix_length(pat, p); if (pat[p - slen] != pat[pat.length - 1 - slen]) delta2[pat.length - 1 - slen] = pat.length - 1 - p + slen; } return delta2; } public static int bm(char[] string, char[] pat) { int[] d1 = makeD1(pat); int[] d2 = makeD2(pat); int i = pat.length - 1; while (i < string.length) { int j = pat.length - 1; while (j >= 0 && (string[i] == pat[j])) { i--; j--; } if (j < 0) return (i + 1); i += Math.max(d1[string[i]], d2[j]); } return -1; } - Question 4Senior
What is Perm Gen space in Heap ?
- Java
Reveal answerHide answer
Perm Gen stands for permanent generation. It is the space on Java Heap that holds meta-data describing user classes (classes that are not part of the Java language). Examples of such meta-data are objects describing classes and methods and they are stored in the Permanent Generation. Applications with large code-base can quickly fill up this segment of the heap which will cause java.lang.OutOfMemoryError: PermGen no matter how high your -Xmx (maximum size of the memory allocation pool) and how much memory you have on the machine.
- Question 5Senior
Given two double values d1 , d2 , what is the most reliable way to test their equality?
- Java
Reveal answerHide answer
The most accurate way to tell whether two double values are equal to one another is to use Double.compare() and test against 0, as in:
System.out.println(Double.compare(d1, d2) == 0); We can't use == because of Double.NaN (literally: “Not a Number”). Consider: final double d1 = Double.NaN; final double d2 = Double.NaN; System.out.println(d1 == d2); will print false . - Question 5Senior
What is the difference between Serial and Throughput Garbage collector?
- Java
Reveal answerHide answer
The throughput garbage collector uses a parallel version of the young generation collector and is meant to be used with applications that have medium to large data sets. On the other hand, the serial collector is usually adequate for most small applications (those requiring heaps of up to approximately 100MB on modern processors).
- Question 6Senior
Get Fibonacci Number in O( log n) time using Matrix Exponentiation
- Fibonacci Series Matrices Java
Reveal answerHide answer
The algorithm is based on this innocent-looking identity (which can be proven by mathematical induction): Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n)
Time complexity :
O( log n) . By halving the N value in every matrixPower's call to itself, we are halving the work needed to be done. Space complexity : O( log n) . The size of the stack in memory is proportionate to the function calls tomatrixPower plus the memory used to account for the matrices which takes up constant space. Implementation: Java
class Solution { int fib(int N) { if (N <= 1) { return N; } int[][] A = new int[][]{{1, 1}, {1, 0}}; matrixPower(A, N-1); return A[0][0]; } void matrixPower(int[][] A, int N) { if (N <= 1) { return; } matrixPower(A, N/2); multiply(A, A); int[][] B = new int[][]{{1, 1}, {1, 0}}; if (N%2 != 0) { multiply(A, B); } } void multiply(int[][] A, int[][] B) { int x = A[0][0] * B[0][0] + A[0][1] * B[1][0]; int y = A[0][0] * B[0][1] + A[0][1] * B[1][1]; int z = A[1][0] * B[0][0] + A[1][1] * B[1][0]; int w = A[1][0] * B[0][1] + A[1][1] * B[1][1]; A[0][0] = x; A[0][1] = y; A[1][0] = z; A[1][1] = w; } } PY class Solution: def fib(self, N: int) -> int: if (N <= 1):return N
A = [[1, 1], [1, 0]] self.matrix_power(A, N-1) return A[0][0] def matrix_power(self, A: list, N: int): if (N <= 1):return A
self.matrix_power(A, N//2) self.multiply(A, A) B = [[1, 1], [1, 0]] if (N%2 != 0): self.multiply(A, B) def multiply(self, A: list, B: list): x = A[0][0] * B[0][0] + A[0][1] * B[1][0] y = A[0][0] * B[0][1] + A[0][1] * B[1][1] z = A[1][0] * B[0][0] + A[1][1] * B[1][0] w = A[1][0] * B[0][1] + A[1][1] * B[1][1] A[0][0] = x A[0][1] = y A[1][0] = z A[1][1] = w - Question 7Senior
Explain a use case for the Builder Design Pattern
- Java
Reveal answerHide answer
The good example is a class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to N parameters, N-2 of which are just being passed into the super constructor. Instead of using a particular constructor with N params we could use the Builder Design Pattern. Consider the following example: public class StudentBuilder
{ private String _name; private int _age = 14; // this has a default private String _motto = ""; // most students don't have one public StudentBuilder() { } public Student buildStudent() { return new Student(_name, _age, _motto); } public StudentBuilder name(String _name) { this._name = _name; return this; } public StudentBuilder age(int _age) { this._age = _age; return this; } public StudentBuilder motto(String _motto) { this._motto = _motto; return this; } }This lets us write code like:
Student s1 = new StudentBuilder().name("Eli").buildStudent(); Student s2 = new StudentBuilder() .name("Spicoli") .age(16) .motto("Aloha, Mr Hand") .buildStudent(); - Question 7Senior
What is RMI?
- Java
Reveal answerHide answer
The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and distributed garbage collection. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object.
- Question 8Senior
Why is char[] preferred over String for passwords?
- Java
Reveal answerHide answer
Problem
Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[] ?
Solution
Strings are immutable. That means once you've created the String , if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before garbage collection kicks in. With an array , you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.
- Question 8Senior
Does Java support default parameter values?
- Java
Reveal answerHide answer
No. We can use overloading instead of default parameters like: public MyParameterizedFunction(String param1, int param2)
{ this(param1, param2, false); } public MyParameterizedFunction(String param1, int param2, boolean param3) { //use all three parameters here } - Question 8Senior
What is the role of Remote Interface in RMI?
- Java
Reveal answerHide answer
The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. A class that implements a remote interface should declare the remote interfaces being implemented, define the constructor for each remote object and provide an implementation for each remote method in all remote interfaces.
- Question 9Senior
How do I test a private function or a class that has private methods, fields or inner classes?
- Java
Reveal answerHide answer
Problem
How do I unit test (using xUnit) a class that has internal private methods, fields or nested classes?
Solution
The best way to test private methods is to use reflection. The following patterns will let you do pretty much anything related to the private methods and fields: Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true); return method.invoke(targetObject, argObjects);And for fields:
Field field = TargetClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(object, value); - Question 9Senior
What is the main difference between an inner class and astatic nested class in Java?
- Java
Reveal answerHide answer
In short nonstatic nested class can access instance of the container class, while static can't. A nested class could be nonstatic or static and in each case is a class defined within another class. A nested class should exist only to serve is enclosing class, if a nested class is useful by other classes (not only the enclosing), should be declared as a top level class.
Nonstatic Nested (Inner) class : is implicitly associated with the enclosing instance of the containing class, this means that it is possible to invoke methods and access variables of the enclosing instance. One common use of a nonstatic nested class is to define an Adapter class. Static Nested Class : can't access enclosing class instance and invoke methods on it, so should be used when the nested class doesn't require access to an instance of the enclosing class . A common use of static nested class is to implement a components of the outer object.
- Question 10Senior
Does Java support default parameter values?
- Java
Reveal answerHide answer
No. We can use overloading instead of default parameters like: public MyParameterizedFunction(String param1, int param2)
{ this(param1, param2, false); } public MyParameterizedFunction(String param1, int param2, boolean param3) { //use all three parameters here } - Question 10Senior
Why is Spring MVC better than Servlets / JSP ?
- Java
Reveal answerHide answer
Servlets are based upon a low-level API for handling requests and responses. Web frameworks like Spring MVC are designed to make building web applications, which handle HTTP requests and responses, easier. Most Java web frameworks, including Spring MVC, use servlets behind the scenes. Not necessarily 'better' but Spring MVC is essentially a higher level abstraction built on top of Java Servlets centered around the Model View Controller design pattern. This pattern promotes seperation of concerns when building your web application. The linch pin of the framework is the DispatcherServlet class which actually is a Servlet implementing the Front Controller design pattern.
- Question 10Senior
What is Double Brace initialization in Java?
- Java
Reveal answerHide answer
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{ add(1); add(2); }};However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.
- Question 11Senior
Given two double values d1 , d2 , what is the most reliable way to test their equality?
- Java
Reveal answerHide answer
The most accurate way to tell whether two double values are equal to one another is to use Double.compare() and test against 0, as in:
System.out.println(Double.compare(d1, d2) == 0); We can't use == because of Double.NaN (literally: “Not a Number”). Consider: final double d1 = Double.NaN; final double d2 = Double.NaN; System.out.println(d1 == d2); will print false . - Question 11Senior
How do you ensure that N threads can access N resources without deadlock?
- Java
Reveal answerHide answer
A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the mutexes in the same order, no deadlocks can arise.
- Question 12Senior
What is the purpose of using RMISecurityManager in RMI?
- Java
Reveal answerHide answer
RMISecurityManager provides a security manager that can be used by RMI applications, which use downloaded code. The class loader of RMI will not download any classes from remote locations, if the security manager has not been set.
- Question 12Senior
What exactly is marker interface in Java?
- Java
Reveal answerHide answer
The marker interface in Java is an interfaces with no field or methods. In other words, it an empty interface in java is called a marker interface. An example of a marker interface is a Serializable , Clonable and Remote interface. Marker interface is used as a tag to inform a message to the java compiler so that it can add special behaviour to the class implementing it.
- Question 13Senior
What is meant by binding in RMI?
- Java
Reveal answerHide answer
Binding is the process of associating or registering a name for a remote object, which can be used at a later time, in order to look up that remote object. A remote object can be associated with a name using the bind or rebind methods of the Naming class.
- Question 13Senior
Get Fibonacci Number in O( log n) time using Matrix Exponentiation
- Fibonacci Series Matrices Java
Reveal answerHide answer
Problem
The algorithm is based on this innocent-looking identity (which can be proven by mathematical induction): Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n) Time complexity :
O( log n) . By halving the N value in every matrixPower's call to itself, we are halving the work needed to be done. Space complexity : O( log n) . The size of the stack in memory is proportionate to the function calls tomatrixPower plus the memory used to account for the matrices which takes up constant space. Implementation: Java
class Solution { int fib(int N) { if (N <= 1) { return N; } int[][] A = new int[][]{{1, 1}, {1, 0}}; matrixPower(A, N-1); return A[0][0]; } void matrixPower(int[][] A, int N) { if (N <= 1) { return; } matrixPower(A, N/2); multiply(A, A); int[][] B = new int[][]{{1, 1}, {1, 0}}; if (N%2 != 0) { multiply(A, B); } } void multiply(int[][] A, int[][] B) { int x = A[0][0] * B[0][0] + A[0][1] * B[1][0]; int y = A[0][0] * B[0][1] + A[0][1] * B[1][1]; int z = A[1][0] * B[0][0] + A[1][1] * B[1][0]; int w = A[1][0] * B[0][1] + A[1][1] * B[1][1]; A[0][0] = x; A[0][1] = y; A[1][0] = z; A[1][1] = w; } } PY class ### Solution def fib(self, N: int) -> int: if (N <= 1):return N
A = [[1, 1], [1, 0]] self.matrix_power(A, N-1) return A[0][0] def matrix_power(self, A: list, N: int): if (N <= 1):return A
self.matrix_power(A, N//2) self.multiply(A, A) B = [[1, 1], [1, 0]] if (N%2 != 0): self.multiply(A, B) def multiply(self, A: list, B: list): x = A[0][0] * B[0][0] + A[0][1] * B[1][0] y = A[0][0] * B[0][1] + A[0][1] * B[1][1] z = A[1][0] * B[0][0] + A[1][1] * B[1][0] w = A[1][0] * B[0][1] + A[1][1] * B[1][1] A[0][0] = x A[0][1] = y A[1][0] = z A[1][1] = w - Question 14Senior
What is the role of the java.rmi.Naming Class?
- Java
Reveal answerHide answer
The java.rmi.Naming class provides methods for storing and obtaining references to remote objects in the remote object registry. Each method of the Naming class takes as one of its arguments a name that is a String in URL format.
- Question 15Senior
What are some of the best practices relating to the Java Collection Framework?
- Java
Reveal answerHide answer
Choosing the right type of the collection to use, based on the application’s needs, is very crucial for its performance. For example if the size of the elements is fixed and know a priori, we shall use an Array, instead of an ArrayList. Some collection classes allow us to specify their initial capacity. Thus, if we have an estimation on the number of elements that will be stored, we can use it to avoid rehashing or resizing. Always use Generics for type-safety, readability, and robustness. Also, by using Generics you avoid the ClassCastException during runtime. Use immutable classes provided by the Java Development Kit (JDK) as a key in a Map, in order to avoid the implementation of the hashCode and equals methods for our custom class. Program in terms of interface not implementation. Return zero-length collections or arrays as opposed to returning a null in case the underlying collection is actually empty.
- Question 15Senior
What is the basic principle of RMI architecture?
- Java
Reveal answerHide answer
The RMI architecture is based on a very important principle which states that the definition of the behavior and the implementation of that behavior, are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs.
- Question 16Senior
How do you find out what client machine is making a request to your servlet?
- Java
Reveal answerHide answer
The ServletRequest class has functions for finding out the IP address or host name of the client machine. getRemoteAddr() gets the IP address of the client machine and getRemoteHost() gets the host name of the client machine. See example here.
- Question 17Senior
What are the differences between a HashMap and a HashTable in Java?
- Java
Reveal answerHide answer
There are several differences between HashMap and Hashtable in Java:
- Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
- Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
- One of HashMap's subclasses is LinkedHashMap , so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn't be as easy if you were using Hashtable .
- Question 17Senior
What is Servlet Chaining?
- Java
Reveal answerHide answer
Servlet Chaining is the method where the output of one servlet is sent to a second servlet. The output of the second servlet can be sent to a third servlet, and so on. The last servlet in the chain is responsible for sending the response to the client.
- Question 18Senior
When to use LinkedList over ArrayList in Java?
- Java
Reveal answerHide answer
LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but finding a position in the list takes time proportional to the size of the list. ArrayList , on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.
- Question 18Senior
What does Connection Pooling mean?
- Java
Reveal answerHide answer
The interaction with a database can be costly, regarding the opening and closing of database connections. Especially, when the number of database clients increases, this cost is very high and a large number of resources is consumed.A pool of database connections is obtained at start up by the application server and is maintained in a pool. A request for a connection is served by a connection residing in the pool. In the end of the connection, the request is returned to the pool and can be used to satisfy future requests.
- Question 19Senior
What is the applet class loader, and what does it provide?
- Java
Reveal answerHide answer
When an applet is loaded over the internet, the applet is loaded by the applet classloader. The class loader enforces the Java name space hierarchy. Also, the class loader guarantees that a unique namespace exists for classes that come from the local file system, and that a unique namespace exists for each network source. When a browser loads an applet over the net, that applet’s classes are placed in a private namespace associated with the applet’s origin. Then, those classes loaded by the class loader are passed through the verifier.The verifier checks that the class file conforms to the Java language specification . Among other things, the verifier ensures that there are no stack overflows or underflows and that the parameters to all bytecode instructions are correct.
- Question 20Senior
What exactly is marker interface in Java?
- Java
Reveal answerHide answer
The marker interface in Java is an interfaces with no field or methods. In other words, it an empty interface in java is called a marker interface. An example of a marker interface is a Serializable , Clonable and Remote interface. Marker interface is used as a tag to inform a message to the java compiler so that it can add special behaviour to the class implementing it.
- Question 20Senior
What is the difference between Applets loaded over the internet and Applets loaded via the file system?
- Java
Reveal answerHide answer
Regarding the case where an applet is loaded over the internet, the applet is loaded by the applet classloader and is subject to the restrictions enforced by the applet security manager. Regarding the case where an applet is loaded from the client’s local disk, the applet is loaded by the file system loader. Applets loaded via the file system are allowed to read files, write files and to load libraries on the client. Also, applets loaded via the file system are allowed to execute processes and finally, applets loaded via the file system are not passed through the byte code verifier.
Expert questions
15 questions- Question 1Expert
Why ArrayList are preferable in many more use-cases than LinkedList ?
- Java
Reveal answerHide answer
LinkedList is almost always a (performance) bug: It uses lots of small memory objects, and therefore impacts performance across the process. Lots of small objects are bad for cache-locality. Any indexed operation requires a traversal, i.e. has O(n) performance. This is not obvious in the source code, leading to algorithms O(n) slower than if ArrayList was used. Getting good performance is tricky. Even when big-O performance is the same as ArrayList , it is probably going to be significantly slower anyway. It's jarring to see LinkedList in source because it is probably the wrong choice.
- Question 3Expert
What is an efficient way to implement a singleton pattern in Java?
- Java
Reveal answerHide answer
Since java5 use an enum :
public enum Elvis { INSTANCE; private final String[] favoriteSongs = { "Hound Dog", "Heartbreak Hotel" }; public void printFavorites() { System.out.println(Arrays.toString(favoriteSongs)); } }This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton. Pre java5, the most simple case is:
public final class Foo { private static final Foo INSTANCE = new Foo(); private Foo() { if (INSTANCE != null) { throw new IllegalStateException("Already instantiated"); } } public static Foo getInstance() { return INSTANCE; } public Object clone() throws CloneNotSupportedException{ throw new CloneNotSupportedException("Cannot clone instance of this class"); } } - Question 4Expert
What's the difference between SoftReference and WeakReference in Java?
- Java
Reveal answerHide answer
A Strong reference is a normal reference that protects the referred object from collection by GC. i.e. Never garbage collects. A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError . A Weak reference is a reference that does not protect a referenced object from collection by GC. i.e. garbage collects when no Strong or Soft refs. A Phantom reference is a reference to an object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed.
- Question 5Expert
Compare volatile vs static variables in Java
- Java
Reveal answerHide answer
Declaring a static variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no Objects created at all. However, threads may have locally cached values of it.
When a variable is volatile and not static, there will be one variable for each Object . So, on the surface it seems there is no difference from a normal variable but totally different from static. However, even with Object fields, a thread may cache a variable value locally. This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the thread has in cache an old value. Even if you access a static value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value.
- Question 11Expert
What is Morris Traversal for a Tree and how to implement one?
- Binary Tree Java
Reveal answerHide answer
Morris (In-Order) traversal is a tree traversal algorithm that does not employ the use of recursion or a stack. In this traversal, links are created as successors and nodes are printed using these links. Finally, the changes are reverted back to restore the original tree. Basically a tree is threaded by making all right child pointers that would normally be null point to the inorder successor of the node (if it exists), and all left child pointers that would normally be null point to the inorder predecessor of the node. Consider:
C E H A D I B G F Algorithm: Initialize the root as the current node curr . While curr is not NULL , check if curr has a left child. If curr does not have a left child, print curr and update it to point to the node on the right of curr . Else, make curr the right child of the rightmost node in curr 's left subtree. Update curr to this left node. Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) The way of looking at time complexity is to find out how many times a tree node will be traversed. As it is constant (3 times for a binary tree). So we are looking at O(n) . Implementation: Java
public class MorrisPreorderTraversal { static class Node { //static class to represent node structure int data; //to store data of each node Node left, right; //to point to left and right child of the node respectively Node(int d) { //constructor for initialisation of each values this.data = d; this.left = null; this.right = null; } } public static void printPreorder(Node root) { if (root == null) { //if tree is empty return; } while (root != null) { if (root.left == null) { //if left child is empty System.out.print(root.data + " "); //traverse current node and root = root.right; //move to it's right } else { Node curr = root.left; //to store inorder predecessor while (curr.right != null && curr.right != root) { curr = curr.right; } if (curr.right == root) { //if right child of inorder predecessor points to root node itself curr.right = null; root = root.right; } else { //otherwise System.out.print(root.data + " "); //traverse current node curr.right = root; //make right child of inorder predecessor point to this node root = root.left; } } } } public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); printPreorder(root); } }/* -:Sample Input Tree:- 1 / \ 2 3 / \ / \ 4 5 6 7 -:Sample Output:- 1 2 4 5 3 6 7 -:Time Complexity:- O(n) where n is the number of nodes in the given tree -:Space Complexity:- O(1) */ - Question 12Expert
Why isn’t String‘s length() accurate?
- Java
Reveal answerHide answer
It isn’t accurate because it will only account for the number of characters within the String . In other words, it will fail to account for code points outside of what is called the BMP (Basic Multilingual Plane), that is, code points with a value of U+10000 or greater. The reason is historical: when Java was first defined, one of its goal was to treat all text as Unicode; but at this time, Unicode did not define code points outside of the BMP. By the time Unicode defined such code points, it was too late for char to be changed. The correct way to count the real numbers of characters within a String, i.e. the number of code points, is either:
someString.codePointCount(0, someString.length()) // or, with Java 8: someString.codePoints().count() - Question 13Expert
Provide some examples when a finally block won't be executed in Java?
- Java
Reveal answerHide answer
Usually, finally will be called after the execution of the try or catch code blocks. The only times finally won't be called are:
1. If you invoke System.exit() 2. If the JVM crashes first 3. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block 4. If the OS forcibly terminates the JVM process; e.g., kill -9 <pid> on UNIX 5. If the host system dies; e.g., power failure, hardware error, OS panic, et cetera- If the finally block is going to be executed by a daemon thread and all other non-daemon threads exit before finally is called
- Question 14Expert
What's wrong with Double Brace Initialization in Java?
- Java
Reveal answerHide answer
Using Double Brace initialization is not ideal because:
- You're creating way too many anonymous classes. For example:
Map source = new HashMap(){{ put("firstName", "John"); put("lastName", "Smith"); put("organizations", new HashMap(){{ put("0", new HashMap(){{ put("id", "1234"); }}); put("abc", new HashMap(){{ put("id", "5678"); }}); }}); }};... will produce these classes: Test$1$1$1.class Test$1$1$2.class Test$1$1.class Test$1.class Test.class
That's quite a bit of overhead for your classloader - for nothing! 2. You're potentially creating a memory leak. If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected.
- Question 14Expert
Compare volatile vs static variables in Java
- Java
Reveal answerHide answer
Declaring a static variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no Objects created at all. However, threads may have locally cached values of it. When a variable is volatile and not static, there will be one variable for each Object . So, on the surface it seems there is no difference from a normal variable but totally different from static. However, even with Object fields, a thread may cache a variable value locally. This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the thread has in cache an old value. Even if you access a static value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value.
- Question 15Expert
What does synchronized mean?
- Java
Reveal answerHide answer
The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources. The synchronized keyword is one of the tools that make your code thread safe. synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. Synchronized methods can't be called in the same time from multiple threads. So simply speaking when you have two threads that are reading and writing to the same 'resource', say a variable named foo , you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to foo , or worse, it may only be half changed. This would not be what you logically expect.
- Question 16Expert
What is DGC? And how does it work?
- Java
Reveal answerHide answer
DGC stands for Distributed Garbage Collection. Remote Method Invocation (RMI) uses DGC for automatic garbage collection. Since RMI involves remote object references across JVM’s, garbage collection can be quite difficult. DGC uses a reference counting algorithm to provide automatic memory management for remote objects.
- Question 17Expert
What are the layers of RMI Architecture?
- Java
Reveal answerHide answer
The RMI architecture consists of the following layers: Stub and Skeleton layer: This layer lies just beneath the view of the developer. This layer is responsible for intercepting method calls made by the client to the interface and redirect these calls to a remote RMI Service. Remote Reference Layer: The second layer of the RMI architecture deals with the interpretation of references made from the client to the server’s remote objects. This layer interprets and manages references made from clients to the remote service objects. The connection is a one-to-one (unicast) link. Transport layer: This layer is responsible for connecting the two JVM participating in the service. This layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.
- Question 18Expert
Does Garbage collection occur in permanent generation space in JVM?
- Java
Reveal answerHide answer
Garbage Collection does occur in PermGen space and if PermGen space is full or cross a threshold, it can trigger a full garbage collection. If you look carefully at the output of the garbage collector, you will find that PermGen space is also garbage collected. This is the reason why correct sizing of PermGen space is important to avoid frequent full garbage collections.
- Question 19Expert
What is the difference between HashSet and TreeSet ?
- Java
Reveal answerHide answer
The HashSet is Implemented using a hash table and thus, its elements are not ordered. The add, remove, and contains methods of a HashSet have constant time complexity O(1). On the other hand, a TreeSet is implemented using a tree structure. The elements in a TreeSet are sorted, and thus, the add, remove, and contains methods have time complexity of O(logn).
- Question 20Expert
How does thread synchronization occurs inside a monitor ? What levels of synchronization can you apply?
- Java
Reveal answerHide answer
The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock.