This one blog will be a little different from all the other blogs I have written. It would have a mixture of questions that i come across and sometimes I read on some sites which are indeed useful.

Anyone is free to add to this list. Just comment and let me know and I can add them. And in case there is an error in the solution feel free to correct it. After all knowledge sharing is the key to growing.

The list might be random so please bear with me and also a mixture of logical reasoning, OOPS, java and android.

  • Why does java not support multiple inheritance ?
ANS: Because of the diamond problem. In the case of multiple inheritance it is possible that two classes may have the same method name and another class may extend these two classes and therefore the compiler would not know which method to consider. So it is not supported in java.
  • Given a definition like: say you have an animal and you have to define a dog, a cat or even a horse. All animals can walk and eat and sleep. But the sounds they produce would be different. How would you achieve this in java.
ANS: We create Animal as the parent class implementing the methods walk and eat and with an abstract method sound() or may be makeSound(). Then have all the other classes extend the Animal class and override the makeSound method to print the sound the animal makes.

Something like:

public class Animal{
    public void eat(){
        System.out.println("Animals eat");

    public void sleep(){
        System.out.println("Animals sleep too");

    public abstract void makeSound();

public class Dog extends Animal{
    public void makeSound(){
        System.out.println("woouf woouf");

Continue making classes and override the makeSound method.
  • With respect to #2 would you choose to create multiple classes for all the animals that exist or would you choose to use an if else statement in the Animal class?
ANS: It is possible to simply call the super method and pass the type of animal and have a switch case or multiple if else statements and then print the sound accordingly.

But there are a couple of reasons this should not be done.
1. It reduces code readability
2. If you wish to add one more method like makeSound() you would have to add if else statements to it too
3. The most important reason, it breaks one of the SOLID principles of java, the open and closed principle.
  • Can a constructor have the static keyword in java?
ANS: a) No. It is not allowed in Java. But why really? This is because anything marked as static will only belong to that class and never to any subclass. 

For example: create a class Demo and create another class DemoChild that extends Demo. Ensure that both of these classes have constructors with a Sysout message. You wi notice that when we create an instance of the child class, the constructor of the super gets called. 

This is why a static constructor is not supported in java else the meaning of inheritance would have been void.

b) We use the keyword super or this in order to call a method of the super class that is also why we can not have static constructors else you would not be able to use these keywords.
  • Given an array that contains n-1 values which range from 1 to n, find the missing value in the array.
ANS: We will just go through some of the possibilities and may be why one is better than the other.

1. You could write code this way:

int missingNumber = 0;
List list = new ArrayList(Arrays.asList(intArrHere));

for(int i=0;i<n;i++){
        missingNumber = i+1;

Well, this is a solution but then the time complexity would be O(n2) (Big O n squared). 

Why ? Since wr have our loop that runs n times and also the contains method that performs an indexOf search which also runs a loop n times. Is there anything better? Yes.

2. Calculate the sum of n numbers and the sum of the elements in the array. Get the difference and that is the missing number.

int totalSum = (n*(n+1))/2;
int arraySum = 0;

for(int i=0;i<=arr.length;i++){
    arraySum += arr[i];

int missingNumber = totalSum - arraySum;

We have reduced the time complexity to O(n).
  • Given two layouts.
    1. The layout has a linearlayout as the root within which we have a relativelayout and inside it a textview and an imageview
    2. The other one has a linearlayout as the root and inside it we have a textview imageview and a relativelayout.Which layout would you choose to load into the activity.
ANS: The 2nd layout is preferable. Why? It is because we have nested layouts in the first case. This means that for the relativelayout the linearlayout has to be measured first, and for the child elements its parent would have to be measured. 

This leads to measures done about three times as the childs measure would depend on the parent. While in the 2nd layout the drawing time and measures taken would be less.

Please note using nested linear layouts would always cause a performance issue.
  • What is transient and volatile?
ANS: Both of these are keywords in java. Transient is related to serialization and Volatile to synchronization.

When wanting to pass data from one activity to another via intents we need to serialize the objects. We also do this in order to store objects into the database or to write them to a file. You will notice that the object getting serialized will give you the same values when you de-serialize using the same mechanism. Any variable marked as transient will not be serialized. This means that its value will not be stored and on de-serialization you might get null as the value for that variable or 0 incase of floats or integers. 

Volatile on the other hand refers to allowing that variable to be accessed in a thread safe form. Meaning if a thread is modifying the value of a volatile variable then any other thread that tries to access it will only be allowed to do so when the first one has finished its work, thus making the right instance available to the other thread.
  • What does public static void main(String[] args) stand for
ANS: This is the famous java line we write in first before anything else. I will explain the words one after the other: 

public:- This is the access modifier that means that this method can be called from anywhere. There are several other access modifiers but for jvm to be able to call the main method we use this modifier.

static:- This specifies that the function is not instance related. Meaning, we can call this function without creating an instance of the class.

void:- void refers to the return type of this function which is nothing is this case. (Nothing is supposed to be returned)

main():- This is the function or method name. This function is termed as the starting point of every java application and thus when executed JVM looks for this method name with the signature as under:

public static void main(String[] args){} where String[] refers to the parameters that the method can accept through command line.
  • What is continuous integration (CI)?
ANS: This is a software engineering practice that now plays an important role in the agile methodologies. The idea is to be able to deliver sprint after sprint without breaking the build while delivering incremental features. Why so?

Because there are chances when trying to focus on getting a new module integrated and developed well any other part of the code might stop functioning and that is why we use CI. The common CI tools most of us would have heard of are: Hudson, BuildBot and Jenkins.
  • What is the difference between the RecyclerView and a ListView?
ANS: There is no difference between a recycler view and a ListView if you ever had to just look at a UI placed before you. Since a ListView can allow you to add dividers while in the case of a RecyclerView you could add the divider in the layout row. A recycler view supports animations but again you could add animations to a ListView row item too. Then why do we have a RecyclerView when we have a ListView? 

a) In the case of the ListView it is the individual’s choice whether or not to use the ViewHolder pattern in the adapter, whilst in the RecyclerView it is mandatory to use the ViewHolder pattern.  This prevents the list from being laggy and also findviewById() is not anymore an expensive operation. 

The Recycler has an improved mechanism of performing layout binding. It uses a two-level caching mechanism - the scrap heap and the recycle heap. When a view is temporarily detached from the layoutmanager it is put into the scrap heap. Thus when we scroll, it would first check if the scrap heap has the view at that position, if it does, it simply returns the view from the scrap heap. Else, it creates a new view, puts it into the recycle heap and calls bindViewHolder method in order to bind data to the new view that would have been created. 

Efficiency in the RecyclerView has improved.

b) The RecyclerView uses a LayoutManager, the major supported layoutmanagers include, the LinearLayoutManager, the StaggeredGridLayoutManager and the GridLayoutManager. In the case of the listview, the main objective was to display items vertically and it was later on that we had variations of being able to display items horizontally. But in the case of the RecyclerView, we not have the same view used to display items vertically like a list, or in the form of a grid, or in the form of a staggered grid view like pinterest.

c) Coming back to animations, in the case of a listview, you would have to create custom animations and calling notifyDatasetChanged would mess up the animations, it would not be that smooth. While in the case of the recycler view, you can use ItemAnimator provided by the RecyclerView and also you do not have to call notifyDatasetChanged, rather you have the option of just changing one item in the view and it would be able to animate it well. 

There are many things you might have to do extra in the case of a RecyclerView, for example, add a custom listener for the click events, or even write your own cursor adapter with a recycler view, but overall, a RecyclerView is a favorable option to use over a ListView.

You can always refer to this for more clarity:
  • What is a LayoutManager in the recycler view?
ANS: A LayoutManager is used to display or rather lay the row items the way you wish them to be laid out. The LinearLayoutManager would display the items in the form of a ListView (vertical) or even horizontally, while the GridLayoutManager would display the items in the form of a grid, similarly, the StaggeredGridLayoutManager would display the items in the form of a grid but each item may have a different height.

It is also responsible in measuring the item rows and positioning them and also determines how to handle views that are not visible/are yet to be shown (you can refer to the above question as to how the recycler re-uses its views)
  • What is the main thread in Android?
ANS: The main thread is also known as the UI thread in Android. It is the thread on which the entire application runs unless and otherwise specified. The UI thread is responsible for rendering the UI and also helps users to be able to interact with widgets on the screen. It is therefore advisable not to perform long running operations on the main thread.
  • Given that you have to load 100 items on every scroll end, would you use an array adapter or a cursor adapter? Why?>
ANS: I would choose to use the cursor adapter since it manages how to display data well. In the case of an array adapter, we would have all the items loaded into the list even when we do not need them, whilst in the case of the cursor adapter it only fetches that many records that really need to be displayed or rather are needed, unlike in the array adapter where we have the getView() getting called multiple times. In other words, the cursor adapter uses a lazy loading kind of mechanism in order to load data into the views.  

However, when using a cursor adapter, this means you would be using a cursor which would be kept open until you are using it and there are chances of leaking it too. But to overcome this, we can use a cursor loader than manages the cursor properly.
  • The HashMap does not work with primitive types. Why?
ANS: Because generics only support object types (wrapper classes) and not primitives.
  • What is the difference between int and Integer?
a) int is a primitive type while Integer is an object / class type / reference type (a wrapper for int)
b) Wrapper classes inherit from the Object class, while primitive types don't.
c) an int type is mutable (it's value can be changed unless it is marked final) while an Integer type variable's value cannot be changed. In order to change it, you would need to create a new object of the type Integer.
  • What is the difference between mutable and immutable? Is a String mutable?
ANS: Mutable objects that those whose values can be changed while immutable objects are those whose values cannot be changed. A String is not mutable. 
We can claim that a string is mutable because when we say: 
String str = "hi";
str = str + " there!";

We are ideally changing the value of str from "hi" to "hi there!", but it doesn't happen like that. Technically, There are three instances of the string that gets created.
a) One stores "hi"
b) The other stores " there!"
c) The third one stores "hi there!"

So, when we update the value of the string, we have a new object that is created which would point to the same reference as the first one. (More information can surely be found on StackOverflow)

On the other hand, the StringBuffer and StringBuilder Objects are mutable, as whatever we append to these would make changes to the same object and no new object will get created. A slight difference between these two is that, the StringBuffer is thread safe while StringBuilder is not.
  • What are the pitfalls of using AsyncTasks
ANS: Initially async tasks were created to be painless, but there are some pitfalls it has, other than it being able to communicate well with the UI thread from the onPostExecute method.

a) When an activity is rotated, the instance of the activity gets destroyed and a new one is created, the old async task created will lose the context and hence it would not be able to pass the results to the new activity unless you maintain a reference to the async task.

b) When an activity is destroyed due to whatever reasons, we cannot assume that the async task is also destroyed, hence we have to manage the cancellation of the async task ourselves.

c) There is a limit to the number of async tasks you can execute at a time (there is a pool of 128 tasks with an addition of 10 tasks max.) but if you are supporting the older versions the max you can execute is 10 async tasks, which would mean if you queue up around 138 tasks, the app will crash.

d) There is no guarantee an async task is cancelled just because you use the "cancel" method of the async task. You might have to check if the async task has been cancelled or not using the isCancelled method to stop your executions, or make sure your thread are interruptible.