Android-Cheat-sheet
Cheat Sheet for Android Interviews
Under Apache License 2.0
By anitaa1990
Cheat Sheet for Android Interviews
Under Apache License 2.0
By anitaa1990
Android-Cheat-sheet
Cheat Sheet for Android Interviews
Find missing number from an array
Dynamic Programming
Given coin denominations and the total amount, find out the number of ways to make the change
Queues
Implement a queue using stack
LinkedList
Add the head pointers of two linked lists
Stacks
ReverseAStack
Back Tracking
find all the subsets of the given array that sum up to the number K
Graphs
Form circular chain by given list of words
Trees
Serialize binary tree to a file and then deserialize back to tree
Strings
Check if two strings are anagrams
Integers
Minimum Number of Platforms Required for a Railway/Bus Station
Miscellaneous
MergeSort
Searching
Ternary Search
Runtime Complexity Table:
The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.
What is Context?
A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in.
Application Context: This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of an activity.
Activity Context: This context is available in an activity. This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.
What is ABI Management?
Different Android handsets use different CPUs, which in turn support different instruction sets. Each combination of CPU and instruction sets has its own Application Binary Interface, or ABI. The ABI defines, with great precision, how an application's machine code is supposed to interact with the system at runtime. You must specify an ABI for each CPU architecture you want your app to work with. You can checkout the full specifcations here
Why bytecode cannot be run in Android?
Android uses DVM (Dalvik Virtual Machine ) rather using JVM(Java Virtual Machine).
What is a BuildType in Gradle? And what can you use it for?
Gradle creates a build variant for every possible combination of your project’s product flavors and build types.
Explain the build process in Android:
The final step involves the android apkbuilder which takes all the input and builds the apk (android packaging key) file.
What is the Android Application Architecture?
What is Manifest file and R.java file in Android?
Describe activities
Activities are basically containers or windows to the user interface.
Lifecycle of an Activity
OnCreate()
: This is when the view is first created. This is normally where we create views, get data from bundles etc.OnStart()
: Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.OnResume()
: Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.OnPause()
: Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed.OnStop()
: Called when you are no longer visible to the user.OnDestroy()
: Called when the activity is finishingOnRestart()
: Called after your activity has been stopped, prior to it being started again
What’s the difference between onCreate() and onStart()?
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.
Why would you do the setContentView() in onCreate() of Activity class?
As onCreate() of an Activity is called only once, this is the point where most initialization should go. It is inefficient to set the content in onResume() or onStart() (which are called multiple times) as the setContentView() is a heavy operation.
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. But because the onCreate()
method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.onSaveInstanceState()
- is a method used to store data before pausing the activity.
Launch modes in Android?
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.
How does the activity respond when the user rotates the screen?
How to prevent the data from reloading and resetting when the screen is rotated?
For instance, let’s say we have a search screen and the user has entered a query in the Edittext. This results in a list of items being displayed in the RecyclerView. Now if the screen is rotated, the ideal way to prevent resetting of data would be to store the list of search items in the ViewModel and the query text user has entered in the OnSaveInstanceState method of the activity.
Mention two ways to clear the back stack of Activities when a new Activity is called using intent
The first approach is to use a FLAG_ACTIVITY_CLEAR_TOP flag. The second way is by using FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK in conjunction.
What’s the difference between FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_CLEAR_TOP?
FLAG_ACTIVITY_CLEAR_TOP on the other hand, if set and if an old instance of this Activity exists in the task list then barring that all the other activities are removed and that old activity becomes the root of the task list. Else if there’s no instance of that activity then a new instance of it is made the root of the task list. Using FLAG_ACTIVITY_NEW_TASK in conjunction is a good practice, though not necessary.
Describe content providers
When you want to access data in a ContentProvider, you must instead use the ContentResolver object in your application’s Context to communicate with the provider as a client. The provider object receives data requests from clients, performs the requested action, and returns the results.
Access data using Content Provider:
The ContentResolver.query() method returns a Cursor, so you can retrieve data from each column using Cursor methods.
Describe services
A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface. It can run in the background, even when the user is not interacting with your application. These are the three different types of services:
Difference between Service & Intent Service
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.
Difference 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.
Difference between Service, Intent Service, AsyncTask & Threads
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?
A Handler class is preferred when we need to perform a background task repeatedly after every x seconds/minutes.
What is a Job Scheduling?
Scenarios:
What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?
Note: AsyncTasks by default run on a single thread using a serial executor, meaning it has only 1 thread and each task runs one after the other.
What is the onTrimMemory() method?
onTrimMemory()
: Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process. This will happen for example when it goes in the background and there is not enough memory to keep as many background processes running as desired.Android can reclaim memory for from your app in several ways or kill your app entirely if necessary to free up memory for critical tasks. To help balance the system memory and avoid the system's need to kill your app process, you can implement the ComponentCallbacks2
interface in your Activity classes. The provided onTrimMemory() callback method allows your app to listen for memory related events when your app is in either the foreground or the background, and then release objects in response to app lifecycle or system events that indicate the system needs to reclaim memory. Reference
Android Bound Service
Example Implementation: Link
AIDL vs Messenger Queue
Messenger is needed if you want to bind a remote service (e.g. running in another process).
What is a ThreadPool? And is it more effective than using several separate Threads?
ThreadPool consists of a task queue and a group of worker threads, which allows it to run multiple parallel instances of a task.
Difference between Serializable and Parcelable?
How to disallow serialization? We can declare the variable as transient.
Difference between Activity & Service
Activities are basically containers or windows to the user interface. Services is a component that is used to perform operations on the background. It does not have an UI.
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. I have detailed a sample implementation on this. You can check it out here
What is an intent?
Two types of intents-
What is a Sticky Intent?
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 is an Action?
Description of the intent. For instance, ACTION_CALL - used to perform calls
What are intent Filters?
Specifies the type of intent that the activity/service can respond to.
Describe fragments:
Fragment is a UI entity attached to Activity. Fragments can be reused by attaching in different activities. Activity can have multiple fragments attached to it. Fragment must be attached to an activity and its lifecycle will depend on its host activity.
Describe fragment lifecycle
onAttach()
: The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.onCreate()
: The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.onCreateView()
: The system calls this callback when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI.onActivityCreated()
: The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context objectonStart()
: The onStart() method is called once the fragment gets visible.onResume()
: Fragment becomes active.onPause()
: The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.onStop()
: Fragment going to be stopped by calling onStop()onDestroyView()
: Fragment view will destroy after call this methodonDestroy()
:called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.
What is the difference between fragments & activities. Explain the relationship between the two.
An Activity is an application component that provides a screen, with which users can interact in order to do something whereas a Fragment represents a behavior or a portion of user interface in an Activity (with its own lifecycle and input events, and which can be added or removed at will).
When should you use a fragment rather than an activity?
When you have data that needs to be persisted across Activity restarts (such as retained fragments)
Difference between adding/replacing fragment in backstack?
In terms of fragment’s life cycle events onPause, onResume, onCreateView and other life cycle events will be invoked in case of replace but they wont be invoked in case of add.
Why is it recommended to use only the default constructor to create a Fragment?
The reason why you should be passing parameters through bundle is because when the system restores a fragment (e.g on config change), it will automatically restore your bundle. This way you are guaranteed to restore the state of the fragment correctly to the same state the fragment was initialised with.
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. Use this link for reference
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.
Difference between FragmentPagerAdapter vs FragmentStatePagerAdapter?
detach(Fragment)
on the transaction instead of remove(Fragment)
.FragmentStatePagerAdapter: the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the
savedInstanceState.Also it won't affect the performance even if there are large number of fragments.
What is Toast in Android?
Android Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after sometime.
What are Loaders in Android?
Sample Implementation
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.
What is View Group? How are they different from Views?
android.view.View
class, which is the base class of all UI classes.ViewGroup: ViewGroup is the invisible container. It holds View and ViewGroup. For example, LinearLayout is the ViewGroup that contains Button(View), and other Layouts also. ViewGroup is the base class for Layouts.
What is the difference between a regular .png and a nine-patch image?
It is one of a resizable bitmap resource which is being used as backgrounds or other images on the device. The NinePatch class allows drawing a bitmap in nine sections. The four corners are unscaled; the middle of the image is scaled in both axes, the four edges are scaled into one axis.
Difference between RelativeLayout and LinearLayout?
Relative Layout - Arranges elements relative to parent or other elements.
What is ConstraintLayout?
You can read more about how to implement a simple app with ConstraintLayout here, by yours truly :)
When might you use a FrameLayout?
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 is Adapters?
An adapter responsible for converting each data entry into a View that can then be added to the AdapterView (ListView/RecyclerView).
How to support different screen sizes?
Use the smallest width qualifier. For example, you can create a layout named main_activity that's optimized for handsets and tablets by creating different versions of the file in directories as follows:
Outline the process of creating custom Views:
Sample Implementation
Briefly describe some ways that you can optimize View usage
Measuring how long it takes each View to complete the measure, layout, and draw phases. You can also use Hierarchy Viewer to identify any parts of the rendering pipeline that you need to optimize.
Bitmap pooling in android?
Bitmap pooling is a simple technique, that aims to reuse bitmaps instead of creating new ones every time. When you need a bitmap, you check a bitmap stack to see if there are any bitmaps available. If there are not bitmaps available you create a new bitmap otherwise you pop a bitmap from the stack and reuse it. Then when you are done with the bitmap, you can put it on a stack. Find more info here
How to load bitmap to memory?
Find more info here
What are the permission protection levels in Android?
SignatureOrSystem - A permission that the system grants only to applications that are in the Android system image or that are signed with the same certificate as the application that declared the permission.
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 off the main thread as possible.
What is a singleton class in Android?
A singleton class is a class which can create only an object that can be shared all other classes.
```
private static volatile RESTService instance;
protected RESTService(Context context) {
super(context);
}
public static RESTService getInstance(Context context) {
if (instance == null) {
synchronized (RESTService.class) {
if (instance == null) instance = new RESTService(context);
}
}
return instance;
}
```
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?
onBindViewHolder()
method inside RecyclerView.But what happens when you start scrolling and need to start showing next views?
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?
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.Item Animator: ListViews are lacking in support of good animations, but the RecyclerView brings a whole new dimension to it.
How would you implement swipe animation in Android
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="-100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700"/>
</set>
Arraymap/SparseArray vs HashMap in Android?
Article 2 on the subject
How to reduce apk size?
Article on the subject
How to reduce build time of an Android app?
org.gradle.configureondemand=true
- This command will tell gradle to only build the projects that it really needs to build.org.gradle.daemon=true
- Daemon keeps the instance of the gradle up and running in the background even after your build finishes. This will remove the time required to initialize the gradle and decrease your build timing significantly.org.gradle.parallel=true
- Allow gradle to build your project in parallel. If you have multiple modules in you project, then by enabling this, gradle can run build operations for independent modules parallelly.org.gradle.jvmargs=-Xmx3072m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
- Since android studio 2.0, gradle uses dex in the process to decrease the build timings for the project. Generally, while building the applications, multiple dx processes runs on different VM instances. But starting from the Android Studio 2.0, all these dx processes runs in the single VM and that VM is also shared with the gradle. This decreases the build time significantly as all the dex process runs on the same VM instances. But this requires larger memory to accommodate all the dex processes and gradle. That means you need to increase the heap size required by the gradle daemon. By default, the heap size for the daemon is about 1GB. Ensure that dynamic dependency is not used. i.e. do not use
implementation 'com.android.support:appcompat-v7:27.0.+'
.
This command means gradle will go online and check for the latest version every time it builds the app.
Instead use fixed versions i.e. 'com.android.support:appcompat-v7:27.0.2'
Android Architecture Components?
A collection of libraries that help you design robust, testable, and maintainable apps. Official documentation
Room - Official documentation
Article on how to implement Room Db
Sample implementation
Live Data - Official documentation
Sample implementation
ViewModel - Official documentation
Sample implementation
Data Binding - Official documentation
Sample implementation
Lifecycles - Official documentation
Difference between MVC & MVP & MVVM?
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. Sample Implementation
RXJava - What is it?
RxJava - Basics, Types of Operators, Types of Observables - Sample Implementation
S.O.L.I.D Principles in Android development
The execution of the code does not depend upon the OS
Difference between ‘throw’ and ‘throws’ in Java Exception Handling?
throw
keyword is used to throw Exception from any method or static block whereas throws
is used to indicate that which Exception can possibly be thrown by this method.
Is there ever a scenario where we can skip the finally block in a try catch?
By Calling System.exit(0) in try or catch block, we can skip the finally block. System.exit(int) method can throw a SecurityException. If System.exit(0) exits the JVM without throwing that exception then finally block will not execute. But, if System.exit(0) does throw security exception then finally block will be executed.
What are anonymous classes?
Rules:
Why is the main method static in java?
Example:
public class Hello {
static {
System.out.println("Hello, World!");
}
}
What is garbage collector? How does it work?
All objects are allocated on the heap area managed by the JVM. As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.
Difference between stack memory & heap memory?
In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap. Stack is thread specific and Heap is application specific. The stack is important to consider in exception handling and thread executions.
Explain OOPs concept
Object Oriented Programming is a programming style that involves concepts such as Classes, objects,Abstraction, Encapsulation, Inheritance, Polymorphism.
What is Inheritance?
Inheritance is the process by which objects of one class acquire the properties & objects of another class. The two most common reasons to use inheritance are: a) To promote code reuse. b) To use polymorphism.
Does Java support multiple inheritance?
Java supports multiple inheritance by interface only since it can implement multiple interfaces but can extend only one class.
What is Encapsulation?
For instance, a class can be an encapsulated class if all the variables in it are defined as Private and by providing getter and setter methods.
What is Abstract class?
Non-abstract methods can access a method that you declare as abstract.
What are Interfaces?
Marker Interfaces: Marker interfaces are those which do not declare any required Methods. The java.io.Serializable interface is a typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.
Difference between Abstract and Interfaces?
Abstract classes can have non abstract methods. It can have instance variables. We have provide default implementation to abstract class method. A class can extend only one abstract class.A class can implement multiple interfaces.
What is Polymorphism?
2 forms of polymorphism:
What is Method overloading?
Note:
What is Method overriding?
Note: Static methods cannot be overridden. Overloaded methods can still be overridden.
Why would you not call abstract method in constructor?
The problem is that the class is not yet fully initialized, and when the method is called in a subclass, it may cause trouble.
Composition over inheritance?
public Person(String title, String name, String age) {
this.Title = title;
this.Name = name;
this.Age = age;
}
}
class Employee {
Int Salary;
private Person person;
public Employee(Person p, Int salary) {
this.person = p;
this.Salary = salary;
}
}
```
Abstraction solves the problem in the design side while Encapsulation is the Implementation.
Constructors vs Methods?
this()
: Constructors use this to refer to another constructor in the same class with a different parameter list.super()
: Constructors use super to invoke the superclass's constructor.Methods: Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Class methods are methods which are declared as static. The method can be called without creating an instance of the class
What is the difference between instantiation and initialization of an object?
Instantiation is the process of explicitly assigning definitive value to a declared variable.
Do objects get passed by reference or value in Java? Elaborate on that.
Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.
Primitives in Java?
Difference between == and .equals() method in Java?
We can use == operators for reference comparison (address comparison) and .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.
Why strings are Immutable?
Once a value is assigned to a string it cannot be changed. And if changed, it creates a new object of the String. This is not the case with StringBuffer.
What is String.intern()? When and why should it be used?
When the intern method is invoked, if the String pool already contains that String object such that equals() return true, it will return the String object from the pool, otherwise it will add that object to the pool of unique String.
String pool in Java:
String str = new String("Cat");
In above statement, either 1 or 2 string will be created. If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool. If there is no string literal “Cat” in the pool, then it will be first created in the pool and then in the heap space, so total 2 string objects will be created.
Final modifier?
Final modifiers - once declared cannot be modified. A blank final variable in Java is a final variable that is not initialized during declaration.
Finalize keyword?
Finalize is a method used to perform clean up processing just before object is garbage collected.
Finally keyword?
finally is a code block and is used to place important code, it will be executed whether exception is handled or not.
Static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
What is reflection?
Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
Multi threading?
Multiple tasks are running concurrently in a program.
Fail-fast & Fail-Safe?
On the other hand fail-safe Iterators works on copy of collection instead of original collection.
What does the keyword synchronized mean?
synchronized blocks the next thread's call to method as long as the previous thread's execution is not finished. Threads can access this method one at a time.
What does the keyword volatile mean?
An access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock.
What is Autoboxing and Unboxing?
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Optionals in Java?
Optional is a container object which is used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values.
What is externalization?
Implement the java.io.Externalizable interface - then you implement your own code to write object’s states in the writeExternal()
method and read object’s states in the readExternal()
method.
What are Data Structures?
Intentional arrangement of a collection of data. There are 5 fundamental behaviours of a data structure: access, insert, delete, find & sort.
Explain Big O Notation?
Note: O(1) means that it takes a constant time, like three minutes no matter the amount of data in the set.
O(n) means it takes an amount of time linear with the size of the set.
Explain Big Omega Notation
The Big Omega Notation is used to describe the best case running time for a given algorithm.
Arrays in Java?
Arrays: Complexity:
| Algorithm | Average | Worst Case |
| ---------- |:--------:| -----------:|
| Space | Θ(n) | O(n) |
| Search | Θ(n) | O(n) |
| Insert | Θ(n) | O(n) |
| Delete | Θ(n) | O(n) |
Linked Lists in Java?
Linked List: Runtime Complexity:
| Algorithm | Average | Worst Case |
| ---------- |:--------:| -----------:|
| Space | Θ(n) | O(n) |
| Search | Θ(n) | O(n) |
| Insert | Θ(1) | O(1) |
| Delete | Θ(1) | O(1) |
Binary Tree
Their disadvantage is that in the worst case they can degenerate into a linked list in terms of efficiency.
Stacks:
Efficiency of stacks: The time is not dependent of the no of items in the stack so it is very efficient. O(1)
.
Queues:
Priority queue: same as queue but has a priority associated with it. Items are retrieved based on their priority
Blocking Queues:
Example on implementing a blocking queue
Difference between stacks & queues?
Example on how to prevent deadlock
What is the List interface & Set interface?
List interface supports for ordered collection of objects and it may contain duplicates. The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements
Difference between ArrayList & Vectors?
Insertion and deletion in ArrayList is slow compared to LinkedList?
Implementations of Map?
LinkedHashMap: This is a subclass of Hashmap. The order of insertion is preserved since it has a linkedList.
Difference between Enumeration and Iterators?
ListIterator: is just like an iterator except it allows access to the collection in either the forward or backward direction
How Hashmap works in Java?
hashcode()
method of the key object is called so that hash function of the map can find a bucket location to store Entry object.If two different objects have the same hashcode: in this case, a linked list is formed at that bucket location and a new entry is stored as next node. After finding bucket location, we will call keys.equals()
method to identify a correct node in LinkedList and return associated value object for that key in Java HashMap
Generics in Java
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); //typecasting
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
I will be adding more questions soon! If you would like to contribute to the Android Cheat Sheet, just make a pull request!