AndroidPub
Published in

AndroidPub

Android Interview Questions Cheat Sheet — Part II

Image Credits: http://www.dezzain.com/website-development/the-value-of-javascript-for-android-in-web-development/

Why is Java said to be platform independent?

2. Difference between ‘throw’ and ‘throws’ in Java Exception Handling?

3. Is there ever a scenario where we can skip the finally block in a try catch?

4. What are anonymous classes?

  • An anonymous class must always extend a super class or implement an interface but it cannot have an explicit extends or implements clause.
  • An anonymous class must implement all the abstract methods in the super class or the interface.
  • An anonymous class always uses the default constructor from the super class to create an instance.
  • Example:
MyButton.setOnClickListener(new Button.OnClickListener {
@override
public void onClick(View view){
//some code
}
});

5. Why is the main method static in java?

public class Hello { 
static {
System.out.println("Hello, World!");
}
}

6. What is garbage collector? How does it work?

7. Difference between stack memory & heap memory?

8. Explain OOPs concept

9. What is Inheritance?

10. Does Java support multiple inheritance?

11. What is Encapsulation?

  • Encapsulation involves binding code and data together as a single unit.
  • Encapsulation is a technique used for hiding the properties and behaviours of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.
  • For instance, a class can be an encapsulated class if all the variables in it are defined as Private and by providing getter and setter methods.

12. What is Abstract class?

  • Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
  • If even a single method is abstract, the whole class must be declared abstract.
  • Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
  • You can’t mark a class as both abstract and final.
  • Non-abstract methods can access a method that you declare as abstract.

13. What are Interfaces?

  • Interfaces are only declared methods that an implementing class would need.
  • Interfaces cannot be marked as final. Interface variables must be static or final.
  • Interfaces cannot be instantiated directly.
  • Marker Interfaces: Marker interfaces are those which do not declare any required Methods. The java.io.Serializable interface is a typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.

14. Difference between Abstract and Interfaces?

15. What is Polymorphism?

  • Compile time polymorphism: The flow of control is decided during the compile time itself. By overloading.
  • Run time polymorphism: is done using inheritance and interface. The flow of control is decided during the runtime. Overriding: Overriding will have the same method name with the same parameters. One will be the parent class method and the other will be the child class method. Overloading occurs when the same method name is declared but with different parameters.

16. What is Method overloading?

  • Overloaded methods MUST change the argument list
  • Overloaded methods CAN change the return type
  • Overloaded methods CAN change the access modifier
  • Overloaded methods CAN declare new or broader checked exceptions
  • A method can be overloaded in the same class or in a subclass

17. What is Method overriding?

  • You can’t override a method marked public and make it protected
  • You cannot override a method marked final
  • You cannot override a method marked static

18. Why would you not call abstract method in constructor?

19. Composition over inheritance?

class Person {
String Title;
String Name;
Int Age;
public Person(String title, String name, String age) {
this.Title = title;
this.Name = name;
this.Age = age;
}
}class Employee {
Int Salary;
private Person person;
public Employee(Person p, Int salary) {
this.person = p;
this.Salary = salary;
}
}

20. Difference between Encapsulation & Abstraction?

  • Abstraction focuses on the outside view of an object (i.e. the interface)
  • Encapsulation (information hiding) prevents clients from seeing it’s inside view.
  • Abstraction solves the problem in the design side while Encapsulation is the Implementation.

21. Constructors vs Methods?

  • this(): Constructors use this to refer to another constructor in the same class with a different parameter list.
  • super(): Constructors use super to invoke the superclass's constructor.

22. What is the difference between instantiation and initialisation of an object?

23. Do objects get passed by reference or value in Java? Elaborate on that.

  • Java is always pass-by-value. When we pass the value of an object, we are passing the reference to it.
  • Java creates a copy of the variable being passed in the method and then does the manipulations. Hence the change is not reflected in the main method.
  • But when you pass an object reference into a method, a copy of this reference is made, so it still points to the same object. This means, that any changes that you make to the insides of this object are retained, when the method exits.
  • Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.

24. Primitives in Java?

25. Difference between == and .equals() method in Java?

26. Why strings are Immutable?

27. What is String.intern()? When and why should it be used?

  • String.intern() method can be used to to deal with String duplication problem in Java. By carefully using the intern() method you can save a lot of memories consumed by duplicate String instances. A string is duplicate if it contains the same content as another string but occupied different memory location.
  • By calling the intern() method on a string object, for instance “abc”, you can instruct JVM to put this String in the pool and whenever someone else creates “abc”, this object will be returned instead of creating a new object. This way, you can save a lot of memory in Java, depending upon how many Strings are duplicated in your program.
  • When the intern method is invoked, if the String pool already contains that String object such that equals() return true, it will return the String object from the pool, otherwise it will add that object to the pool of unique String.

28. String pool in Java:

29. Final modifier?

  • final Classes- A final class cannot have subclasses.
  • final Variables- A final variable cannot be changed once it is initialised.
  • final Methods- A final method cannot be overridden by subclasses.

30. Finalize keyword?

31. Finally keyword?

32. Static variables?

33. What is reflection?

34. Multi threading?

35. Fail-fast & Fail-Safe?

36. What does the keyword synchronized mean?

37. What does the keyword volatile mean?

  • Suppose two threads are working on a method. If two threads run on different processors each thread may have its own local copy of variable. If one thread modifies its value the change might not reflect in the original one in the main memory instantly.
  • Now the other thread is not aware of the modified value which leads to data inconsistency.Essentially, volatile is used to indicate that a variable’s value will be modified by different threads. ‘volatile’ tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.
  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to ‘main memory’
  • An access to a volatile variable never has the potential to block: we’re only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock.

38. What is Autoboxing and Unboxing?

39. Optionals in Java?

40. What is externalization?

  • In serialization, the JVM is responsible for the process of writing and reading objects. This is useful in most cases, as the programmers do not have to care about the underlying details of the serialization process.
  • However, the default serialization does not protect sensitive information such as passwords and credentials.
  • Thus externalization comes to give the programmers full control in reading and writing objects during serialization.
  • Implement the java.io.Externalizable interface — then you implement your own code to write object’s states in the writeExternal() method and read object’s states in the readExternal() method.

41. What are Data Structures?

42. Explain Big O Notation?

43. Explain Big Omega Notation

44. Arrays in Java?

  • Arrays is an ordered collection. It will have a fixed length which needs to be defined at the initialisation time whereas lists have a variable length. Arrays are easier to store elements of the same data type. Used internally in stack and queue. It is a convenient way of representing a 2D array.
  • Arrays cannot hold generic data types whereas lists can.
  • Arrays can store all data types whereas lists cannot store primitive data types, only objects.
Complexity of Arrays

45. Linked Lists in Java?

  • A LinkedList contains both a head and a tail. The “Head” is the first item in the LinkedList, while the “Tail” is the last item. It is not a circular data structure, therefore the tail does not have its’ pointer pointing at the Head — the pointer is just null.
  • No indices but each node has a pointer pointing to the next element.
  • They are dynamic in nature which means they allocate memory only when needed.
  • Insertion, deletion, updation is easy
  • A linked list is a group of nodes which represent a sequence. Each node consists of a data and a link or reference to the next node in the sequence.
  • Singly Linked List: has a node and a pointer to the next node in the sequence.
  • Doubly Linked List: has a node and 2 pointers — one to the next node and one to the previous node in the sequence. This is very convenient if you need to be able to traverse stored elements in both directions.
Complexity of LinkedList

46. Binary Trees

  • A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.
  • The left subtree of a node contains only values less than the parent node’s value.
  • The right subtree of a node contains only values greater than or equal to the node’s value.
  • Only if the above 2 criteria are matched, then the tree is said to be balanced.
  • Advantages of Binary tree over Linked List: In a linked list, the items are linked together through a single next pointer. In a binary tree, as long as the tree is balanced, the search path to each item is a lot shorter than that in a linked list.
  • Their disadvantage is that in the worst case they can degenerate into a linked list in terms of efficiency.

47. Stacks:

  • Push: a new entity added to the top of the stack.
  • Pop: an entity is removed from the top of the stack.
  • A stack may be defined to have a bounded capacity i.e. if the stack is full and a new entity cannot be added, then it is considered to be in an overflow state.
  • If the stack is empty and an entity cannot be popped, it is considered to be in an underflow state.
  • Efficiency of stacks: The time is not dependent of the no of items in the stack so it is very efficient. O(1).

48. Queues:

  • enqueue: Add an item to the end of the queue. Dequeue: remove an item from the start of the queue.
  • Front: retrieves the first item from the queue.
  • A queue may be defined to have a bounded capacity i.e. if the queue is full and a new entity cannot be added, then it is considered to be in an overflow state.
  • If the queue is empty and an entity cannot be popped, it is considered to be in an underflow state.
  • Efficiency of queues: The time is not dependent of the no of items in the queue so it is very efficient. O(1).
  • A double ended queue (deque): is an abstract collection which differs from queue in a way that an item can be added/removed from either side of the queue.
  • An input-restricted deque: is when deletion takes place at either end but insertion takes place at only one end.
  • An output-restricted deque: is when insertion takes place at either end but deletion takes place only at one end. A common occurrence of deque is doubly linked list.
  • Priority queue: same as queue but has a priority associated with it. Items are retrieved based on their priority.

49. Blocking Queues:

50. Difference between stacks & queues?

51. What is a deadlock in Java

52. What is the List interface & Set interface?

53. Difference between ArrayList & Vectors?

54. Insertion and deletion in ArrayList is slow compared to LinkedList?

  • ArrayList internally uses an array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.
  • During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node and updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

55. Implementations of Map?

  • TreeMap: sorted based on ascending order of keys. For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative.
  • HashTable: Does not allow null values. It is not fail-safe and it is synchronized whereas HashMap allows null values and it is fail-safe and it is not synchronized.
  • LinkedHashMap: This is a subclass of Hashmap. The order of insertion is preserved since it has a linkedList.

56. Difference between Enumeration and Iterators?

  • Enumeration does not include remove() method whereas iterators do. Enumerators act as read only interface as it provides methods to read and traverse through a collection.
  • ListIterator: is just like an iterator except it allows access to the collection in either the forward or backward direction

57. How Hashmap works in Java?

  • HashMap in Java works on hashing principle. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. When we call put method, hashcode() method of the key object is called so that hash function of the map can find a bucket location to store Entry object.
  • If two different objects have the same hashcode: in this case, a linked list is formed at that bucket location and a new entry is stored as next node. After finding bucket location, we will call keys.equals() method to identify a correct node in LinkedList and return associated value object for that key in Java HashMap

58. Generics in Java

  • Type-safety: We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
  • Type casting is not required: There is no need to typecast the object.
  • Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.
List list = new ArrayList();  
list.add("hello");
String s = (String) list.get(0); //typecasting
List<String> list = new ArrayList<String>();  
list.add("hello");
String s = list.get(0);

Thanks for reading!

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store