All topics

Java interview questions

201 questions, 159 with answers. 2,694 open jobs in India ask for Java.

  1. Explain: ArrayList vs LinkedList

    ArrayList vs LinkedList

    Internally, ArrayList is using an array to implement the List interface. As arrays are fixed size in Java, ArrayList creates an array with some initial capacity. Along the way, if we need to store more items than that default capacity, it will replace that array with a new and more spacious one. When more and more elements are added into an ArrayList, the capacity of the underlying array grows 50% of its size each time. Internally, a new array which is 1.5 times the size the original array is allocated, and the old array is copied to the new one.

    LinkedList, as its name suggests, uses a collection of linked nodes to store and retrieve elements. Each node maintains two pointers: one pointing to the next element and another referring to the previous one. LinkedList allows for constant-time insertions or removals using iterators. However, it allows only sequential access of elements.

    Comparing ArrayList and LinkedList

    Both ArrayList and LinkedList are similar to use. The main difference is their implementation that gives different performances in different operations. The major differences between the two are:

    • Random access of elements: ArrayList allows fast and random access of elements as it is essentially an array that works on index basis. Its elements can be directly accessed using the get and set methods. Whereas in LinkedList, finding an element’s position in the list takes time proportional to the size of the list. Any indexed operation requires a traversal.
    • Random insertion and deletion: As LinkedList uses doubly linked list, it takes constant time for insertions or removals as it does not require bit shifting in memory. On the other hand, adding or removing anywhere from an ArrayList except at the end requires shifting all the latter elements over, either to make an opening or fill to the gap.
    • Insertion and deletion from head: Inserting or deleting elements from the head is cheaper in LinkedList than ArrayList.
    • Queue functionality: ArrayList can act only as list but LinkedList can act both as list and queue as it implements the List and Deque interfaces.
    • Memory overhead: Memory overhead in LinkedList is more as compared to ArrayList as a node in LinkedList needs to maintain the addresses of next and previous nodes. Whereas an ArrayList doesn’t have this overhead as in an ArrayList each index only holds the actual object (data).
    • Size: An ArrayList take up as much memory as is allocated for the capacity, regardless of whether elements have actually been added or not. The default initial capacity of an ArrayList is pretty small. But since the underlying implementation is an array, the array must be resized if you add a lot of elements. To avoid the high cost of resizing, when you know you’re going to add a lot of elements, construct the ArrayList with a higher initial capacity.
    • Reverse iterator: LinkedList can be iterated in reverse direction using descendingIterator() while there is no descendingIterator() in ArrayList. For reverse iteration, you need to write your own implementation code.

    This table shows the time complexity comparisons between various ArrayList and LinkedList operations using Big O notation.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  2. Can a constructor be inherited

    Constructor inherited

    Short answer - no, a constructor cannot be inherited. Reasons:

    • Constructors are special and have same name as class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name
    • A constructor cannot be called as a method. It is called when object of the class is created so it does not make sense of creating child class object using parent class constructor notation. i.e. Child c = new Parent();
    • If constructors can be inherited then it will be impossible to achieving encapsulation. Because by using a super class’s constructor we can access/initialize private members of a class.

    Links

    https://www.geeksforgeeks.org/constructors-not-inherited-java/
    https://stackoverflow.com/questions/18147768/why-constructors-can-not-be-inherited-in-java

    From Android Interview Questions (Apache 2.0)

  3. Can a static method be overridden

    No it can’t. Because the idea of overridden is to get different behavior for children during inherence, but static method is not method of instance it’s method of class.

    From Android Interview Questions (Apache 2.0)

  4. Explain: Comparable interface in java

    Java Comparable interface is used to compare objects and sort them according to the natural order.

    Natural ordering is referred to as its compareTo() function. The String objects are sorted lexicographically, and the wrapper class objects are sorted according to their built-in compareTo() function (like how Integers objects are sorted in ascending order)

    compareTo() The compareTo() function compares the current object with the provided object.This function is already implemented for default wrapper classes and primitive data types; but, this function also​ needs to be implemented for user-defined classes. It returns:

    1. a positive integer, if the current object is greater than the provided object.

    2. a negative integer, if the current object is less than the provided object.

    3. zero, if the current object is equal to the provided object.

    Example Sorting string

    ArrayList<String> list = new ArrayList<>();
    list.add("E");
    list.add("A");
    list.add("C");
    list.add("B");
    list.add("D");
    Collections.sort(list);
    System.out.println(list); // [A, B, C, D, E]
    

    Sorting user defined objects

    class Employee implements Comparable<Employee> {
        private String name;
        private int age;
        Employee(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public int compareTo(Employee employee) {
            if (this.age == employee.age)
                return 0;
            else if (this.age > employee.age)
                return 1;
            else
                return -1;
        }
        @Override
        public String toString() {
            return "[name=" + this.name + ", age=" + this.age +"]";
        }
    }
    

    ==========================================================

    List<Employee> employeeList = new ArrayList<Employee>();
    employeeList.add(new Employee("Emp1", 25));
    employeeList.add(new Employee("Emp2", 10));
    System.out.println(employeeList);    // [[name=Emp1, age=25], [name=Emp2, age=10]]
    Collections.sort(employeeList);    
    System.out.println(employeeList); // [[name=Emp2, age=10], [name=Emp1, age=25]]
    

    From Android Interview Questions (Apache 2.0)

  5. Describe Deque interface from java collection

    Deque interface

    public interface Deque<E> extends Queue<E>
    

    A linear collection that supports element insertion and removal at both ends. The name deque is short for "double ended queue" and is usually pronounced "deck". Most Deque implementations place no fixed limits on the number of elements they may contain, but this interface supports capacity-restricted deques as well as those with no fixed size limit.

    This interface defines methods to access the elements at both ends of the deque. Methods are provided to insert, remove, and examine the element. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Deque implementations; in most implementations, insert operations cannot fail.

    The twelve methods described above are summarized in the following table:

    **First Element (Head)**
    **Last Element (Tail)**
    *Throws exception*
    *Special value*
    *Throws exception*
    *Special value*
    **Insert**
    `addFirst(e)`
    `offerFirst(e)`
    `addLast(e)`
    `offerLast(e)`
    **Remove**
    `removeFirst()`
    `pollFirst()`
    `removeLast()`
    `pollLast()`
    **Examine**b>
    `getFirst()`
    `peekFirst()`
    `getLast()`
    `peekLast()`
    

    This interface extends the Queue interface. When a deque is used as a queue, FIFO (First-In-First-Out) behavior results. Elements are added at the end of the deque and removed from the beginning. The methods inherited from the Queue interface are precisely equivalent to Deque methods as indicated in the following table:

    Queue Method Equivalent Deque Method
    add(e) addLast(e)
    offer(e) offerLast(e)
    remove() removeFirst()
    poll() pollFirst()
    element() getFirst()
    peek() peekFirst()

    Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class. When a deque is used as a stack, elements are pushed and popped from the beginning of the deque. Stack methods are precisely equivalent to Deque methods as indicated in the table below:

    Stack Method Equivalent Deque Method
    push(e) addFirst(e)
    pop() removeFirst()
    peek() peekFirst()
    poll() pollFirst()
    element() getFirst()
    peek() peekFirst()

    Note that the peek method works equally well when a deque is used as a queue or a stack; in either case, elements are drawn from the beginning of the deque.

    Unlike the List interface, this interface does not provide support for indexed access to elements.

    While Deque implementations are not strictly required to prohibit the insertion of null elements, they are strongly encouraged to do so. Users of any Deque implementations that do allow null elements are strongly encouraged not to take advantage of the ability to insert nulls. This is so because null is used as a special return value by various methods to indicated that the deque is empty.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  6. Describe List interface

    List interface

    A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for the following:

    • Positional access — manipulates elements based on their numerical position in the list. This includes methods such as get, set, add, addAll, and remove.
    • Search - searches for a specified object in the list and returns its numerical position. Search methods include indexOf and lastIndexOf.
    • Iteration — extends Iterator semantics to take advantage of the list's sequential nature. The listIterator methods provide this behavior.
    • Range-view — The sublist method performs arbitrary range operations on the list.

    The Java platform contains two general-purpose List implementations. ArrayList, which is usually the better-performing implementation, and LinkedList which offers better performance under certain circumstances.

    Like the Set interface, List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. Two List objects are equal if they contain the same elements in the same order.

    Most used Implementing Classes

    • ArrayList. Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
    • LinkedList. Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null). All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
    • Vector. The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. Vectors basically fall in legacy classes but now it is fully compatible with collections.
    • Stack. The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top. When a stack is first created, it contains no items.

    Iterators

    Iterator returned by List's iterator operation returns the elements of the list in proper sequence. List also provides a richer iterator, called a ListIterator, which allows you to traverse the list in either direction, modify the list during iteration, and obtain the current position of the iterator.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  7. Describe Queue interface from java collection

    Queue interface

    public interface Queue<E> extends Collection<E>
    

    A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.

    Concurrency Throws exception Returns special value
    Insert add(e) offer(e)
    Remove remove() poll()
    Examine element() peek()

    Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out). Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.1

    The Queue interface does not define the blocking queue methods, which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the BlockingQueue interface, which extends this interface.

    Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList, do not prohibit insertion of null. Even in the implementations that permit it, null should not be inserted into a Queue, as null is also used as a special return value by the poll method to indicate that the queue contains no elements.

    Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object, because element-based equality is not always well-defined for queues with the same elements but different ordering properties.2

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  8. Describe map interface from java collection

    Map interface

    An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

    This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

    The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

    Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

    The "destructive" methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be "superimposed" is empty.

    Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

    Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: "returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))." This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  9. Describe set interface from java collection

    Set interface

    A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

    The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add, equals and hashCode methods. Declarations for other inherited methods are also included here for convenience. (The specifications accompanying these declarations have been tailored to the Set interface, but they do not contain any additional stipulations.)

    The additional stipulation on constructors is, not surprisingly, that all constructors must create a set that contains no duplicate elements (as defined above).

    Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.

    Some set implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the set may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

    Most used implementing classes

    • HashSet. This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

    • TreeSet. TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

    • LinkedHashSet. Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  10. What is the difference between Semaphore and Monitor?

    Semaphore vs Monitor

    Both semaphores and monitors are used to solve the critical section problem (as they allow processes to access the shared resources in mutual exclusion) and to achieve process synchronization in the multiprocessing environment.

    Monitor type high-level synchronization construct. It is an abstract data type. The Monitor type contains shared variables and the set of procedures that operate on the shared variable.

    When any process wishes to access the shared variables in the monitor, it needs to access it through the procedures. These processes line up in a queue and are only provided access when the previous process release the shared variables. Only one process can be active in a monitor at a time. Monitor has condition variables.

    Semaphore (java.util.concurrent.Semaphore) used for limit the number of threads accessing a specific resource. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

    Advantages of Monitors:

    • Monitors are easy to implement than semaphores;
    • Mutual exclusion in monitors is automatic while in semaphores, mutual exclusion needs to be implemented explicitly;
    • Monitors can overcome the timing errors that occur while using semaphores;
    • Shared variables are global to all processes in the monitor while shared variables are hidden in semaphores.

    Advantages of Semaphores:

    • Semaphores are machine independent (because they are implemented in the kernel services).
    • Semaphores permit more than one thread to access the critical section, unlike monitors.
    • In semaphores there is no spinning, hence no waste of resources due to no busy waiting.

    Links

    https://www.geeksforgeeks.org/monitor-vs-semaphore/
    https://stackoverflow.com/questions/7335950/semaphore-vs-monitors-whats-the-difference

    From Android Interview Questions (Apache 2.0)

  11. What is the difference between int and Integer?

    int vs Integer

    int is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer. To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability. The automatic conversion of primitive data types into its equivalent Wrapper type is known as autoboxing and opposite operation is known as unboxing.

    Autoboxing:

    Converting a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value is:

    • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
    • Assigned to a variable of the corresponding wrapper class.

    Unboxing:

    Converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example conversion of Integer to int. The Java compiler applies unboxing when an object of a wrapper class is:

    • Passed as a parameter to a method that expects a value of the corresponding primitive type.
    • Assigned to a variable of the corresponding primitive type.

    Links

    https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html http://illegalargumentexception.blogspot.com/2008/08/java-int-versus-integer.html https://www.geeksforgeeks.org/autoboxing-unboxing-java/

    From Android Interview Questions (Apache 2.0)

  12. What is the difference between static and regular nested classes?

    Inner classes vs Static nested classes

    The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:

    class OuterClass {
        ...
        class NestedClass {
            ...
        }
    }
    

    Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.

    Example:

    class OuterClass {
        ...
        static class StaticNestedClass {
            ...
        }
        class InnerClass {
            ...
        }
    }
    

    A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)

    Why Use Nested Classes?

    Compelling reasons for using nested classes include the following:

    • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
    • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
    • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

    Static Nested Classes

    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.

    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

    Static nested classes are accessed using the enclosing class name: OuterClass.StaticNestedClass

    For example, to create an object for the static nested class, use this syntax: OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

    Inner Classes

    As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

    Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

    class OuterClass {
        ...
        class InnerClass {
            ...
        }
    }
    

    An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  13. Explain: Different between Array and ArrayList
    • Resizable: Array is static in size that is fixed length data structure, one cannot change the length after creating the Array object. ArrayList is dynamic in size. Each ArrayList object has instance variable capacity which indicates the size of the ArrayList. As elements are added to an ArrayList its capacity grows automatically.

    • Performance: Performance of Array and ArrayList depends on the operation you are performing:

    1. resize() opertation : Automatic resize of ArrayList will slow down the performance as it will use temporary array to copy elements from the old array to new array. ArrayList is internally backed by Array during resizing as it calls the native implemented method System.arrayCopy(src,srcPos,dest,destPos,length).
    2. add() or get() operation : adding an element or retrieving an element from the array or arraylist object has almost same performance , as for ArrayList object these operations run in constant time.
    • Primitives: ArrayList cannot contains primitive data types (like int, float, double) it can only contains Object while Array can contain both primitive data types as well as objects. One get a misconception that we can store primitives(int,float,double) in ArrayList , but it is not true

    • Type-Safety: In Java, one can ensure Type Safety through Generics. while Array is a homogeneous data structure, thus it will contain objects of specific class or primitives of specific data type. In array if one tries to store the different data type other than the specified while creating the array object, ArrayStoreException is thrown.

    • Multi-dimensional: Array can be multi-dimensional, while ArrayList is always single dimensional.

    • Adding elements: We can insert elements into the ArrayList object using the add() method while in array we insert elements using the assignment operator.

    From Android Interview Questions (Apache 2.0)

  14. Do objects get passed by reference or value

    Do objects get passed by reference or value?

    The two most prevalent modes of passing arguments to methods are “passing-by-value” and “passing-by-reference”. Different programming languages use these concepts in different ways. As far as Java is concerned, everything is strictly Pass-by-Value.

    The fundamental concepts in any programming language are “values” and “references”. In Java, Primitive variables store the actual values, whereas Non-Primitives store the reference variables which point to the addresses of the objects they're referring to. Both values and references are stored in the stack memory.

    Arguments in Java are always passed-by-value. During method invocation, a copy of each argument, whether its a value or reference, is created in stack memory which is then passed to the method.

    In case of primitives, the value is simply copied inside stack memory which is then passed to the callee method; in case of non-primitives, a reference in stack memory points to the actual data which resides in the heap. When we pass an object, the reference in stack memory is copied and the new reference is passed to the method.

    Passing Primitive Types

    The Java Programming Language features eight primitive data types. Primitive variables are directly stored in stack memory. Whenever any variable of primitive data type is passed as an argument, the actual parameters are copied to formal arguments and these formal arguments accumulate their own space in stack memory.

    The lifespan of these formal parameters lasts only as long as that method is running, and upon returning, these formal arguments are cleared away from the stack and are discarded.

    Example:

    public class PrimitiveTypesExample {
        public void example() {
            int x1 = 1;
            int x2 = 2;
            System.out.println("Before:");
            System.out.println("X1 = " + x1);
            System.out.println("X2 = " + x2);
            modify(x1, x2);
            System.out.println("After:");
            System.out.println("X1 = " + x1);
            System.out.println("X2 = " + x2);
        }
        private void modify(int x1, int x2) {
            x1 = x1 + 100;
            x2 = x2 + 200;
        }
    }
    

    Output:

    Before:
    X1 = 1
    X2 = 2
    After:
    X1 = 1
    X2 = 2
    

    Passing Object References

    In Java, all objects are dynamically stored in Heap space under the hood. These objects are referred from references called reference variables.

    Whenever an object is passed as an argument, an exact copy of the reference variable is created which points to the same location of the object in heap memory as the original reference variable.

    As a result of this, whenever we make any change in the same object in the method, that change is reflected in the original object. However, if we allocate a new object to the passed reference variable, then it won't be reflected in the original object.

    Example:

    public class NumberHolder {
        private int num;
        NumberHolder(int num) {
            this.num = num;
        }
        public void increment() {
            num = num++;
        }
        public int getValue() {
            return num;
        }
    }
    

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  15. Explain: Exception. Checked and Unchecked.

    Exception. Checked vs Unchecked.

    An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

    In Java, there are two types of exceptions: Checked and Unchecked.

    Checked

    Checked are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

    Example:

    private static void checkedExceptionWithThrows() throws FileNotFoundException {
        File file = new File("not_existing_file.txt");  
        FileInputStream stream = new FileInputStream(file);  
    }
    

    We can also use a try-catch block to handle a checked exception:

    private static void checkedExceptionWithTryCatch() {
        File file = new File("not_existing_file.txt");
        try {
            FileInputStream stream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    

    Unchecked

    An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.

    Example:

    private static void divideByZero() {
        int numerator = 1;
        int denominator = 0;
        int result = numerator / denominator;
    }
    

    Here code will throw ArithmeticException at runtime, cause divide by 0.

    Exception hierarchy

    All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

    Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.

    The Exception class has two main subclasses: IOException class and RuntimeException Class.

    Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

    Links

    https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
    https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
    https://www.baeldung.com/java-checked-unchecked-exceptions
    https://www.tutorialspoint.com/java/java_exceptions.htm
    https://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml

    From Android Interview Questions (Apache 2.0)

  16. Explain: HashSet vs TreeSet

    HashSet vs TreeSet

    HashSet class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

    This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets).

    TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

    TreeSet is basically an implementation of a self-balancing binary search tree like a Red-Black Tree. Therefore operations like add, remove, and search take O(log(n)) time. The reason is that in a self-balancing tree, it is made sure that the height of the tree is always O(log(n)) for all the operations. Therefore, this is considered as one of the most efficient data structure in order to store the huge sorted data and perform operations on it. However, operations like printing N elements in the sorted order takes O(n) time.

    Property HashSet TreeSet
    Ordering Does not maintain any order Maintains an object in sorted order
    Comprasion Uses equals() method Uses compareTo() method
    Data structure Implemented using HashTable Implemented using a tree structure
    Null element Allowed Not allowed
    Performance Time complexity average - O(1) Guaranteed O(log(n)) time cost for the basic operations

    Links

    https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
    https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
    https://www.geeksforgeeks.org/hashset-in-java/
    https://www.geeksforgeeks.org/treeset-in-java-with-examples/
    https://www.geeksforgeeks.org/hashset-vs-treeset-in-java/
    https://www.tutorialspoint.com/difference-between-tree-set-and-hash-set-in-java

    From Android Interview Questions (Apache 2.0)

  17. Explain: Hashtable vs ConcurrentHashMap

    Hashtable vs ConcurrentHashMap

    Hashtable. This class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable.

    ConcurrentHashMap. A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

    Properties Hashtable ConcurrentHashMap
    Is null key allowed No No
    Is null value allowed No Yes
    Is Thread Safe Yes Yes, Thread safety is ensured by having separate locks for separate buckets, resulting in better performance. Performance is further improved by providing read access concurrently without any blocking.
    Performance Slow due to synchronization overhead. Faster than Hashtable. ConcurrentHashMap is a better choice when there are more reads than writes.
    Iterator Hashtable uses enumerator to iterate the values of Hashtable object. Enumerations returned by the Hashtable keys and elements methods are not fail-fast. Fail-safe iterator: Iterator provided by the ConcurrentHashMap is fail-safe, which means it will not throw ConcurrentModificationException.

    When you read from a ConcurrentHashMap using get(), there are no locks, contrary to the Hashtable for which all operations are simply synchronized. Hashtable uses single lock for whole data. ConcurrentHashMap uses multiple locks on segment level (16 by default) instead of object level i.e. whole Map. Hashtable is belongs to the Collection framework; ConcurrentHashMap belongs to the Executor framework. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

    Links

    https://www.geeksforgeeks.org/concurrenthashmap-in-java/
    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html
    https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html

    From Android Interview Questions (Apache 2.0)

  18. How HashMap works?

    HashMap works

    HashMap in Java works on hashing principles. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap.

    Before understanding the internal working of HashMap, you must be aware of hashCode() and equals() method.

    • equals() - It checks the equality of two objects. It compares the Key, whether they are equal or not. It is a method of the Object class. It can be overridden. If you override the equals() method, then it is mandatory to override the hashCode() method.
    • hashCode() - This is the method of the object class. It returns the memory reference of the object in integer form. The value received from the method is used as the bucket number. The bucket number is the address of the element inside the map. Hash code of null Key is 0.

    Buckets. A bucket is one element of HashMap array. It is used to store nodes. Two or more nodes can have the same bucket. In that case link list structure is used to connect the nodes. Buckets are different in capacity. A relation between bucket and capacity is as follows:

    capacity = number of buckets * load factor

    A single bucket can have more than one nodes, it depends on hashCode() method. The better your hashCode() method is, the better your buckets will be utilized.

    Put()/Get()

    What put() method does:

    • First of all, the key object is checked for null. If the key is null, the value is stored in table[0] position. Because hashcode for null is always 0
    • Then on next step, a hash value is calculated using the key’s hash code by calling its hashCode() method. This hash value is used to calculate the index in the array for storing Entry object. JDK designers well assumed that there might be some poorly written hashCode() functions that can return very high or low hash code value. To solve this issue, they introduced another hash() function and passed the object’s hash code to this hash() function to bring hash value in the range of array index size.
    • Now indexFor(hash, table.length) function is called to calculate exact index position for storing the Entry object.

    Same logic is applied in get() method. The moment hashmap identify the exact match for the key object passed as an argument, it simply returns the value object stored in current Entry object.

    Collisions

    Two unequal objects can have the same hash code value, so they will be stored in same array location called bucket. For resolve such situation HashMap uses LinkedList. Entry class had an attribute "next". This attribute always points to the next object in the chain.

    So, in case of collision, Entry objects are stored in linked list form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry? If there is no entry already present, the entry object is stored in this location. If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current entry object becomes next node in linkedlist. If next variable is not null, procedure is followed until next is evaluated as null.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  19. Explain: Memory model

    Java memory model

    The Java memory model specifies how the Java virtual machine works with the computer's memory (RAM). The Java virtual machine is a model of a whole computer so this model naturally includes a memory model - AKA the Java memory model.

    It is very important to understand the Java memory model if you want to design correctly behaving concurrent programs. The Java memory model specifies how and when different threads can see values written to shared variables by other threads, and how to synchronize access to shared variables when necessary.

    Generally, memory is divided into two big parts: the stack and the heap. Also JVM has non-heap memory.

    Stack and Heap

    Stack memory is responsible for holding references to heap objects and for storing value types (also known in Java as primitive types), which hold the value itself rather than a reference to an object from the heap.

    Each thread running in the Java virtual machine has its own thread stack. The thread stack contains information about what methods the thread has called to reach the current point of execution. A thread can only access it's own thread stack. Local variables created by a thread are invisible to all other threads than the thread who created it. Even if two threads are executing the exact same code, the two threads will still create the local variables of that code in each their own thread stack. Thus, each thread has its own version of each local variable.

    The heap memory contains all objects created in your Java application, regardless of what thread created the object. Those are referenced by the variables from the stack. For example, let’s analyze what happens in the following line of code:

    StringBuilder builder = new StringBuilder();
    

    The new keyword is responsible for ensuring that there is enough free space on heap, creating an object of the StringBuilder type in memory and referring to it via the "builder" reference, which goes on the stack.

    There exists only one heap memory for each running JVM process. Therefore, this is a shared part of memory regardless of how many threads are running.

    Objects on the heap can be accessed by all threads that have a reference to the object. When a thread has access to an object, it can also get access to that object's member variables. If two threads call a method on the same object at the same time, they will both have access to the object's member variables, but each thread will have its own copy of the local variables. Here is a diagram illustrating the points above:

    Two threads have a set of local variables. One of the local variables (Local Variable 2) point to a shared object on the heap (Object 3). The two threads each have a different reference to the same object. Their references are local variables and are thus stored in each thread's thread stack (on each). The two different references point to the same object on the heap, though. Differences between Stack vs Heap:

    Non-Heap Memory

    PermGen (Permanent Generation) is a special heap space separated from the main memory heap. The JVM keeps track of loaded class metadata in the PermGen. Additionally, the JVM stores all the static content in this memory section. This includes all the static methods, primitive variables, and references to the static objects. PermGen is replaced by Metaspace since Java 8. The most significant difference is how it handles memory allocation. Specifically, this native memory region grows automatically by default.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  20. Explain: Method signature

    Method signature

    Two of the components of a method declaration comprise the method signature - the method's name and the parameter types. The reason for the emphasis on just the method name and parameter list is because of overloading. It's the ability to write methods that have the same name but accept different parameters.

    The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

    Links

    https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
    http://www.java2s.com/Tutorials/Java/OCA_Java_SE_8_Method_Class/0030__Java_Method_Signature.htm

    From Android Interview Questions (Apache 2.0)

  21. Explain: References types

    References types

    There are four type of references in java:

    • Strong
    • Weak
    • Soft
    • Phantom

    Strong reference

    Strong reference are the ordinary references in Java. Anytime we create a new object, a strong reference is by default created. Any object which has an active strong reference are not eligible for garbage collection. The object is garbage collected only when the variable which was strongly referenced points to null.

    MyClass obj = new MyClass();

    Weak reference

    Weak reference is a reference not strong enough to keep the object in memory. The object is garbage collected whenever a weak reference is found, the object will be recycled regardless of whether the system heap space is sufficient.

    WeakReference<MyClass> obj = new MyClass();

    Soft reference

    Think of a SoftReference as a stronger WeakReference. An object holding a SoftReference won't be reclaimed quickly by the JVM. JVM will determine when to recycle based on the current heap usage. Only when the heap usage is near the threshold, the SoftReferenced object will be collected. Therefore, SoftReference can be used to implement a memory-sensitive cache.

    SoftReference<MyClass> obj = new MyClass();

    Phantom reference

    PhantomReference is the weakest of all types. An object holding a PhantomReference is almost identical to having no reference and can be recycled by the garbage collector at any time. But, before removing them from the memory, JVM puts them in a queue called ‘reference queue’ . They are put in a reference queue after calling finalize() method on them.

    PhantomReference<MyClass> obj = new MyClass();

    Links

    https://docs.oracle.com/javase/8/docs/api/java/lang/ref/package-summary.html
    https://medium.com/google-developer-experts/finally-understanding-how-references-work-in-android-and-java-26a0d9c92f83
    https://www.tutorialdocs.com/article/java-4-referance-types.html

    From Android Interview Questions (Apache 2.0)

  22. What are anonymous classes?

    Anonymous classes

    Anonymous classes are inner classes with no name. Since they have no name, we can't use them in order to create instances of anonymous classes. As a result, we have to declare and instantiate anonymous classes in a single expression at the point of use. Anonymous classes are defined inside an expression, hence it must be a part of a statement, so the semicolon is used at the end of anonymous classes to indicate the end of the expression.

    Anonymous inner class are mainly created in two ways:

    • Class (may be abstract or concrete)
    • Interface

    The anonymous class expression consists of the following:

    • The new operator
    • The name of an interface to implement or a class to extend.
    • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses.
    • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

    Restrictions of anonymous classes:

    • Cannot have explicitly declared constructors
    • Never be abstract
    • No way to extend them

    Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:

    • An anonymous class has access to the members of its enclosing class.
    • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
    • Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name.

    Anonymous classes also have the same restrictions as local classes with respect to their members:

    • Сannot declare static initializers or member interfaces in an anonymous class.
    • Сan have static members provided that they are constant variables.

    Note that you can declare the following in anonymous classes:

    • Fields
    • Extra methods (even if they do not implement any methods of the supertype)
    • Instance initializers
    • Local classes

    Links

    https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
    https://www.geeksforgeeks.org/anonymous-inner-class-java/
    https://www.baeldung.com/java-anonymous-classes

    From Android Interview Questions (Apache 2.0)

  23. What are lambda expressions?

    Lambda expressions

    One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.

    Lambda expressions basically express instances of functional interfaces. Lambda expressions implement the only abstract function and therefore implement functional interfaces. Lambda expressions are added in Java 8 and provide next functionalities:

    • Enable to treat functionality as a method argument, or code as data.
    • A function that can be created without belonging to any class.
    • A lambda expression can be passed around as if it was an object and executed on demand.

    A lambda expression is characterized by the following syntax:

    parameter -> expression body
    

    where lambda operator can be:

    • Zero parameter: () -> System.out.println("Zero parameter lambda");
    • One parameter: (p) -> System.out.println("One parameter: " + p);
    • Multiple parameters: (p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);

    The body of a lambda expression, and thus the body of the function / method it represents, is specified to the right of the -> in the lambda declaration: Here is an example:

    (oldState, newState) -> System.out.println("State changed")
    

    If your lambda expression needs to consist of multiple lines, you can enclose the lambda function body inside the { } bracket which Java also requires when declaring methods elsewhere. Here is an example:

    (oldState, newState) -> {
        System.out.println("Old state: " + oldState);
        System.out.println("New state: " + newState);
      }
    

    You can return values from Java lambda expressions, just like you can from a method. You just add a return statement to the lambda function body, like this:

    (param) -> {
        System.out.println("param: " + param);
        return "return value";
      }
    

    In case all your lambda expression is doing is to calculate a return value and return it, you can specify the return value in a shorter way. Instead of this:

    (a1, a2) -> { return a1 > a2; }
    

    You can write:

    (a1, a2) -> a1 > a2;
    

    The compiler then figures out that the expression a1 > a2 is the return value of the lambda expression (hence the name lambda expressions - as expressions return a value of some kind).

    Following are the important characteristics of a lambda expression:

    • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
    • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
    • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
    • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

    Links

    https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
    http://tutorials.jenkov.com/java/lambda-expressions.html
    https://www.geeksforgeeks.org/lambda-expressions-java-8/
    https://www.tutorialspoint.com/java8/java8_lambda_expressions.htm

    From Android Interview Questions (Apache 2.0)

  24. What are the basic interfaces of Java Collections Framework?

    Java Collections Framework

    The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.

    Iterator and Iterable

    Iterator interface provides the facility of iterating the elements in a forward direction only. There are only three methods in the Iterator interface. They are:

    Method Description
    public boolean hasNext() It returns true if the iterator has more elements otherwise it returns false.
    public Object next() It returns the element and moves the cursor pointer to the next element.
    public void remove() It removes the last elements returned by the iterator. It is less used.

    The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface. It contains only one abstract method: Iterator<T> iterator() It returns the iterator over the elements of type T.

    Collection

    The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface, it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

    Collection interface provides all general purpose methods which all collections classes must support (or throw UnsupportedOperationException). It extends Iterable interface which adds support for iterating over collection elements using the "for-each loop" statement.

    List

    An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. It can have duplicate values. There are various methods in List interface that can be used to insert, delete, and access the elements from the list. List interface is implemented by the classes: ArrayList, LinkedList, Vector, and Stack.

    Set

    Sets represents a collection of sorted elements. Sets do not allow the duplicate elements. Set interface does not provides no guarantee to return the elements in any predictable order; though some Set implementations store elements in their natural ordering and guarantee this order.

    Some useful classes which implement Set interface are – EnumSet, HashSet, LinkedHashSet and TreeSet.

    Map

    The Map interface enable us to store data in key-value pairs (keys should be immutable). A map cannot contain duplicate keys; each key can map to at most one value.

    The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

    Some useful classes which implement Map interface are – ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, Properties, TreeMap and WeakHashMap.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  25. What are the methods of Object class?

    Object class methods

    Comparable Comparator
    public final Class getClass() Returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
    public int hashCode() Returns the hashcode number for this object.
    public boolean equals(Object obj) Compares the given object to this object.
    protected Object clone() Creates and returns the exact copy (clone) of this object.
    public String toString() Returns the string representation of this object.
    public final void notify() Wakes up single thread, waiting on this object's monitor.
    public final void notifyAll() Wakes up all the threads, waiting on this object's monitor.
    public final void wait() Causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
    public final void wait(long timeout) Causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
    public final void wait(long timeout,int nanos) Causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).

    getClass()

    You cannot override getClass. The getClass() method returns a Class object, which has methods you can use to get information about the class, such as its name (getSimpleName()), its superclass (getSuperclass()), and the interfaces it implements (getInterfaces()). The Class class, in the java.lang package, has a large number of methods (more than 50). For example, you can test to see if the class is an annotation (isAnnotation()), an interface (isInterface()), or an enumeration (isEnum()). You can see what the object's fields are (getFields()) or what its methods are (getMethods()), and so on.

    hashCode()

    The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.

    By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

    equals(Object obj)

    The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object. You should always override the equals() method if the identity operator is not appropriate for your class.

    clone()

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  26. What do you know about ArrayList?

    ArrayList

    Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

    The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

    Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

    An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

    Internal implementation

    Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:

    • Creates a bigger sized memory on heap memory (for example memory of double size).
    • Copies the current memory elements to the new memory.
    • New item is added now as there is bigger memory available now.
    • Delete the old memory.

    Synchronization

    ArrayList is not synchronized. If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

    List list = Collections.synchronizedList(new ArrayList(...));

    The iterators returned by this class's iterator method are fail-fast: if the list is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  27. What do you know about Comparator interface?

    Comparator interface

    Comparator interface is used to order(sort) the objects in the collection in your own way. It gives you the ability to decide how elements will be sorted and stored within collection and map. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

    Rules for using Comparator interface:

    • If you want to sort the elements of a collection, you need to implement Comparator interface.
    • If you do not specify the type of the object in your Comparator interface, then, by default, it assumes that you are going to sort the objects of type Object. Thus, when you override the compare() method ,you will need to specify the type of the parameter as Object only.
    • If you want to sort the user-defined type elements, then while implementing the Comparator interface, you need to specify the user-defined type generically. If you do not specify the user-defined type while implementing the interface, then by default, it assumes Object type and you will not be able to compare the user-defined type elements in the collection

    Example

    Let's create Student class:

    public final class Student {
        private final int id;
        private final String name;
        Student(int id, String name) {
            this.id = id;
            this.name = name;
        }
        int getId() {
            return id;
        }
        String getName() {
            return name;
        }
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    

    Then create StudentIdComparator class:

    import java.util.Comparator;
    public final class StudentIdComparator implements Comparator<Student> {
        @Override
        public int compare(Student student1, Student student2) {
            if (student1.getId() == student2.getId()) return 0;
            else if (student1.getId() > student2.getId()) return 1;
            else return -1;
        }
    }
    

    Example of usage StudenIdComparator

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  28. What do you know about ConcurrentHashMap?

    ConcurrentHashMap

    A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

    Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. (More formally, an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key reporting the updated value.) For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time. Bear in mind that the results of aggregate status methods including size, isEmpty, and containsValue are typically useful only when a map is not undergoing concurrent updates in other threads. Otherwise the results of these methods reflect transient states that may be adequate for monitoring or estimation purposes, but not for program control.

    The table is dynamically expanded when there are too many collisions (i.e., keys that have distinct hash codes but fall into the same slot modulo the table size), with the expected average effect of maintaining roughly two bins per mapping (corresponding to a 0.75 load factor threshold for resizing). There may be much variance around this average as mappings are added and removed, but overall, this maintains a commonly accepted time/space tradeoff for hash tables. However, resizing this or any other kind of hash table may be a relatively slow operation. When possible, it is a good idea to provide a size estimate as an optional initialCapacity constructor argument. An additional optional loadFactor constructor argument provides a further means of customizing initial table capacity by specifying the table density to be used in calculating the amount of space to allocate for the given number of elements. Also, for compatibility with previous versions of this class, constructors may optionally specify an expected concurrencyLevel as an additional hint for internal sizing. Note that using many keys with exactly the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable, this class may use comparison order among keys to help break ties.

    Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  29. What do you know about EnumMap?

    EnumMap

    A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

    Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared). This is reflected in the iterators returned by the collections views (keySet(), entrySet(), and values()).

    Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress.

    Null keys are not permitted. Attempts to insert a null key will throw NullPointerException. Attempts to test for the presence of a null key or to remove one will, however, function properly. Null values are permitted.

    Like most collection implementations EnumMap is not synchronized. If multiple threads access an enum map concurrently, and at least one of the threads modifies the map, it should be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the enum map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap(java.util.Map<K, V>) method. This is best done at creation time, to prevent accidental unsynchronized access:

    Map<EnumKey, V> m= Collections.synchronizedMap(new EnumMap<EnumKey, V>(...));
    

    Implementation note: All basic operations execute in constant time. They are likely (though not guaranteed) to be faster than their HashMap counterparts.

    EnumSet vs EnumMap

    Both the EnumSet and EnumMap class provides data structures to store enum values. However, there exist some major differences between them:

    • EnumSet is represented internally as a sequence of bits, whereas the EnumMap is represented internally as arrays.
    • EnumSet is created using its predefined methods like allOf(), noneOf(), of(), etc. However, an EnumMap is created using its constructor.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  30. What do you know about EnumSet?

    EnumSet

    A specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.

    The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared). The returned iterator is weakly consistent: it will never throw ConcurrentModificationException and it may or may not show the effects of any modifications to the set that occur while the iteration is in progress.

    null elements are not permitted. Attempts to insert a null element will throw NullPointerException. Attempts to test for the presence of a null element or to remove one will, however, function properly.

    Like most collection implementations, EnumSet is not synchronized. If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the enum set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet(java.util.Set<T>) method. This is best done at creation time, to prevent accidental unsynchronized access:

    Set<MyEnum> s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class));
    

    All basic operations execute in constant time. They are likely (though not guaranteed) to be much faster than their HashSet counterparts. Even bulk operations execute in constant time if their argument is also an enum set.

    Creating an EnumSet Object

    Since EnumSet is an abstract class, we cannot directly create an instance of it. It has many static factory methods that allow us to create an instance. There are two different implementations of EnumSet provided by JDK:

    • RegularEnumSet
    • JumboEnumSet

    These are package-private and backed by a bit vector. RegularEnumSet uses a single long object to store elements of the EnumSet. Each bit of the long element represents an Enum value. Since the size of long is 64 bits, it can store up to 64 different elements.

    JumboEnumSet uses an array of long elements to store elements of the EnumSet. The only difference from RegularEnumSet is JumboEnumSet uses a long array to store the bit vector thereby allowing more than 64 values.

    The factory methods create an instance based on the number of elements:

    if (universe.length <= 64)
        return new RegularEnumSet<>(elementType, universe);
    else
        return new JumboEnumSet<>(elementType, universe);
    

    EnumSet does not provide any public constructors, instances are created using static factory methods like:

    • allOf(size)
    • noneOf(size)
    • range(e1, e2)
    • of()

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

After the last page: 42 questions more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.