Android Important Question Answer 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Java Interview Question Answer

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by providing
some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike,
etc. It can be physical or logical.

Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume
any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer
differently, to draw something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't
know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a
capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of
the program.

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method overriding
in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by one
of its parent class, it is known as method overriding.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.

Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes
have the same method and you call it from child class object, there will be ambiguity to call the method of A or
B class.

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where you type the text and send the message. You don't know the internal processing about the message
delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method
body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Difference between abstract class and interface


Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods. Since Java 8, it ca
non-abstract methods. have default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.

4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract cla
interface.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.

7) An abstract class can be extended using keyword An interface can be implemented using keyword "implemen
"extends".

8) A Java  abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.

Constructors in Java
The constructor can be defined as the special type of method that is used to initialize the state of an object. It is
invoked when the class is instantiated, and the memory is allocated for the object. Every time, an object is
created using the new keyword, the default constructor of the class is called. The name of the constructor must
be similar to the class name. The constructor must not have an explicit return type.

Rules for creating Java constructor


There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?


The parameterized constructor is used to provide different values to distinct objects. However, you can provide
the same values also.

this keyword in java


There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current
object.
What are the various access specifiers in Java?
In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a
variable. In Java, there are four access specifiers given below.
o Public The classes, methods, or variables which are defined as public, can be accessed by any class or
method.
o Protected Protected can be accessed by the class of the same package, or by the sub-class of this class,
or within the same class.
o Default Default are accessible within the package only. By default, all the classes, methods, and
variables are of default scope.
o Private The private class, methods, or variables defined as private can be accessed within the class
only.

Why does Java not support pointers?


The pointer is a variable that refers to the memory address. They are not used in Java because they are
unsafe(unsecured) and complex to understand.

What are the differences between this and super keyword?


There are the following differences between this and super keyword.
o The super keyword always points to the parent class contexts whereas this keyword always points to
the current class context.
o The super keyword is primarily used for initializing the base class variables within the derived class
constructor whereas this keyword primarily used to differentiate between local and instance variables
when passed in the class constructor.
o The super and this must be the first statement inside constructor otherwise the compiler will throw an
error.

Can there be an abstract method without an abstract class?


No, if there is an abstract method in a class, that class must be abstract.

Can you use abstract and final both with a method?


No, because we need to override the abstract method to provide its implementation, whereas we can't override
the final method.

What is Exception Handling?


Exception Handling is a mechanism that is used to handle runtime errors. It is used primarily to handle checked
exceptions. Exception handling maintains the normal flow of the program. There are mainly two types of
exceptions: checked and unchecked. Here, the error is considered as the unchecked exception.

Abstract class Interface

An abstract class can have a method body The interface has only abstract methods.
(non-abstract methods).
An abstract class can have instance variables. An interface cannot have instance variables.

An abstract class can have the constructor. The interface cannot have the constructor.

An abstract class can have static methods. The interface cannot have static methods.

You can extend one abstract class. You can implement multiple interfaces.

The abstract class can provide the The Interface can't provide the implementation of the abstract
implementation of the interface. class.

The abstract keyword is used to declare an The interface keyword is used to declare an interface.


abstract class.

An abstract class can extend another Java class An interface can extend another Java interface only.
and implement multiple Java interfaces.

What are the differences between abstract class interface?

What is String Pool?


String pool is the space reserved in the heap memory that can be used to store the strings. The main advantage
of using the String pool is whenever we create a string literal; the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in
the pool, a new string instance is created and placed in the pool. Therefore, it saves the memory by avoiding the
duplicacy.

Why are the objects immutable in java?


Because Java uses the concept of the string literal. Suppose there are five reference variables, all refer to one
object "sachin". If one reference variable changes the value of the object, it will be affected by all the reference
variables. 

What are the differences between String and StringBuffer?


The differences between the String and StringBuffer is given in the table below.

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is mutable.

2) The String is slow and consumes more memory when The StringBuffer is fast and consumes less memory
you concat too many strings because every time it when you cancat strings.
creates a new instance.
3) The String class overrides the equals() method of The StringBuffer class doesn't override the equals()
Object class. So you can compare the contents of two method of Object class.
strings by equals() method.

What are the differences between StringBuffer and


StringBuilder?

No. StringBuffer StringBuilder

1) StringBuffer is synchronized, i.e., thread safe. It StringBuilder is non-synchronized,i.e., not thread safe. It
means two threads can't call the methods of means two threads can call the methods of StringBuilder
StringBuffer simultaneously. simultaneously.

2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

What is the difference between final, finally and finalize?

No. final finally finalize

1) Final is used to apply restrictions on class, Finally is used to place Finalize is used to perform
method, and variable. The final class can't be important code, it will be clean up processing just
inherited, final method can't be overridden, and executed whether an before an object is garbage
final variable value can't be changed. exception is handled or not. collected.

2) Final is a keyword. Finally is a block. Finalize is a method.

What is serialization?
Serialization in Java is a mechanism of writing the state of an object into a byte stream.
What is the reflection?
Reflection is the process of examining or modifying the runtime behavior of a class at runtime. The
java.lang.Class class provides various methods that can be used to get metadata, examine and change the
runtime behavior of a class. The java.lang and java.lang.reflect packages provide classes for java reflection. It is
used in:
o IDE (Integrated Development Environment), e.g., Eclipse, MyEclipse, NetBeans.
o Debugger
o Test Tools, etc.

What is a singleton class?


Singleton class is the class which can not be instantiated more than once. To make a class singleton, we either
make its constructor private or use the static getInstance method

What is the Collection framework in Java?


Collection Framework is a combination of classes and interface, which is used to store and manipulate the data
in the form of objects. It provides various classes such as ArrayList, Vector, Stack, and HashSet, etc. and
interfaces such as List, Queue, Set, etc. for this purpose.

What are the main differences between array and collection?


Array and Collection are somewhat similar regarding storing the references of objects and manipulating the
data, but they differ in many ways. The main differences between the array and Collection are defined below:
o Arrays are always of fixed size, i.e., a user can not increase or decrease the length of the array
according to their requirement or at runtime, but In Collection, size can be changed dynamically as per
need.
o Arrays can only store homogeneous or similar type objects, but in Collection, heterogeneous objects
can be stored.
o Arrays cannot provide the ?ready-made? methods for user requirements as sorting, searching, etc. but
Collection includes readymade methods to use.

What is the difference between ArrayList and Vector?

No. ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList is not a legacy class. Vector is a legacy class.

3) ArrayList increases its size by 50% of the Vector increases its size by doubling the array
array size. size.

4) ArrayList is not ?thread-safe? as it is not Vector list is ?thread-safe? as it?s every method
synchronized. is synchronized.
What is the difference between ArrayList and LinkedList?
No. ArrayList LinkedList

1) ArrayList uses a dynamic array. LinkedList uses a doubly linked list.

2) ArrayList is not efficient for LinkedList is efficient for manipulation.


manipulation because too much is
required.

3) ArrayList is better to store and fetch LinkedList is better to manipulate data.


data.

4) ArrayList provides random access. LinkedList does not provide random access.

5) ArrayList takes less memory overhead LinkedList takes more memory overhead, as it
as it stores only object stores the object as well as the address of that
object.

What is the difference between List and Set?


The List and Set both extend the collection interface. However, there are some differences between the both
which are listed below.
o The List can contain duplicate elements whereas Set includes unique items.
o The List is an ordered collection which maintains the insertion order whereas Set is an unordered
collection which does not preserve the insertion order.
o The List interface contains a single legacy class which is Vector class whereas Set interface does not
have any legacy class.
o The List interface can allow n number of null values whereas Set interface only allows a single null
value.
What is the difference between HashSet and TreeSet?
The HashSet and TreeSet, both classes, implement Set interface. The differences between the both are listed
below.
o HashSet maintains no order whereas TreeSet maintains ascending order.
o HashSet impended by hash table whereas TreeSet implemented by a Tree structure.
o HashSet performs faster than TreeSet.
o HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.

What is the difference between Set and Map?


The differences between the Set and Map are given below.
o Set contains values only whereas Map contains key and values both.
o Set contains unique values whereas Map can contain unique Keys with duplicate values.
o Set holds a single number of null value whereas Map can include a single null key with n number of
null values.

What is the difference between HashSet and HashMap?


The differences between the HashSet and HashMap are listed below.
o HashSet contains only values whereas HashMap includes the entry (key, value). HashSet can be
iterated, but HashMap needs to convert into Set to be iterated.
o HashSet implements Set interface whereas HashMap implements the Map interface
o HashSet cannot have any duplicate value whereas HashMap can contain duplicate values with unique
keys.
o HashSet contains the only single number of null value whereas HashMap can hold a single null key
with n number of null values.

What is the difference between HashMap and TreeMap?


The differences between the HashMap and TreeMap are given below.
o HashMap maintains no order, but TreeMap maintains ascending order.
o HashMap is implemented by hash table whereas TreeMap is implemented by a Tree structure.
o HashMap can be sorted by Key or value whereas TreeMap can be sorted by Key.
o HashMap may contain a null key with multiple null values whereas TreeMap cannot hold a null key but
can have multiple null values.

What is the difference between HashMap and Hashtable?


No. HashMap Hashtable
1) HashMap is not synchronized. Hashtable is synchronized.

2) HashMap can contain one null key and multiple Hashtable cannot contain any null key or null
null values. value.

3) HashMap is not ?thread-safe,? so it is useful for Hashtable is thread-safe, and it can be shared
non-threaded applications. between various threads.

4) 4) HashMap inherits the AbstractMap class Hashtable inherits the Dictionary class.

What is the difference between Collection and Collections?


The differences between the Collection and Collections are given below.
o The Collection is an interface whereas Collections is a class.
o The Collection interface provides the standard functionality of data structure to List, Set, and Queue.
However, Collections class is to sort and synchronize the collection elements.
o The Collection interface provides the methods that can be used for data structure whereas Collections
class provides the static methods which can be used for various operation on a collection.

How to remove duplicates from ArrayList?


There are two ways to remove duplicates from the ArrayList.
o Using HashSet: By using HashSet we can remove the duplicate element from the ArrayList, but it will
not then preserve the insertion order.
o Using LinkedHashSet: We can also maintain the insertion order by using LinkedHashSet instead of
HashSet.

The Process to remove duplicate elements from ArrayList using the LinkedHashSet:

o Copy all the elements of ArrayList to LinkedHashSet.


o Empty the ArrayList using clear() method, which will remove all the elements from the list.

What is the difference between Comparable and Comparator?

No. Comparable Comparator

1) Comparable provides only one sort of sequence. The Comparator provides multiple
sorts of sequences.

2) It provides one method named compareTo(). It provides one method named


compare().
3) It is found in java.lang package. It is located in java.util package.

4) If we implement the Comparable interface, The The actual class is not changed.
actual class is modified.

What are the Stacks?


Stacks are an abstract collection that follow LIFO mechanism. Main functionalities include:
Push: a new entity added to the top of the stack.
Pop: an entity is removed from the top of the stack.

What are anonymous classes?


An anonymous class is just what its name implies—it has no name. It combines the class declaration
and the creation of an instance of the class in one step.
Example:
MyButton.setOnClickListener(new Button.OnClickListener {
@override
public void onClick(View view){
//some code
} });

Difference between Stack memory & Heap Memory?


Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in
the computer’s RAM .

What is the difference Instantiation and Initialisation of an


object?
Initialisation is the process of the memory allocation, when a new variable is created. Variables
should be explicitly given a value, otherwise they may contain a random value that remained from the
previous variable that was using the same memory space. To avoid this problem, Java language
assigns default values to data types.
Instantiation is the process of explicitly assigning denitive value to a declared variable.

Difference between == and .equals() method in java?


== operators for reference comparison (address comparison)
.equals() method for content comparison.
* In simple words, == checks if both objects point to the same memory location whereas
.equals() evaluates to the comparison of values in the objects.

What is Multi Threading?


Multiple tasks are running concurrently in a program.

Android Interview Question Answer

Define Android Architecture?


The Android architecture consists of 4 components:
1. Linux Kernal
2. Libraries
3. Android Framework
4. Android Applications

Explain the Android application Architecture.


Following is a list of components of Android application architecture:

o Services: They handle background processing associated with an application.


o Activities: They dictate the UI and handle the user interaction to the smart phone screen..

o Broadcast Receiver: They handle communication between Android OS and applications.

o Content Providers: It will share the data between applications.

What is activity in Android?


Activities are basically containers or windows to the user interface.

What is Context in Android?


Interface to global information about an application environment. This is an abstract class whose
implementation is provided by the Android system. It allows access to application-specific resources
and classes, as well as up-calls for application-level operations such as launching activities,
broadcasting and receiving intents, etc.
● It allows us to access resources.
● It allows us to interact with other Android components by sending messages.
● It gives you information about your app environment.

Firstly, let’s look at 3 most used function for retrieving the Context:

● getContext() — returns the Context which is linked to the Activity from which is called,

● getApplicationContext() — returns the Context which is linked to Application which

holds all activities running inside it,

● getBaseContext() —is related to ContextWrapper, which is created around existing

Context and let us change its behavior. With getBaseContext() we can fetch the existing

Context inside ContextWrapper class.

Types of Context in Android


There are mainly two types of context are available in Android.
1. Application Context and
2. Activity Context

Application Context

This context is tied to the life cycle of an application. Mainly it is an instance that is a
singleton and can be accessed via getApplicationContext(). Some use cases of
Application Context are:
● If it is necessary to create a singleton object
● During the necessity of a library in an activity

List of functionalities of Application Context:

● Load Resource Values


● Start a Service
● Bind to a Service
● Send a Broadcast
● Register BroadcastReceiver

Activity Context

It is the activity context meaning each and every screen got an activity. For example,
EnquiryActivity refers to EnquiryActivity only and AddActivity refers to AddActivity only. It is
tied to the life cycle of activity. It is used for the current context. The method of invoking the
Activity Context is getContext().

Some use cases of Activity Context are:

● The user is creating an object whose lifecycle is attached to an activity.


● Whenever inside an activity for UI related kind of operations like toast, dialogue,
etc.,

getContext():

It returns the Context which is linked to the Activity from which it is called. This is useful
when we want to call the context from only the current running activity.

List of functionalities of Activity Context:

● Load Resource Values


● Layout Inflation
● Start an Activity
● Show a Dialog
● Start a Service
● Bind to a Service
● Send a Broadcast
● Register BroadcastReceiver

What are the core building blocks of android?


The core building blocks of Android are:
o Activity
o View
o Intent
o Service
o Content Provider
o Fragment etc.

What are the life cycle methods of android activity?


There are 7 life-cycle methods of activity. They are as follows:
1. onCreate()
2. onStart()
3. onResume()
4. onPause()
5. onStop()
6. onRestart()
7. onDestroy()

What are the life cycle methods of android Fragment?


There are 10 life-cycle methods of activity. They are as follows:
1. onAttach()
2. onCreate()
3. onCreateView()
4. onActivityCreated()
5. onStart()
6. onResume()
7. onPause()
8. onStop()
9. onDestroyView()
10. onDestroy()

What are the life cycle methods of Services?

onStartCommand()

onBind()

onCreate()

onDestroy()
 What is intent?
It is a kind of message or information that is passed to the components. It is used to launch an activity, display a
web page, send SMS, send email, etc. There are two types of intents in android:
1. Implicit Intent (is used to invoke the system components)
2. Explicit Intent (is used to invoke the activity class)

Define Android toast.


An android toast provides feedback to the users about the operation being performed by them. It displays the
message regarding the status of operation initiated by the user.

 Give a list of impotent folders in android


The following folders are declared as impotent in android:
o AndroidManifest.xml
o build.xml
o bin/
o src/
o res/
o assets/

Explain the use of 'bundle' in android?


We use bundles to pass the required data to various subfolders.

What is an application resource file?


The files which can be injected for the building up of a process are called as application resource file.

List the various storages that are provided by Android.


The various storage provided by android are:
o Shared Preferences
o Internal Storage
o External Storage
o SQLite Databases
o Network Connection

Types of Android Layout

● Android Linear Layout: LinearLayout is a ViewGroup subclass,


used to provide child View elements one by one either in a particular
direction either horizontally or vertically based on the orientation
property.
● Android Relative Layout: RelativeLayout is a ViewGroup subclass,
used to specify the position of child View elements relative to each
other like (A to the right of B) or relative to the parent (fix to the top of
the parent).
● Android Constraint Layout: ConstraintLayout is a ViewGroup
subclass, used to specify the position of layout constraints for every
child View relative to other views present. A ConstraintLayout is
similar to a RelativeLayout, but having more power.
● Android Frame Layout: FrameLayout is a ViewGroup subclass,
used to specify the position of View elements it contains on the top of
each other to display only a single View inside the FrameLayout.
● Android Table Layout: TableLayout is a ViewGroup subclass, used
to display the child View elements in rows and columns.
● Android Web View: WebView is a browser that is used to display
the web pages in our activity layout.
● Android ListView: ListView is a ViewGroup, used to display
scrollable lists of items in a single column.
● Android Grid View: GridView is a ViewGroup that is used to display
a scrollable list of items in a grid view of rows and columns.

What is service in android?


A service is a component that runs in the background. It is used to play music, handle network transaction, etc.

Different types of services:


Foreground Service: A foreground service performs some operation that is noticeable to the
user. For example, we can use a foreground service to play an audio track. A Notification
must be displayed to the user.

Background Service: A background service performs an operation that isn’t directly noticed by the
user. In Android API level 26 and above, there are restrictions to using background services and it is
recommended to use Work Manager in these cases.
Bound Service: A service is bound when an application component binds to it by calling
bindService() . A bound service offers a client-server interface that allows components to interact with
the service, send requests, receive results. A bound service runs only as long as another application
component is bound to it.

What is a content provider?


A content provider is used to share information between Android applications.

 What is fragment?
The fragment is a part of Activity by which we can display multiple screens on one activity.

What is a singleton class in Android?


A singleton class is a class which can create only an object that can be shared by all other classes.

What is sleep mode in Android?


In sleep mode, CPU is slept and doesn't accept any commands from android device except Radio interface layer
and alarm.

What’s the difference between onCreate() and onStart()?


The onCreate() method is called once during the Activity lifecycle, either when the
application starts, or when the Activity has been destroyed and then recreated, for example
during a configuration change.
The onStart() method is called whenever the Activity becomes visible to the user, typically
after onCreate() or onRestart().

Scenario in which only onDestroy is called for an activity without


onPause() and onStop()?
If finish() is called in the OnCreate method of an activity, the system will invoke onDestroy()
method directly.

onSavedInstanceState() and onRestoreInstanceState() in activity?


OnRestoreInstanceState() - When activity is recreated after it was previously destroyed, we
can recover the saved state from the Bundle that the system passes to the activity. Both the
onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that
contains the instance state information.
onSaveInstanceState() - is a method used to store data before pausing the activity.

Launch modes in Android?


Standard: It creates a new instance of an activity in the task from which it was started.
Multiple instances of the activity can be created and multiple instances can be added to the
same or dierent tasks. Eg: Suppose there is an activity stack of A -> B -> C.
Now if we launch B again with the launch mode as “standard”, the new stack will be A -> B
-> C -> B.

SingleTop: It is the same as the standard, except if there is a previous instance of the
activity that exists in the top of the stack, then it will not create a new instance but rather
send the intent to the existing instance of the activity.
Eg: Suppose there is an activity stack of A -> B. Now if we launch C with the launch mode
as “singleTop”, the new stack will be A -> B -> C as usual.
Now if there is an activity stack of A -> B -> C.
If we launch C again with the launch mode as “singleTop”, the new stack will still be
A -> B -> C.

SingleTask: A new task will always be created and a new instance will be pushed to the
task as the root one. So if the activity is already in the task, the intent will be redirected to
onNewIntent() else a new instance will be created. At a time only one instance of activity will
exist.
Eg: Suppose there is an activity stack of A -> B -> C -> D.
Now if we launch D with the launch mode as “singleTask”, the new stack will be A -> B ->
C -> D as usual.
Now if there is an activity stack of A -> B -> C -> D.
If we launch activity B again with the launch mode as “singleTask”, the new activity stack
will be A -> B. Activities C and D will be destroyed.

SingleInstance: Same as single task but the system does not launch any activities in the
same task as this activity. If new activities are launched, they are done so in a separate task.
Eg: Suppose there is an activity stack of A -> B -> C -> D. If we launch activity B again with
the launch mode as “singleInstance”, the new activity stack will be:
Task1—A -> B -> C
Task2—D

How does the activity respond when the user rotates the screen?
When the screen is rotated, the current instance of activity is destroyed a new instance of the
Activity is created in the new orientation. The onRestart() method is invoked first when a
screen is rotated. The other lifecycle methods get invoked in the similar flow as they were
when the activity was first created.’
Different between Service & Intent Service?
Service is the base class for Android services that can be extended to create any service. A
class that directly extends Service runs on the main thread so it will block the UI (if there is
one) and should therefore either be used only for short tasks or should make use of other
threads for longer tasks.
IntentService is a subclass of Service that handles asynchronous requests (expressed as
“Intents”) on demand. Clients send requests through startService(Intent) calls. The service is
started as needed, handles each Intent in turn using a worker thread, and stops itself when it
runs out of work.

Different between AsyncTasks &Threads?


AsyncTask can be used to handle work items shorter than 5ms in duration. With AsyncTask,
you can update UI unlike java Thread. But many long running tasks will choke the
performance.
Thread should be used to separate long running operations from main thread so that
performance is improved. But it can’t be cancelled elegantly and it can’t handle configuration
changes of Android. You can’t update UI from Thread.

Different between Service, Intent Service, AsyncTask &Threads?


Android service is a component that is used to perform operations on the background such
as playing music. It doesn’t has any UI (user interface). The service runs in the background
indefinitely even if application is destroyed.
AsyncTask allows you to perform asynchronous work on your user interface. It performs the
blocking operations in a worker thread and then publishes the results on the UI thread,
without requiring you to handle threads and/or handlers yourself.
IntentService is a base class for Services that handle asynchronous requests (expressed as
Intents) on demand. Clients send requests through startService(Intent) calls; the service is
started as needed, handles each Intent in turn using a worker thread, and stops itself when it
runs out of work.
A thread is a single sequential flow of control within a program. Threads can be thought of
as mini-processes running within a main process.

What are Handlers?


Handlers are objects for managing threads. It receives messages and writes code on how to
handle the message. They run outside of the activity’s lifecycle, so they need to be cleaned up
properly or else you will have thread leaks.
Handlers allow communicating between the background thread and the main thread.
A Handler class is preferred when we need to perform a background task repeatedly after
every x seconds/minutes.

Android Bound Service?


A bound service is a service that allows other android components (like activity) to bind to it
and send and receive data. A bound service is a service that can be used not only by
components running in the same process as local service, but activities and services, running
in different processes, can bind to it and send and receive data.
When implementing a bound service we have to extend Service class but we have to override
onBind method too. This method returns an object that implements IBinder, that can be used
to interact with the service.

Different between Serializable and Parcelable?


Serialization is the process of converting an object into a stream of bytes in order to store an
object into memory.
Parcelable is an Android specic interface where you implement the serialization yourself. It
was created to be far more ecient than Serializable.

How would you update the UI of an activity from a background


service?
We need to register a LocalBroadcastReceiver in the activity. And send a broadcast with the
data using intents from the background service. As long as the activity is in the foreground,
the UI will be updated from the background. Ensure to unregister the broadcast receiver in
the onStop() method of the activity to avoid memory leaks. We can also register a Handler
and pass data using Handlers.

What is a Sticky Intent?


Sticky Intents allows communication between a function and a service.
sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent you
are sending stays around after the broadcast is complete, so that others can quickly retrieve
that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter) . For
example, if you take an intent for ACTION_BATTERY_CHANGED to get battery change
events: When you call registerReceiver() for that action— even with a null
BroadcastReceiver—you get the Intent that was last Broadcast for that action. Hence, you
can use this to find the state of the battery without necessarily registering for all future state
changes in the battery.

What is a Pending Intent?


If you want someone to perform any Intent operation at future point of time on behalf of you,
then we will use Pending Intent.

What are intent Filters?


An intent filter is an expression in an app's manifest file that specifies the type of intents that
the component would like to receive

Difference between adding/replacing fragment in backstack?


replace removes the existing fragment and adds a new fragment. This means when you press
back button the fragment that got replaced will be created with its onCreateView being
invoked.
add retains the existing fragments and adds a new fragment that means existing fragment will
be active and they wont be in ‘paused’ state hence when a back button is pressed
onCreateView is not called for the existing fragment(the fragment which was there before
new fragment was added).

You’re replacing one Fragment with another—how do you ensure


that the user can return to the previous Fragment, by pressing the
Back button?
We need to save each Fragment transaction to the backstack, by calling addToBackStack()
before you commit() that transaction

Callbacks invoked during addition of a fragment to back stack


and while popping back from back stack?
addOnBackStackChangedListener is called when fragment is added or removed from the
backstack.

What are retained fragments?


By default, Fragments are destroyed and recreated along with their parent Activity’s when a
configuration change occurs. Calling setRetainInstance(true) allows us to bypass this
destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment
when the activity is recreated.

What are Loaders in Android?


Loader API was introduced in API level 11 and is used to load data from a data source to
display in an activity or fragment. Loaders persist and cache results across configuration
changes to prevent duplicate queries.

What is the difference between Dialog & DialogFragment?


A fragment that displays a dialog window, floating on top of its activity’s window. This
fragment contains a Dialog object, which it displays as appropriate based on the fragment’s
state. Dialogs are entirely dependent on Activities. If the screen is rotated, the dialog is
dismissed.
Dialog fragments take care of orientation, configuration changes as well.

Difference between margin & padding?


Padding will be space added inside the container, for instance, if it is a button, padding will
be added inside the button.
Margin will be space added outside the container.

Difference between RelativeLayout and LinearLayout?


Linear Layout—Arranges elements either vertically or horizontally. i.e. in a row or column.
Relative Layout—Arranges elements relative to parent or other elements.

What is ConstraintLayout?
It allows you to create large and complex layouts with a at view hierarchy (no nested view
groups). It’s similar to RelativeLayout in that all views are laid out according to relationships
between sibling views and the parent layout, but it’s more flexible than RelativeLayout and
easier to use with Android Studio’s Layout Editor

When might you use a FrameLayout?


Frame Layouts are designed to contain a single item, making them an efficient choice when
you need to display a single View.
If you add multiple Views to a FrameLayout then it’ll stack them one above the other, so
FrameLayouts are also useful if you need overlapping Views, for example if you’re
implementing an overlay or a HUD element.

What are Adapters?


An adapter responsible for converting each data entry into a View that can then be added to
the AdapterView (ListView/RecyclerView).

What is an Application Not Responding (ANR) error, and how


can you prevent them from occurring in an app?
An ANR dialog appears when your UI has been unresponsive for more than 5 seconds,
usually because you’ve blocked the main thread. To avoid encountering ANR errors, you
should move as much work o the main thread as possible.

What’s the Difference between commit() and apply() in


SharedPreferences?
commit() writes the data synchronously and returns a boolean value of success or failure
depending on the result immediately.
apply() is asynchronous and it won’t return any boolean response. Also if there is an apply()
outstanding and we perform another commit(). The commit() will be blocked until the apply()
is not completed.

How does RecyclerView work?


RecyclerView is designed to display long lists (or grids) of items. Say we want to display 100
row of items. A simple approach would be to just create 100 views, one for each row and lay
all of them out. But that would be wasteful because at any point of time, only 10 or so items
could t on screen and the remaining items would be o screen. So RecyclerView instead
creates only the 10 or so views that are on screen. This way you get 10x better speed and
memory usage.
But what happens when you start scrolling and need to start showing next views?
Again, a simple approach would be to create a new view for each new row that you need to
show. But this way by the time you reach the end of the list you will have created 100 views
and your memory usage would be the same as in the first approach. And creating views takes
time, so your scrolling most probably wouldn’t be smooth.
This is why RecyclerView takes advantage of the fact that as you scroll, new rows come
on screen also old rows disappear o screen. Instead of creating new view for each new
row, an old view is recycled and reused by binding new data to it.
This happens inside the onBindViewHolder() method. Initially you will get new unused view
holders and you have to fill them with data you want to display. But as you scroll you will
start getting view holders that were used for rows that went off screen and you have to
replace old data that they held with new data.

How does RecyclerView differ from ListView?


ViewHolder Pattern: Recyclerview implements the ViewHolders pattern whereas it is not
mandatory in a ListView. A RecyclerView recycles and reuses cells when scrolling.
What is a ViewHolder Pattern? —A ViewHolder object stores each of the component
views inside the tag eld of the Layout, so you can immediately access them without the need
to look them up repeatedly. In ListView, the code might call findViewById() frequently
during the scrolling of ListView, which can slow down performance. Even when the Adapter
returns an inflated view for recycling, you still need to look up the elements and update them.
A way around repeated use of findViewById() is to use the "view holder" design pattern.
LayoutManager: In a ListView, the only type of view available is the vertical ListView. A
RecyclerView decouples list from its container so we can put list items easily at run time in
the different containers (LinearLayout, GridLayout) by setting LayoutManager.
Item Animator: ListViews are lacking in support of good animations, but the RecyclerView
brings a whole new dimension to it.

Difference between MVC & MVP & MVVM?

MVC: Model View Controller


Model:
1. Represents the data models.
2. Manages the Data States
3. Has business Logics

View:
1. The way we represent our data e.g. Views/layouts in Android.
2. Renders the UI.

Controller:
1. Handles user interactions with our application.
2. The communication channel between the model and the view.
e.g. the fragments/Activities in Android.
The MVC flow diagram will look like:

The user interacts with the UI, and the controller gets notified via the view. Based on the User
interaction the controller modifies certain Models. Models perform some business logic and
return the updated model data state to the controller. The controller can then update the UI
according to the new data state as received from Model.

MVP: Model View Presenter


Model:
Same as in MVC pattern.

View:
1. The way we represent our data e.g. Views/layouts as well as Activities/Fragments in
Android.
2. Will implement an interface for the Presenter’s Actions.

Presenter:
1. Has no relation to the views(Unlike MVC).
2. Operations are invoked by our views.
3. Views are updated via View’s Interface.

The MVP flow diagram will look like:


Although the Flow diagram looks same as MVC the difference is how the VIew and
Presenters/Controllers interacts with each other.

So the model remains the same(as in MVC).


The presenter here just performs the Interface actions and has no knowledge of the Views it is
trying to update.
So the views implementing that interface updates the UI.

It is far better than MVC as here the presenter has NO ANDROID API and it can be easily
tested.
The views can be tested using espresso etc to see if the views are updated or not.

MVVM- Model View ViewModel


It further minimizes the view binding code i.e. how the view is bind to the model data.

Talking in the Android ecosystem, it uses the Data binding library from Google, and the
View’s binding logic is implemented in the XML layouts.

Model:
Same as in MVC/MVP pattern.

View:
1. Same as in MVC/MVP pattern.

ViewModel:
1. It contains the Model.
2. Uses observable values for update values.
3. On the value update, the relevant views will get updates(uses Data Binding Library).

The MVP flow diagram will look like:

So the view receives the User interactions and will notify the view model.
Now the ViewModel will update the model as well as the Observable(which will invoke the
value change). Next, the ViewModel interface will update the UI(XML layouts) directly.

Kotlin Interview Questions

1. How does Kotlin work on Android?


Just like Java, the Kotlin code is also compiled into the Java bytecode and is executed at
runtime by the Java Virtual Machine i.e. JVM. When a Kotlin file named Main.kt is compiled
then it will eventually turn into a class and then the bytecode of the class will be generated.
The name of the bytecode file will be MainKt.class and this file will be executed by the JVM.

2. Why should we use Kotlin?


● Kotlin is concise
● Kotlin is null-safe
● Kotlin is interoperable
3. What is the difference between the variable declaration with
var and val?
If you want to declare some mutable(changeable) variable, then you can use var. For the
immutable variable, use val i.e. val variables can't be changed once assigned.

4. What is the difference between the variable declaration with


val and const?
Both the variables that are declared with val and const are immutable in nature. But the value
of the const variable must be known at the compile-time whereas the value of the val variable
can be assigned at runtime also.

5. How to ensure null safety in Kotlin?


One of the major advantages of using Kotlin is null safety. In Java, if you access some null
variable then you will get a NullPointerException. So, the following code in Kotlin will
produce a compile-time error:

var name: String = "MindOrks"


name = null //error
So, to assign null values to a variable, you need to declare the name variable as a nullable
string and then during the access of this variable, you need to use a safe call operator i.e. ?.

var name: String? = "MindOrks"


print(name?.length) // ok
name = null // ok

6. What is the difference between safe calls(?.) and null check(!!)?


Safe call operator i.e. ?. is used to check if the value of the variable is null or not. If it is null
then null will be returned otherwise it will return the desired value.

var name: String? = "MindOrks"


println(name?.length) // 8
name = null
println(name?.length) // null

If you want to throw NullPointerException when the value of the variable is null, then you
can use the null check or !! operator.

var name: String? = "MindOrks"


println(name?.length) // 8
name = null
println(name!!.length) // KotlinNullPointerException

7. Do we have a ternary operator in Kotlin just like java?


No, we don't have a ternary operator in Kotlin but you can use the functionality of ternary
operator by using if-else or Elvis operator.

8. What is Elvis operator in Kotlin?


In Kotlin, you can assign null values to a variable by using the null safety property. To check
if a value is having null value then you can use if-else or can use the Elvis operator i.e. ?:

 For example:

var name:String? = "Mindorks"


val nameLength = name?.length ?: -1
println(nameLength)
The Elvis operator(?:) used above will return the length of name if the value is not null
otherwise if the value is null, then it will return -1.

9. How to convert a Kotlin source file to a Java source file?


Steps to convert your Kotlin source file to Java source file:

1. Open your Kotlin project in the IntelliJ IDEA / Android Studio.


2. Then navigate to Tools > Kotlin > Show Kotlin Bytecode.
3. Now click on the Decompile button to get your Java code from the bytecode.

10. What is the use of @JvmStatic, @JvmOverloads, and


@JvmFiled in Kotlin?
● @JvmStatic: This annotation is used to tell the compiler that the method is a static
method and can be used in Java code.
● @JvmOverloads: To use the default values passed as an argument in Kotlin code
from the Java code, we need to use the @JvmOverloads annotation.
● @JvmField: To access the fields of a Kotlin class from Java code without using any
getters and setters, we need to use the @JvmField in the Kotlin code.
11. What is a data class in Kotlin?
Data classes are those classes which are made just to store some data. In Kotlin, it is marked
as data. The following is an example of the same:

data class Developer(val name: String, val age: Int)


When we mark a class as a data class, you don’t have to implement or create the following
functions like we do in Java: hashCode(), equals(), toString(), copy(). The compiler
automatically creates these internally, so it also leads to clean code. Although, there are few
other requirements that data classes need to fulfill.

12. Can we use primitive types such as int, double, float in Kotlin?
In Kotlin, we can't use primitive types directly. We can use classes like Int, Double, etc. as an
object wrapper for primitives. But the compiled bytecode has these primitive types.

13. What is String Interpolation in Kotlin?


If you want to use some variable or perform some operation inside a string then String
Interpolation can be used. You can use the $ sign to use some variable in the string or can
perform some operation in between {} sign.

var name = "MindOrks"


print("Hello! I am learning from $name")

14. What do you mean by destructuring in Kotlin?


Destructuring is a convenient way of extracting multiple values from data stored in(possibly
nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand
side of an assignment). Sometimes it is convenient to destructure an object into a number of
variables, for example:

val (name, age) = developer


Now, we can use name and age independently like below:

println(name)
println(age)

15. When to use the lateinit keyword in Kotlin?


lateinit is late initialization.

Normally, properties declared as having a non-null type must be initialized in the constructor.
However, fairly often this is not convenient.
For example, properties can be initialized through dependency injection, or in the setup
method of a unit test. In this case, you cannot supply a non-null initializer in the constructor,
but you still want to avoid null checks when referencing the property inside the body of a
class. To handle this case, you can mark the property with the lateinit modifier.

16. How to check if a lateinit variable has been initialized or not?


You can check if the lateinit variable has been initialized or not before using it with the help
of isInitialized method. This method will return true if the lateinit property has been
initialized otherwise it will return false. For example:

class Person {
lateinit var name: String
fun initializeName() {
println(this::name.isInitialized)
name = "MindOrks" // initializing name
println(this::name.isInitialized)
}
}
fun main(args: Array<String>) {
Person().initializeName()
}

17. What is the difference between lateinit and lazy in Kotlin?


● lazy can only be used for val properties, whereas lateinit can only be applied to var
because it can’t be compiled to a final field, thus no immutability can be guaranteed.
● If you want your property to be initialized from outside in a way probably unknown
beforehand, use lateinit.

18. Is there any difference between == operator and ===


operator?
Yes. The == operator is used to compare the values stored in variables and the === operator
is used to check if the reference of the variables are equal or not. But in the case of primitive
types, the === operator also checks for the value and not reference.

// primitive example
val int1 = 10
val int2 = 10
println(int1 == int2) // true
println(int1 === int2) // true
// wrapper example
val num1 = Integer(10)
val num2 = Integer(10)
println(num1 == num2) // true
println(num1 === num2) //false

19. What is the forEach in Kotlin?


In Kotlin, to use the functionality of a for-each loop just like in Java, we use
a forEach function. The following is an example of the same:

var listOfMindOrks = listOf("mindorks.com", "blog.mindorks.com", "afteracademy.com")


listOfMindOrks.forEach {
Log.d(TAG,it)
}

20. What are companion objects in Kotlin?


In Kotlin, if you want to write a function or any member of the class that can be called
without having the instance of the class then you can write the same as a member of a
companion object inside the class.

To create a companion object, you need to add the companion keyword in front of the object


declaration.

The following is an example of a companion object in Kotlin:

class ToBeCalled {
companion object Test {
fun callMe() = println("You are calling me :)")
}
}
fun main(args: Array<String>) {
ToBeCalled.callMe()
}

21. What is the equivalent of Java static methods in Kotlin?


To achieve the functionality similar to Java static methods in Kotlin, we can use:

● companion object
● package-level function
● object
22. What is the difference between FlatMap and Map in Kotlin?
● FlatMap is used to combine all the items of lists into one list.
● Map is used to transform a list based on certain conditions.

23. What is the difference between List and Array types in


Kotlin?
If you have a list of data that is having a fixed size, then you can use an Array. But if the size
of the list can vary, then we have to use a mutable list.

24. Can we use the new keyword to instantiate a class object in


Kotlin?
No, in Kotlin we don't have to use the new keyword to instantiate a class object. To
instantiate a class object, simply we use:

var varName = ClassName()

25. What are visibility modifiers in Kotlin?


A visibility modifier or access specifier or access modifier is a concept that is used to define
the scope of something in a programming language. In Kotlin, we have four visibility
modifiers:

● private: visible inside that particular class or file containing the declaration.


● protected: visible inside that particular class or file and also in the subclass of that
particular class where it is declared.
● internal: visible everywhere in that particular module.
● public: visible to everyone.

26. How to create a Singleton class in Kotlin?


A singleton class is a class that is defined in such a way that only one instance of the class
can be created and is used where we need only one instance of the class like in logging,
database connections, etc.

To create a Singleton class in Kotlin, you need to use the object keyword.
object AnySingletonClassName
Note: You can't use constructor in object, but you can use init.

27. What are init blocks in Kotlin?


init blocks are initializer blocks that are executed just after the execution of the primary
constructor. A class file can have one or more init blocks that will be executed in series. If
you want to perform some operation in the primary constructor, then it is not possible in
Kotlin, for that, you need to use the init block.

28. What are the types of constructors in Kotlin?


● Primary constructor: These constructors are defined in the class header and you
can't perform some operation in it, unlike Java's constructor.
● Secondary constructor: These constructors are declared inside the class body by
using the constructor keyword. You must call the primary constructor from the
secondary constructor explicitly. Also, the property of the class can’t be declared
inside the secondary constructor. There can be more than one secondary constructors
in Kotlin.

29. Is there any relationship between primary and secondary


constructors?
Yes, when using a secondary constructor, you need to call the primary constructor explicitly.

30. What is the default type of argument used in a constructor?


By default, the type of arguments of a constructor in val. But you can change it to var
explicitly.

31. What are Coroutines in Kotlin?


A framework to manage concurrency in a more performant and simple way with its
lightweight thread which is written on top of the actual threading framework to get the most
out of it by taking the advantage of cooperative nature of functions.

32. What is suspend function in Kotlin Coroutines?


Suspend function is the building block of the Coroutines in Kotlin. Suspend function is a
function that could be started, paused, and resume. To use a suspend function, we need to use
the suspend keyword in our normal function definition.
33. What is the difference between Launch and Async in Kotlin
Coroutines?
The difference is that the launch{} does not return anything and the async{} returns an
instance of Deferred<T>, which has an await() function that returns the result of the coroutine
like we have future in Java in which we do future.get() to the get the result.

In other words:

● launch: fire and forget


● async: perform a task and return a result

34. What are scopes in Kotlin Coroutines?


Coroutines = Co + Routines

Here, Co means cooperation and Routines means functions.
It means that when functions cooperate with each other, we call it as Coroutines.

Let's understand this with an example. I have written the below code in a different way just
for the sake of understanding. Suppose we have two functions as functionA and functionB.

functionA as below:
fun functionA(case: Int) {
when (case) {
1 -> {
taskA1()
functionB(1)
}
2 -> {
taskA2()
functionB(2)
}
3 -> {
taskA3()
functionB(3)
}
4 -> {
taskA4()
functionB(4)
}
}
}
And functionB as below:

fun functionB(case: Int) {


when (case) {
1 -> {
taskB1()
functionA(2)
}
2 -> {
taskB2()
functionA(3)
}
3 -> {
taskB3()
functionA(4)
}
4 -> {
taskB4()
}
}
}
Then, we can call the functionA as below:

functionA(1)

Here, functionA will do the taskA1 and give control to the functionB to execute the taskB1.


Then, functionB will do the taskB1 and give the control back to the functionA to execute
the taskA2 and so on.

The important thing is that functionA and functionB are cooperating with each other.

With Kotlin Coroutines, the above cooperation can be done very easily which is without the
use of when or switch case which I have used in the above example for the sake of
understanding

35. How Exception Handling is done in Kotlin Coroutines?


Coroutines have become a new way for us to do asynchronous programming in Android
using Kotlin. When building a production-ready app, we want to handle all our exceptions
properly for users to have a smooth experience while using our app.

What are the exceptions?


Exceptions are the unexpected events that come up while running or performing any
program. Due to exceptions, the execution is disturbed and the expected flow of the
application is not executed.

That is why we need to handle the exceptions in our code to execute the proper flow of the
app.

How do we handle exceptions in a general way?


A generic way to handle exception in kotlin is to use a try-catch block. Where we write our
code which might throw an exception in the try block, and if there is any exception generated,
then the exception is caught in the catch block.

Let us understand by example,

try {
val solution = 5 / 0
val addition = 2 + 5
Log.d("MainActivity", solution.toString())
Log.d("MainActivity", addition.toString())
} catch (e: Exception) {
Log.e("MainActivity", e.toString())
}
In this above code, we are trying to first divide 5 by 0 and also we want to add two
numbers 2,5. Then we want to print the solution in Logcat. When we run the app, the proper
flow should be first we get the value in the solution variable and then assign the sum in
addition variable. Later, we want to print the values in the Log statement.
But, when we run the app we would see the following output,

E/MainActivity: java.lang.ArithmeticException: divide by zero

Here, the solution and addition variables are not printed but the Log statement in


the catch block is printed with an Arithmetic Exception. The reason here is, that any number
can't be divided by 0. So, when we got the exception you can see that no step was performed
below the first line and it directly went to catch block.

How do we handle exceptions in Kotlin Coroutines efficiently?


Now, we are going to discuss how we can handle exception efficiently while using Kotlin
Coroutines in our project. There are the following ways to handle exceptions,

● Generic way
● Using CoroutineExceptionHandler
● Using SupervisorScope
To discuss this further, we will use an example of fetching a list of users. We would have an
interface,

interface ApiService {

@GET("users")
suspend fun getUsers(): List<ApiUser>

@GET("more-users")
suspend fun getMoreUsers(): List<ApiUser>

@GET("error")
suspend fun getUsersWithError(): List<ApiUser>

36. How to choose between a switch and when in Kotlin?


Whenever we want to handle many if-else conditions, then we generally use switch-case
statements. But Kotlin provides a more concise option i.e. in Kotlin, we can use when in
place of the switch. And, when can be used as:

● expression
● arbitrary condition expression
● without argument

● with two or more choices


For example:

when(number) {
1 -> println("One")
2, 3 -> println("Two or Three")
4 -> println("Four")
else -> println("Number is not between 1 and 4")
}

37. What is the open keyword in Kotlin used for?


By default, the classes and functions are final in Kotlin. So, you can't inherit the class or
override the functions. To do so, you need to use the open keyword before the class and
function.

38. What are lambdas expressions?


Lambdas expressions are anonymous functions that can be treated as values i.e. we can pass
the lambdas expressions as arguments to a function return them, or do any other thing we
could do with a normal object. For example:

val add : (Int, Int) -> Int = { a, b -> a + b }


val result = add(9, 10)

39. What are Higher-Order functions in Kotlin?


A higher-order function is a function that takes functions as parameters or returns a function.
For example, A function can take functions as parameters.

fun passMeFunction(abc: () -> Unit) {


// I can take function
// do something here
// execute the function
abc()
}
For example, A function can return another function.

fun add(a: Int, b: Int): Int {


return a + b
}
And, we have a function returnMeAddFunction which takes zero parameters and returns a
function of the type ((Int, Int) -> Int).

fun returnMeAddFunction(): ((Int, Int) -> Int) {


// can do something and return function as well
// returning function
return ::add
}
And to call the above function, we can do:

val add = returnMeAddFunction()


val result = add(2, 2)

40. What are extension functions in Kotlin?


Extension functions are like extensive properties attached to any class in Kotlin. By using
extension functions, you can add some methods or functionalities to an existing class even
without inheriting the class. For example: Let's say, we have views where we need to play
with the visibility of the views. So, we can create an extension function for views like,

fun View.show() {
this.visibility = View.VISIBLE
}

fun View.hide() {
this.visibility = View.GONE
}
and to use it we use, like,

toolbar.hide()

41. What is an infix function in Kotlin?


An infix function is used to call the function without using any bracket or parenthesis. You
need to use the infix keyword to use the infix function.

class Operations {
var x = 10;
infix fun minus(num: Int) {
this.x = this.x - num
}
}
fun main() {
val opr = Operations()
opr minus 8
print(opr.x)
}

42. What is an inline function in Kotlin?


Inline function instruct compiler to insert complete body of the function wherever that
function got used in the code. To use an Inline function, all you need to do is just add an
inline keyword at the beginning of the function declaration.

43. What is noinline in Kotlin?


While using an inline function and want to pass some lambda function and not all lambda
function as inline, then you can explicitly tell the compiler which lambda it shouldn't inline.

inline fun doSomethingElse(abc: () -> Unit, noinline xyz: () -> Unit) {


abc()
xyz()
}

44. What are Reified types in Kotlin?


When you are using the concept of Generics to pass some class as a parameter to some
function and you need to access the type of that class, then you need to use the reified
keyword in Kotlin.

For example:

inline fun <reified T> genericsExample(value: T) {


println(value)
println("Type of T: ${T::class.java}")
}
fun main() {
genericsExample<String>("Learning Generics!")
genericsExample<Int>(100)
}
45. What is the operator overloading in Kotlin?
In Kotlin, we can use the same operator to perform various tasks and this is known as
operator overloading. To do so, we need to provide a member function or an extension
function with a fixed name and operator keyword before the function name because normally
also, when we are using some operator then under the hood some function gets called. For
example, if you are writing num1+num2, then it gets converted to num1.plus(num2).

For example:

fun main() {
val bluePen = Pen(inkColor = "Blue")
bluePen.showInkColor()

val blackPen = Pen(inkColor = "Black")


blackPen.showInkColor()

val blueBlackPen = bluePen + blackPen


blueBlackPen.showInkColor()
}

operator fun Pen.plus(otherPen: Pen):Pen{


val ink = "$inkColor, ${otherPen.inkColor}"
return Pen(inkColor = ink)
}

data class Pen(val inkColor:String){


fun showInkColor(){ println(inkColor)}
}

47. What are pair and triple in Kotlin?


Pair and Triples are used to return two and three values respectively from a function and the
returned values can be of the same data type or different.

val pair = Pair("My Age: ", 25)


print(pair.first + pair.second)

48. What are labels in Kotlin?


Any expression written in Kotlin is called a label. For example, if we are having a for-loop in
our Kotlin code then we can name that for-loop expression as a label and will use the label
name for the for-loop.
We can create a label by using an identifier followed by the @ sign. For
example, name@, loop@, xyz@, etc. The following is an example of a label:

loop@ for (i in 1..10) {


// some code goes here
}
The name of the above for-loop is loop.

49. What are the benefits of using a Sealed Class over Enum?
Sealed classes give us the flexibility of having different types of subclasses and also
containing the state. The important point to be noted here is the subclasses that are
extending the Sealed classes should be either nested classes of the Sealed class or should be
declared in the same file as that of the Sealed class.

50. What are collections in Kotlin?


Collections in Kotlin are used to store group of related objects in a single unit. By using
collection, we can store, retrieve manipulate and aggregate data.

Types of Kotlin Collections


Kotlin collections are broadly categories into two different forms. These are:
1. Immutable Collection (or Collection)
2. Mutable Collection

Immutable Collection:
Immutable collection also called Collection supports read only functionalities. Methods of immutable collection
that supports read functionalities are:

Collection Types Methods of Immutable Collection

List listOf()
listOf<T>()

Map mapOf()

Set setOf()
Mutable Collection:
Mutable collections supports both read and write functionalities. Methods of mutable collections that supports
read and write functionalities are:

Collection Types Methods of Mutable Collection

List ArrayList<T>()
arrayListOf()
mutableListOf()

Map HashMap
hashMapOf()
mutableMapOf()

Set hashSetOf()
mutableSetOf()

PART 2

1. What’s the Target Platform of Kotlin? How is Kotlin-Java


interoperability possible?

Java Virtual Machine(JVM) is the Target Platform of Kotlin. Kotlin is 100%


interoperable with Java since both, on compilation produce bytecode. Hence
Kotlin code can be called from Java and vice-versa.

2. How do you declare variables in Kotlin? How does the


declaration differ from the Java counterpart?

There are two major differences between Java and Kotlin variable
declaration:

o The type of declaration


In Java the declaration look like this:
o
o String s = "Java String";
o int x = 10;
In Kotlin the declaration looks like:

val s: String = "Hi"


var x = 5
In Kotlin, the declaration begins with a val and a var followed by the
optional type. Kotlin can automatically detect the type using type
inference.

o Default value
The following is possible in Java:
o
o String s:

The following variable declaration in Kotlin is not valid.

val s: String

3. What’s the difference between val and var declaration? How


to convert a String to an Int?
val variablescannot be changed. They’re like final modifiers in Java.
A var can be reassigned. The reassigned value must be of the same data type.

fun main(args: Array<String>) {


val s: String = "Hi"
var x = 5
x = "6".toInt()
}
We use the toInt() method to convert the String to an Int.

4. What’s Null Safety and Nullable Types in Kotlin? What is


the Elvis Operator?
Kotlin puts a lot of weight behind null safety which is an approach to
prevent the dreaded Null Pointer Exceptions by using nullable types which
are like String?, Int?, Float? etc. These act as a wrapper type and can hold null
values. A nullable value cannot be added to another nullable or basic type of
value.
To retrieve the basic types we need to use safe calls that unwrap the Nullable
Types. If on unwrapping, the value is null we can choose to ignore or use a
default value instead. The Elvis Operator is used to safely unwrap the value
from the Nullable.
It’s represented as ?: over the nullable type. The value on the right hand side
would be used if the nullable type holds a null.

var str: String? = "JournalDev.com"


var newStr = str?: "Default Value"
str = null
newStr = str?: "Default Value"

5. What’s a const? How does it differ from a val?

By default val properties are set at runtime. Adding a const modifier on


a val would make a compile-time constant.
A const cannot be used with a var or on its own.
A const is not applicable on a local variable.

6. Does Kotlin allow us to use primitive types such as int, float,


double?

At the language level, we cannot use the above-mentioned types. But the
JVM bytecode that’s compiled does certainly have them.

7. What’s the entry point of every Kotlin Program?


The main function is the entry point of every Kotlin program. In Kotlin we
can choose not to write the main function inside the class. On compiling the
JVM implicitly encapsulates it in a class.
The strings passed in the form of Array<String> are used to retrieve the
command line arguments.

8. How is !!different from ?. in unwrapping the nullable


values? Is there any other way to unwrap nullable values
safely?
!! isused to force unwrap the nullable type to get the value. If the value
returned is a null, it would lead to a runtime crash. Hence a !! operator
should be only used when you’re absolutely sure that the value won’t be null
at all. Otherwise, you’ll get the dreaded null pointer exception. On the other
hand, a ?. is an Elvis Operator that does a safe call.
We can use the lambda expression let on the nullable value to unwrap safely
as shown below.

Here the let expression does a safe call to unwrap the nullable type.

9. How is a function declared? Why are Kotlin functions


known as top-level functions?
fun sumOf (a: Int, b: Int): Int{
return a + b
}
A function’s return type is defined after the : Functions in Kotlin can be declared at the root
of the Kotlin file.

10. What’s the difference between == and === operators in


Kotlin?

== is used to compare the values are equal or not. === is used to check if the
references are equal or not.
11. List down the visibility modifiers available in Kotlin.
What’s the default visibility modifier?
o public
o internal
o protected
o private

public is the default visibility modifier.

12. Does the following inheritance structure compile?

class A{
}
class B : A(){
}

NO. By default classes are final in Kotlin. To make them non-final, you need to
add the open modifier.

open class A{
}

class B : A(){

13. What are the types of constructors in Kotlin? How are


they different? How do you define them in your class?

Constructors in Kotlin are of two types:


Primary – These are defined in the class headers. They cannot hold any
logic. There’s only one primary constructor per class.
Secondary – They’re defined in the class body. They must delegate to the
primary constructor if it exists. They can hold logic. There can be more than
one secondary constructors.

class User(name: String, isAdmin: Boolean){

constructor(name: String, isAdmin: Boolean, age: Int) :this(name, isAdmin)


{
this.age = age
}

14. What’s init block in Kotlin


init is
the initialiser block in Kotlin. It’s executed once the primary
constructor is instantiated. If you invoke a secondary constructor, then it
works after the primary one as it is composed in the chain.

15. How does string interpolation work in Kotlin? Explain


with a code snippet?

String interpolation is used to evaluate string templates.


We use the symbol $ to add variables inside a string.

val name = "Journaldev.com"


val desc = "$name now has Kotlin Interview Questions too. ${name.length}"
Using {} we can compute an expression too.

16. What’s the type of arguments inside a constructor?


By default, the constructor arguments are val unless explicitly set to var.

17. Is new a keyword in Kotlin? How would you instantiate a


class object in Kotlin?

NO. Unlike Java, in Kotlin, new isn’t a keyword.


We can instantiate a class in the following way:

class A
var a = A()
val new = A()
18. What is the equivalent of switch expression in Kotlin?
How does it differ from switch?
when is the equivalent of switch in Kotlin.
The default statement in a when is represented using the else statement.

var num = 10
when (num) {
0..4 -> print("value is 0")
5 -> print("value is 5")
else -> {
print("value is in neither of the above.")
}
}
when statments have a default break statement in them.

19. What are data classes in Kotlin? What makes them so


useful? How are they defined?
In Java, to create a class that stores data, you need to set the variables, the
getters and the setters, override the toString(), hash() and copy() functions.
In Kotlin you just need to add the data keyword on the class and all of the
above would automatically be created under the hood.

data class Book(var name: String, var authorName: String)

fun main(args: Array<String>) {


val book = Book("Kotlin Tutorials","Anupam")
}
Thus, data classes saves us with lot of code.
It creates component functions such as component1().. componentN() for each of
the variables.
20. What are destructuring declarations in Kotlin? Explain it
with an example.

Destructuring Declarations is a smart way to assign multiple values to


variables from data stored in objects/arrays.

Within paratheses, we’ve set the variable declarations. Under the hood,
destructuring declarations create component functions for each of the class
variables.

21. What’s the difference between inline and infix functions?


Give an example of each.

Inline functions are used to save us memory overhead by preventing object


allocations for the anonymous functions/lambda expressions called. Instead,
it provides that functions body to the function that calls it at runtime. This
increases the bytecode size slightly but saves us a lot of memory.
infix functions on the other are used to call functions without parentheses or
brackets. Doing so, the code looks much more like a natural language.

22. What’s the difference between lazy and lateinit?


Both are used to delay the property initializations in Kotlin
lateinit is a modifier used with var and is used to set the value to the var at a
later point.
lazy is a method or rather say lambda expression. It’s set on a val only. The
val would be created at runtime when it’s required.

val x: Int by lazy { 10 }


lateinit var y: String

23. How to create Singleton classes?


To use the singleton pattern for our class we must use the keyword object

object MySingletonClass
An object cannot have a constructor set. We can use the init block inside it
though.

24. Does Kotlin have the static keyword? How to create static
methods in Kotlin?
NO. Kotlin doesn’t have the static keyword.
To create static method in our class we use the companion object.
Following is the Java code:
class A {
public static int returnMe() { return 5; }
}

The equivalent Kotlin code would look like this:

class A {
companion object {
fun a() : Int = 5
}
}
To invoke this we simply do: A.a().

25. What’s the type of the following Array?

val arr = arrayOf(1, 2, 3);

The type is Array<Int>.

Tell some advantages of Kotlin over Java? or What are the Kotlin
functionalities that we can't achieve in java?

- Null safety
- Kotlin coroutines
- Triple and Pair structures
- Destructuring Initialization
- Inline functions
- Infix functions
- Scope functions
- We can write functions at the file level.

Picasso
(-)

● Slow loading big images from internet into ListView

(+)

● Tinny size of library


● Small size of cache
● Simple to use
● UI does not freeze
● WebP support

Glide
(-)

● Big size of library

(+)

● Tinny size of cache


● Simple to use
● GIF support
● WebP support
● Fast loading big images from internet into ListView
● UI does not freeze
● BitmapPool to re-use memory and thus lesser GC events

What are the bit sizes for Kotlin basic data types?
- Byte 8 bits
- Short 16 bits
- Int 32 bits
- Long 64 bits
- Float 32 bits
- Double 64 bits

var:
● Declare a variable whose value can be changed at any time.
● This is commonly used for declaring a variable with global scope.
● It is re-assign able.
● It is not re-declarable in its scope.

val:
● It is used to define constants at run time. A major difference from const.
● It is not re-assign able in its scope.
● It is not re-declarable in its scope.
● The declaration is block function scoped.

const:
● When you know at compile time that it’s never gonna change.
● It is not re-assign able in its scope.
● It is not re-declarable in its scope.
Difference between Volley and Retrofit?

Volley-

● No automatic parsing
● Caching Mechanism
● volley we can set a retry policy using setRetryPolicy method
● inbuilt image loading support

Retrofit-

● Automatic JSON parsing


● No Caching mechanism
● Retrofit does not support any retrying mechanism
● no Image loading

Difference between MVC & MVP & MVVM?


● MVC is the Model-View-Controller architecture where model refers to the data model classes. The
view refers to the xml files and the controller handles the business logic. The issue with this
architecture is unit testing. The model can be easily tested since it is not tied to anything. The controller
is tightly coupled with the android apis making it difficult to unit test. Modularity & flexibility is a
problem since the view and the controller are tightly coupled. If we change the view, the controller
logic should also be changed. Maintenance is also an issues.

● MVP architecture: Model-View-Presenter architecture. The View includes the xml and the
activity/fragment classes. So the activity would ideally implement a view interface making it easier for
unit testing (since this will work without a view).

● MVVM: Model-View-ViewModel Architecture. The Model comprises data, tools for data processing,
business logic. The View Model is responsible for wrapping the model data and preparing the data for
the view. IT also provides a hook to pass events from the view to the model.

What are the coroutines?


A coroutine in Kotlin programming language is the feature that helps to converts asynchronous background
processes to the sequential code.

● Managing background threads.


● It helps in thread concurrency efficiently.
● Replace traditional callbacks.
● Maps the async code into the sequential code.
● Main thread safety.
Kotlin Coroutines on Android

Asynchronous programming is very important and it’s now a common part of modern application. It increases
the amount of work that your app can perform in parallel. This allows running heavy tasks away from UI Thread
in the background, which ultimately gives a smooth and better experience to the user of the app.
Coroutine in Kotlin
The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can
execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other
languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify
async code.

The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating
coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the
purpose of which task to execute next and which tasks later.

Coroutines are basically of two types:

● Stackless
● Stackful

Kotlin implements stackless coroutines, it means that the coroutines don’t have their own stack, so they don’t
map on the native thread.

Why we need coroutines?


As we know android developers today have many async tools in hand. These include RxJava, AsyncTasks, Jobs,
Threads. So why there is a need to learn something new?

● While Using Rx, it requires a lot of effort to get it enough, to use it safely. On the Other hand,
AsyncTasks and threads can easily introduce leaks and memory overhead. Even using these tools after
so many disadvantages, the code can suffer from callbacks, which can introduce tons of extra code. Not
only that, but the code also becomes unreadable as it has many callbacks which ultimately slow down
or hang the device leading to poor user experience.

● Android is a single thread platform, By default, everything runs on the main thread. In Android, almost
every application needs to perform some non UI operations like (Network call, I/O operations), so
when coroutines concept is not introduced, what is done is that programmer dedicate this task to
different threads, each thread executes the task given to it, when the task is completed, they return the
result to UI thread to update the changes required. Though In android there is a detailed procedure
given, about how to perform this task in an effective way using best practices using threads, this
procedure includes lots of callbacks for passing the result among threads, which ultimately introduce
tons of code in our application and the waiting time to get the result back to increases.

● On Android, Every app has a main thread (which handles all the UI operations like drawing views and
other user interactions. If there is too much work happening on this main thread, like network calls (eg
fetching a web page), the apps will appear to hang or slow down leading to poor user experience.
Kotlin Coroutines Features
Coroutines is the recommended solution for asynchronous programming on Android. Some highlighted features
of coroutines are given below.

● Lightweight: One can run many coroutines on a single thread due to support for suspension, which
doesn’t block the thread where the coroutine is running. Suspending frees memory over blocking while
supporting multiple concurrent operations.
● Built-in cancellation support: Cancellation is generated automatically through the running coroutine
hierarchy.
● Fewer memory leaks: It uses structured concurrency to run operations within a scope.
● Jetpack integration: Many Jetpack libraries include extensions that provide full coroutines support.
Some libraries also provide their own coroutine scope that one can use for structured concurrency.

Kotlin Coroutines vs Threads


● Fetching the data from one thread and passing it to another thread takes a lot of time. It also introduces
lots of callbacks, leading to less readability of code. On the other hand, coroutines eliminate callbacks.
● Creating and stopping a thread is an expensive job, as it involves creating their own stacks.,whereas
creating coroutines is very cheap when compared to the performance it offers. coroutines do not have
their own stack.
● Threads are blocking, whereas coroutines are suspendable. By blocking it means that when a thread
sleeps for some duration, the entire threads get blocked, it cannot do any other operation, whereas since
coroutines are suspendable, so when they are delayed for some seconds, they can perform any other
work.
● Coroutines offer a very high level of concurrency as compared to threads, as multiple threads involve
blocking and context switching. Context switching with threads is slower as compared to coroutines, as
with threads context can only be switched when the job of 1 thread gets over, but with coroutines, they
can change context any time, as they are suspendable.
● Coroutines are light and super fast. Coroutines are faster than threads, as threads are managed by
Operating System, whereas coroutines are managed by users. Having thousands of coroutines working
together are much better than having tens of threads working together.

What's the best way to manage the coroutines lifecycle inside Android
ViewModel?
● This below library has added a viewModelScope as an extension function of the ViewModel class.
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:x.x.x"

The created coroutine scope will be bound to Main Dispatchers and will automatically be canceled
when the ViewModel is cleared.

● viewModelScope.launch will start a coroutine in the viewModelScope. This means when the job that
we passed to viewModelScope gets canceled, all coroutines in this job/scope will be canceled.
If the user left the Activity before delay returned, this coroutine will automatically be canceled when
onCleared is called upon the destruction of the ViewModel.
What is the difference between CoroutineScope & ViewModelScope?
CoroutineScope:
CoroutineScope is the API available in Kotlin Coroutine to create a coroutine and all coroutines run inside a
CoroutineScope. A scope controls the lifetime of coroutines through its job. When you cancel the job of scope,
it cancels all coroutines started in that scope.
ViewModelScope:
It’s available in the below library implementation and it si specific t to Android

Does a coroutine started at UI-thread, blocks UI-thread while suspended?


No, A coroutine started on Dispatchers.Main won't block the main thread while suspended.

How coroutines provide Main-safety?


Previously, It was a headache to make sure the threads-safety while calling a network request or database
operations. Then after operation completion, we should make sure either we are on Main-thread to update our
UI.

● Coroutines can easily switch threads at any time and pass results back to the original thread, it's a good
idea to start UI-related coroutines on the Main thread.
● A coroutine started on Dispatchers.Main won’t block the main thread while suspended.
● Libraries like Room and Retrofit offer main-safety out of the box when using coroutines, so you don’t
need to manage threads to make network or database calls. This can often lead to a substantially
simpler code.

Does Kotlin have a Ternary Operator? If No, what is equivalent to the


ternary operator in Kotlin?
No, Kotlin doesn't have a ternary operator like Java. We can utilize if-else structure to use as expression, and it
can produce results the same as the ternary operator.

What are the Dangling pointers?


The dangling pointers are the pointers in the programming language that do not point to the valid object.
A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. These are
special cases of memory safety violations.
For example A pointer to a null object or a non-static variable after function execution.

Architecture Components

● What are Android Architecture components: Android architecture components are a


collection of libraries that help you design robust, testable, and maintainable apps.
● What are ViewModel and How do they work on Android? : A class is designed
to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to
survive configuration changes such as screen rotations.
● What is LiveData?: It is an observable data holder class. Unlike a regular observable, LiveData
is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities,
fragments, or services.
● What is Data Binding: It helps in declaratively binding UI elements to in our layout to data
sources of our app
● Explain WorkManger: It manages every background jobs in Android with the circumstances
we choose
● Explain Room Persistence Library: It is an SQLite object mapping library. Use it to
Avoid boilerplate code and easily convert SQLite table data to Java objects

What is Dependency Injection and Why to do that? : Reduced


Dependencies:
● Classes often require references to other classes. For example, a Car class might need a reference to an
Engine class. These required classes are called dependencies, and in this example the Car class is
dependent on having an instance of the Engine class to run.

● Advantages: Reduced Dependency Carrying, More Reusable Code, More Testable Code, More
Readable Code

● Component Vs Subcomponent: Component dependencies — Use this when you want to keep two
components independent. Subcomponents — Use this when you want to keep two components coupled.

What is Dagger 2?
Dagger library was created by developers at Square, way back in 2012. Dagger 1 was used to create instances of
classes and inject dependencies via Reflections. Improving upon the first version, and collaborating with a team
of developers at Google, Dagger 2 a much faster and improved version without Reflections was introduced.

Dagger 2 is a compile-time android dependency injection framework and uses the Java Specification Request
(JSR) 330 and uses an annotation processor.
Following are the basic annotations used in Dagger 2:

1. @Module : This is used on the class that does the work of constructing objects that’ll be eventually
provided as dependencies.
2. @Provides : This is used on the methods inside the Module class that’ll return the object.
3. @Inject : This is used upon a constructor, field or a method and indicates that dependency has been
requested.
4. @Component : The Module class doesn’t provide the dependency directly to the class that’s
requesting it. For this, a Component interface is used that acts as a bridge between @Module and
@Inject.
5. @Singleton : This indicates that only a single instance of the dependency object would be created.

What is RxJava?
RxJava is a JVM library for doing asynchronous and executing event-based programs by using observable
sequences. It's main building blocks are triple O's, Operator, Observer, and Observables. And using them we
perform asynchronous tasks in our project. It makes multithreading very easy in our project. It helps us to decide
on which thread we want to run the task.

What is RxAndroid?
RxAndroid is an extension of RxJava for Android which is used only in Android application.
RxAndroid introduced the Main Thread required for Android.
To work with the multithreading in Android, we will need the Looper and Handler for Main Thread execution.
RxAndroid provides AndroidSchedulers.mainThread() which returns a scheduler and that helps in
performing the task on the main UI thread that is mainly used in the Android project. So, here
AndroidSchedulers.mainThread() is used to provide us access to the main thread of the application to perform
actions like updating the UI.
In Android, updating UI from background thread is technically not possible, so using
AndroidSchedulers.mainThread() we can update anything on the main thread. Internally it utilizes the concept
of Handler and Looper to perform the action on the main thread.
RxAndroid uses RxJava internally and compiles it. But while using RxAndroid in our project we still add the
dependency of RxJava to work with like,
implementation 'io.reactivex.rxjava3:rxjava:3.0.0'
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
Note: The reason being is there might be a chance that RxAndroid doesn't have the latest version of RxJava
used in the project. So, using RxJava dependency we override the versioning of the internal RxJava version used
in RxAndroid.

Use-Cases in Android Rx Android


RxJava has the power of operators and as the saying goes by, "RxJava has an operator for almost everything".
Case 1:
Consider an example, where we want to do an API call and save it to some storage/file. It would be a
long-running task and doing a long-running task on the main thread might lead to unexpected behavior like App
Not Responding.
So, to do the above-mentioned task we might think to use AsyncTask as our goto solution. But with Android R,
AsyncTask is going to be deprecated, and then libraries like RxJava will be the solution for it.
Using RxJava over AsyncTask helps us to write less code. It provides better management of the code as using
AsyncTask might make the code lengthy and hard to manage.
Case 2:
Consider a use-case where we might want to fetch user details from an API and from the user's ID which we got
from the previous API we will call another API and fetch the user's friend list.
Doing it using AsyncTask we might have to do use multiple Asynctask and manage the results in was way
where we want to combine all the AsyncTask to return the result as a single response.
But using RxJava we can use the power of zip operator to combine the result of multiple different API calls and
return a single response.
Case 3:
Consider an example of doing an API call and getting a list of users and from that, we want only the data which
matches the given current condition.
A general approach is to do the API call, and from the Collection, we can then filter the content of that specific
user based on the condition and then return the data.
But using RxJava we can directly filter out the data while returning the API response by using the filter operator
and we do all of this by doing the thread management.
These are a few use cases to understand RxJava for Android and why we need RxAndroid in our project.
RxJava Basics
The building blocks of RxJava are:

● Observable: class that emits a stream of data or events. i.e. a class that can be used to perform some
action, and publish the result.
● Observer: class that receivers the events or data and acts upon it. i.e. a class that waits and watches the
Observable, and reacts whenever the Observable publishes results.

The Observer has 4 interface methods to know the different states of the Observable.

● onSubscribe(): This method is invoked when the Observer is subscribed to the Observable.
● onNext(): This method is called when a new item is emitted from the Observable.
● onError(): This method is called when an error occurs and the emission of data is not successfully
completed.
● onComplete(): This method is called when the Observable has successfully completed emitting all
items

What is MVVM architecture?


MVVM architecture is a Model-View-ViewModel architecture that removes the tight coupling between each
component. Most importantly, in this architecture, the children don't have the direct reference to the parent, they
only have the reference by observables.

● Model: It represents the data and the business logic of the Android Application. It consists of the
business logic - local and remote data source, model classes, repository.
● View: It consists of the UI Code(Activity, Fragment), XML. It sends the user action to the ViewModel
but does not get the response back directly. To get the response, it has to subscribe to the observables
which ViewModel exposes to it.
● ViewModel: It is a bridge between the View and Model(business logic). It does not have any clue
which View has to use it as it does not have a direct reference to the View. So basically, the ViewModel
should not be aware of the view who is interacting with. It interacts with the Model and exposes the
observable that can be observed by the View.

This is all about the MVVM, now let's move to the implementation part of it.

You might also like