From 4531256a09b8697f712c1f37d9d511a9998a947e Mon Sep 17 00:00:00 2001 From: niharika8059 Date: Sun, 14 Jun 2020 00:01:01 +0530 Subject: [PATCH 1/4] Added more questions for DS,Java,Android and System Design --- README.md | 875 +++++++++--------- src/arrays/FindMaximumSumPathInTwoArrays.java | 95 ++ src/arrays/MergeTwoSortedArrays.java | 63 ++ src/arrays/Segregate0And1s.java | 57 ++ src/linkedlist/ReverseDoublyLinkedList.java | 107 +++ src/sort/HeapSort.java | 84 ++ 6 files changed, 863 insertions(+), 418 deletions(-) create mode 100644 src/arrays/FindMaximumSumPathInTwoArrays.java create mode 100644 src/arrays/MergeTwoSortedArrays.java create mode 100644 src/arrays/Segregate0And1s.java create mode 100644 src/linkedlist/ReverseDoublyLinkedList.java create mode 100644 src/sort/HeapSort.java diff --git a/README.md b/README.md index 7477374..08bbff0 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ Cheat Sheet for Android Interviews * [Data Structure Coding Programs](#data-structure-coding-programs) * [Android Interview Questions](#android-interview-questions) * [Java Interview Questions](#java-interview-questions) +* [System Design Interview Questions](#system-design-interview-questions)
@@ -22,7 +23,10 @@ Cheat Sheet for Android Interviews * [Find the maximum difference between the values in an array such that the largest values always comes after the smallest value](/src/arrays/FindMaxDifference.java) * [Find second largest element in an array](/src/arrays/FindSecondLargestElement.java) * [Find the 3 numbers in an array that produce the max product](/src/arrays/FindMaxProduct.java) - * [Find missing number from an array](/src/arrays/FindMissingNumber.java) + * [Find missing number from an array](/src/arrays/FindMissingNumber.java) + * [Find Maximum Sum path Across 2 Arrays](/src/arrays/FindMaximumSumPathInTwoArrays.java) + * [Merge two sorted arrays with O(1) extra space](/src/arrays/MergeTwoSortedArrays.java) + * [Segregate 0s and 1s in an array](/src/arrays/Segregate0And1s.java)
@@ -33,22 +37,22 @@ Cheat Sheet for Android Interviews * [Find the maximum sum of a subsequence such that no consecutive elements are part of the subsequence](/src/dynamicprogramming/MaxSumSubsequenceOfNonadjacentElements.java) * [Given a score "n", find the total number of ways score "n" can be reached](/src/dynamicprogramming/GameScoring.java) * [Compute Levenshtein distance between two strings](/src/dynamicprogramming/LevenshteinDistance.java) - * [Given coin denominations and the total amount, find out the number​ of ways to make the change](/src/dynamicprogramming/CoinChangingProblem.java) + * [Given coin denominations and the total amount, find out the number​ of ways to make the change](/src/dynamicprogramming/CoinChangingProblem.java)
- - - + + + * Queues
* [Find the Maximum in a Sliding Window](/src/queue/Dequeue.java) * [Implement a queue using stack](/src/queue/QueuesUsingStack.java)
- + * LinkedList
* [Reverse a Linked List](/src/linkedlist/ReverseLinkedList.java) * [Remove duplicates from a Linked List](/src/linkedlist/RemoveDuplicates.java) - * [Delete Node of a given key from a Linked List](/src/linkedlist/DeleteNodeWithKey.java) + * [Delete Node of a given key from a Linked List](/src/linkedlist/DeleteNodeWithKey.java) * [Find the Middle Node of a Linked List](/src/linkedlist/FindMiddleNode.java) * [Find the Nth Node of a Linked List](/src/linkedlist/FindNthNode.java) * [Check if a Linked List is cyclic](/src/linkedlist/CheckIfContainsCycle.java) @@ -61,11 +65,12 @@ Cheat Sheet for Android Interviews * [Reverse nodes at even indices](/src/linkedlist/ReverseEvenNodes.java) * [Rotate linked list by n](/src/linkedlist/RotateLinkedList.java) * [Reverse every 'k' elements in a linked list](/src/linkedlist/ReversekElements.java) - * [Add the head pointers of two linked lists](/src/linkedlist/AddTwoIntegers.java) -
- - - + * [Add the head pointers of two linked lists](/src/linkedlist/AddTwoIntegers.java) + * [Reverse a Doubly Linked List](/src/linkedlist/ReverseDoublyLinkedList.java) +
+ + + * Stacks
* [Evaluate an expression](/src/stacks/EvaluationExpression.java) * [Implement a stack using queues](/src/stacks/StacksUsingQueues.java) @@ -73,8 +78,8 @@ Cheat Sheet for Android Interviews * [Tower of Hanoi](/src/stacks/TowerOfHanoi.java) * [ReverseAStack](/src/stacks/ReverseStack.java)
- - + + * Back Tracking
* [Solve Boggle](/src/backtracks/Boggle.java) @@ -82,15 +87,15 @@ Cheat Sheet for Android Interviews * [Solve N queen problem](/src/backtracks/NQueenProblem.java) * [find all the subsets of the given array that sum up to the number K](/src/backtracks/KSumSubsets.java)
- - + + * Graphs
* [Clone a Directed Graph](/src/graphs/CloneDirectedGraph.java) * [Minimum Spanning Tree](/src/graphs/MinimumSpanningTree.java) - * [Form circular chain by given list of words](/src/graphs/WordChaining.java) -
- - + * [Form circular chain by given list of words](/src/graphs/WordChaining.java) +
+ + * Trees
* [Implements an InOrder Iterator on a Binary Tree](/src/trees/BinaryTreeIterator.java) * [Convert a binary tree to a doubly linked list](/src/trees/BinaryTreeToLinkedList.java) @@ -105,7 +110,7 @@ Cheat Sheet for Android Interviews * [Swap the 'left' and 'right' children for each node in a binary tree](/src/trees/MirrorBinaryTreeNodes.java) * [Find nth highest node in a Binary Search Tree](/src/trees/NthHighestBST.java) * [Print nodes forming the boundary of a Binary Search Tree](/src/trees/PrintTreePerimeter.java) - * [Serialize binary tree to a file and then deserialize back to tree](/src/trees/SerializeBinaryTree.java) + * [Serialize binary tree to a file and then deserialize back to tree](/src/trees/SerializeBinaryTree.java)
@@ -118,13 +123,13 @@ Cheat Sheet for Android Interviews * [Remove a String](/src/strings/ReverseString.java) * [String Segmentation](/src/strings/StringSegmentation.java) * [Find next highest permutation of a given string](/src/strings/NextHighestPermutation.java) - * [Check if two strings are anagrams](/src/strings/CheckIfAnagram.java) + * [Check if two strings are anagrams](/src/strings/CheckIfAnagram.java)
- - + + * Integers
* [Reverse Integer](/src/math/ReverseInteger.java) - * [Find sum of digits of an integer](/src/math/FindSumOfInteger.java) + * [Find sum of digits of an integer](/src/math/FindSumOfInteger.java) * [Find Next highest Number from a Integer](/src/math/NextHighestNumber.java) * [Check if it is an Armstrong number](/src/math/CheckIfArmstrongNumber.java) * [Find the factorial of a number](/src/math/FindFactorial.java) @@ -135,27 +140,28 @@ Cheat Sheet for Android Interviews * [Integer Division](/src/math/IntegerDivision.java) * [Find Pythagorean Triplets](/src/math/FindPythagoreanTriplets.java) * [Print all possible sum combinations using positive integers](/src/math/SumCombinations.java) - * [Find Missing Number](/src/math/FindMissingNumber.java) + * [Find Missing Number](/src/math/FindMissingNumber.java) * [Find all subsets of a given set of integers](/src/math/IntegerSubsets.java) * [Given an input string, determine if it makes a valid number](/src/math/NumberValidity.java) * [Calculate 'x' raised to the power 'n'](/src/math/PowerOfNumber.java) * [Calculate square root of a number](/src/math/CalculateRoot.java) - * [Minimum Number of Platforms Required for a Railway/Bus Station](/src/math/MinimumPlatforms.java) -
- - + * [Minimum Number of Platforms Required for a Railway/Bus Station](/src/math/MinimumPlatforms.java) +
+ + * Miscellaneous
* [Find three integers in the array with sum equal to the given value](/src/misc/SumOfThreeValues.java) * [Find position of a given key in 2D matrix](/src/misc/SearchMatrix.java) * [Determine the host byte order of any system](/src/misc/HostByteOrder.java) * [Find the point that requires the least total distance covered by all the ​people to meet at that point](/src/misc/ClosestMeetingPoint.java) * [Given a two dimensional array, if any element in it is zero make its whole row and column zero](/src/misc/SumOfThreeValues.java) -
- - +
+ + ### Data Structure Coding Programs * Sorting
* [BubbleSort](/src/sort/BubbleSort.java) + * [HeapSort](/src/sort/HeapSort.java) * [InsertionSort](/src/sort/InsertionSort.java) * [SelectionSort](/src/sort/SelectionSort.java) * [QuickSort](/src/sort/QuickSort.java) @@ -163,25 +169,25 @@ Cheat Sheet for Android Interviews * Question: Why is quicksort preferred over merge sort for sorting arrays?
* Quicksort does not require any extra storage whereas merge sort requires O(n) space allocation. Allocating/de-allocating memory space can increase the run time.
* Question: Why is merge sort preferred over quicksort for sorting linked lists?
- * There is a difference in linked lists due to memory allocation. In linked lists we can insert items in the middle in O(n) space and time. There is no extra memory allocation required. + * There is a difference in linked lists due to memory allocation. In linked lists we can insert items in the middle in O(n) space and time. There is no extra memory allocation required.
- - + + * Searching
* [Binary Search](/src/search/BinarySearch.java) * [Rotated Binary Search](/src/search/RotatedBinarySearch.java) - * [Ternary Search](/src/search/TernarySearch.java) + * [Ternary Search](/src/search/TernarySearch.java) * Question: Why is binary search preferred over ternary search?
* When dividing an array by k ( 2(binary) or 3(ternary)), it reduces the array size to 1/k. But it increases the no of comparisons by k.
- - + + * Runtime Complexity Table:

- - - -### Android Interview Questions + + + +### Android Interview Questions * What is Application?
* 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.
@@ -190,27 +196,42 @@ Cheat Sheet for Android Interviews 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.
+* Application LifeCycle?
+ +*
How to achieve Interprocess communication in android?
+ +*
Why do we use Headless fragments?
+ +*
Design patterns in Android
+ +*
Map vs FlatMap operator in Rxjava?
+ +*
Role of Handlers,Loopers and MessageQueue in Android?
+ +*
Why do we prefer Framelayout for Fragments?
+ +*
How to make endless circular recyclerView?
* 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](https://developer.android.com/ndk/guides/abis)
- - + + * 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?
* Build types define properties that Gradle uses when building and packaging your Android app. * A build type defines how a module is built, for example whether ProGuard is run. * A product flavor defines what is built, such as which resources are included in the build. - * Gradle creates a build variant for every possible combination of your project’s product flavors and build types.
- + * Gradle creates a build variant for every possible combination of your project’s product flavors and build types.
+ * Explain the build process in Android:
* First step involves compiling the resources folder (/res) using the aapt (android asset packaging tool) tool. These are compiled to a single class file called R.java. This is a class that just contains constants. - * Second step involves the java source code being compiled to .class files by javac, and then the class files are converted to Dalvik bytecode by the "dx" tool, which is included in the sdk 'tools'. The output is classes.dex. + * Second step involves the java source code being compiled to .class files by javac, and then the class files are converted to Dalvik bytecode by the "dx" tool, which is included in the sdk 'tools'. The output is classes.dex. * The final step involves the android apkbuilder which takes all the input and builds the apk (android packaging key) file.
@@ -223,15 +244,15 @@ Cheat Sheet for Android Interviews d. Resource Externalization − strings and graphics
e. Notification − light,sound,icon,notification,dialog box,and toast
f. Content Providers − It will share the data between applications
- + * What is Manifest file and R.java file in Android?
* Manifest: Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code. It contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc. * R.Java: It is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory.
- + * 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.
@@ -240,118 +261,118 @@ Cheat Sheet for Android Interviews * ```OnStop()```: Called when you are no longer visible to the user.
* ```OnDestroy()```: Called when the activity is finishing
* ```OnRestart()```: Called after your activity has been stopped, prior to it being started again
- - + + * 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.
- - + + * 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?
- * 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 different tasks. + * 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 different tasks. * Example: 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. - * Example: 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. + * 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. + * Example: 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. - * Example: 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. + * 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. + * Example: 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 “singleTask”, the new activity stack will be: + * 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 “singleTask”, the new activity stack will be: * Task1 — A -> B -> C and 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.
- - + + * How to prevent the data from reloading and resetting when the screen is rotated?
* The most common approach these days would be to use a combination of ViewModels and onSaveInstanceState(). So how we do we that? * Basics of [ViewModel](https://developer.android.com/reference/android/arch/lifecycle/ViewModel): A ViewModel is LifeCycle-Aware. In other words, a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new instance of the owner will just re-connected to the existing ViewModel. So if you rotate an Activity three times, you have just created three different Activity instances, but you only have one ViewModel. * So the common practice is to store data in the ViewModel class (since it persists data during configuration changes) and use OnSaveInstanceState to store small amounts of UI data. * 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_TASK is used to clear all the activities from the task including any existing instances of the class invoked. The Activity launched by intent becomes the new root of the otherwise empty task list. This flag has to be used in conjunction with FLAG_ ACTIVITY_NEW_TASK.
- * 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.
- - + * 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
- * A ContentProvider provides data from one application to another, when requested. It manages access to a structured set of data. It provides mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process.
+ * A ContentProvider provides data from one application to another, when requested. It manages access to a structured set of data. It provides mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process.
* 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:
* Start by making sure your Android application has the necessary read access permissions. Then, get access to the ContentResolver object by calling getContentResolver() on the Context object, and retrieving the data by constructing a query using ContentResolver.query().
- * The ContentResolver.query() method returns a Cursor, so you can retrieve data from each column using Cursor methods.
- - + * 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: * 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](https://developer.android.com/guide/topics/ui/notifiers/notifications.html) 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 [WorkManager](https://developer.android.com/topic/libraries/architecture/workmanager) 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.
- - + + * Difference 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.
+ * 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.
- - - + + + * Difference between AsyncTasks & Threads?
* 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. * 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
* 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.
- - + + * What is a Job Scheduling?
* Job Scheduling api, as the name suggests, allows to schedule jobs while letting the system optimize based on memory, power, and connectivity conditions. - * The JobScheduler supports batch scheduling of jobs. The Android system can combine jobs so that battery consumption is reduced. JobManager makes handling uploads easier as it handles automatically the unreliability of the network. It also survives application restarts. + * The JobScheduler supports batch scheduling of jobs. The Android system can combine jobs so that battery consumption is reduced. JobManager makes handling uploads easier as it handles automatically the unreliability of the network. It also survives application restarts. * Scenarios: * Tasks that should be done once the device is connect to a power supply * Tasks that require network access or a Wi-Fi connection. * Task that are not critical or user facing * Tasks that should be running on a regular basis as batch where the timing is not critical * [Reference](http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html#schedulingtasks)
- - + + * 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?
* An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes. @@ -364,8 +385,8 @@ Cheat Sheet for Android Interviews * 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](https://developer.android.com/topic/performance/memory)
- - + + * 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.
@@ -375,7 +396,7 @@ A bound service is a service that can be used not only by components running in * A service handler: this component handles incoming requests from clients that interact with the service itself.
* A Messenger: this class is used to create an object implementing IBinder interface so that a client can interact with the service.
* Example Implementation: [Link](https://www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger-2.html) - + * AIDL vs Messenger Queue
* AIDL is for purpose when you've to go application level communication for data and control sharing, a scenario depicting it can be : An app requires list of all contacts from Contacts app (content part lies here) plus it also wants to show the call's duration and you can also disconnect it from that app (control part lies here). @@ -391,52 +412,52 @@ A bound service is a service that can be used not only by components running in * Difference between Serializable and Parcelable?
* Serializable is a standard Java interface. Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient than Serializable (The problem with this approach is that reflection is used and it is a slow process. This mechanism also tends to create a lot of temporary objects and cause quite a bit of garbage collection.). - * Serialization Serialization is the process of converting an object into a stream of bytes in order to store an object into memory, so that it can be recreated at a later time, while still keeping the object's original state and data. + * Serialization Serialization is the process of converting an object into a stream of bytes in order to store an object into memory, so that it can be recreated at a later time, while still keeping the object's original state and data. * 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 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](https://medium.com/@anitaa_1990/how-to-update-an-activity-from-background-service-or-a-broadcastreceiver-6dabdb5cef74)
* What is an intent?
* Intents are messages that can be used to pass information to the various components of android. For instance, launch an activity, open a webview etc.
- * Two types of intents-
+ * Two types of intents-
* Implicit: Implicit intent is when you call system default intent like send email, send SMS, dial number.
* Explicit: Explicit intent is when you call an application activity from another activity of the same application.
* What is a Sticky Intent?
- * Sticky Intents allows communication between a function and a service. + * 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 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. @@ -447,107 +468,107 @@ We can also register a Handler and pass data using Handlers. I have detailed a s * ```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 method - * ```onDestroy()``` :called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.
- - + * ```onDestroy()``` :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 there are ui components that are going to be used across multiple activities. + * When there are ui components that are going to be used across multiple activities. * When there are multiple views that can be displayed side by side (viewPager tabs) * When you have data that needs to be persisted across Activity restarts (such as retained fragments)
- - + + * 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). * 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](https://why-android.com/2016/03/29/learn-how-to-use-the-onbackstackchangedlistener/) 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?
* FragmentPagerAdapter: the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls ```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.
- - - + * 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?
* 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. * [Sample Implementation](https://medium.com/mindorks/a-journey-to-the-world-of-mvp-and-loaders-part-2-e176200e5866)
- - + + * 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?
* View: View objects are the basic building blocks of User Interface(UI) elements in Android. View is a simple rectangle box which responds to the user's actions. Examples are EditText, Button, CheckBox etc. View refers to the ```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.
- - + * 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?
- * Linear Layout - Arranges elements either vertically or horizontally. i.e. in a row or column. + * 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 flat 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. - * [Sample Implementation](https://github.com/anitaa1990/ConstraintLayout-Sample) + * [Sample Implementation](https://github.com/anitaa1990/ConstraintLayout-Sample) * You can read more about how to implement a simple app with ConstraintLayout [here](https://android.jlelse.eu/learning-to-implement-constraintlayout-in-android-8ddc69fe0a1a), by yours truly :)
- - + + * 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.
- - + * 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?
* Create a flexible layout - The best way to create a responsive layout for different screen sizes is to use ConstraintLayout as the base layout in your UI. ConstraintLayout allows you to specify the position and size for each view according to spatial relationships with other views in the layout. This way, all the views can move and stretch together as the screen size changes. * Create stretchable nine-patch bitmaps * Avoid hard-coded layout sizes - Use wrap_content or match_parent. Create alternative layouts - The app should provide alternative layouts to optimize the UI design for certain screen sizes. For eg: different UI for tablets - * 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: - * res/layout/main_activity.xml # For handsets (smaller than 600dp available width) - * res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger). + * 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: + * res/layout/main_activity.xml # For handsets (smaller than 600dp available width) + * res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger). * The smallest width qualifier specifies the smallest of the screen's two sides, regardless of the device's current orientation, so it's a simple way to specify the overall screen size available for your layout.
- - - + + + * Outline the process of creating custom Views:
* Create a class that Subclass a view * Create a res/values/attrs.xml file and declare the attributes you want to use with your custom View. @@ -555,34 +576,34 @@ savedInstanceState.Also it won't affect the performance even if there are large * Override either onSizeChanged() or onMeasure(). * Draw your View by overriding onDraw(). * [Sample Implementation](https://code.tutsplus.com/tutorials/android-sdk-creating-custom-views--mobile-14548)
- - + + * Briefly describe some ways that you can optimize View usage
* Checking for excessive overdraw: install your app on an Android device, and then enable the "Debug GPU Overview" option. * Flattening your view hierarchy: inspect your view hierarchy using Android Studio’s ‘Hierarchy Viewer’ tool. * 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](https://www.linkedin.com/pulse/performance-improvement-bitmap-pooling-android-ali-muzaffar/)
- - + + * How to load bitmap to memory?
- * [Find more info here](https://android.jlelse.eu/loading-large-bitmaps-efficiently-in-android-66826cd4ad53)
- - + * [Find more info here](https://android.jlelse.eu/loading-large-bitmaps-efficiently-in-android-66826cd4ad53)
+ + * What are the permission protection levels in Android?
* Normal - A lower-risk permission that gives requesting applications access to isolated application-level features, with minimal risk to other applications, the system, or the user. The system automatically grants this type of permission to a requesting application at installation, without asking for the user's explicit approval. * Dangerous - A higher-risk permission. Any dangerous permissions requested by an application may be displayed to the user and require confirmation before proceeding, or some other approach may be taken to avoid the user automatically allowing the use of such facilities. * Signature - A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission. If the certificates match, the system automatically grants the permission without notifying the user or asking for the user's explicit approval. - * 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.
- - - + * 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. ``` @@ -590,7 +611,7 @@ savedInstanceState.Also it won't affect the performance even if there are large protected RESTService(Context context) { super(context); } - + public static RESTService getInstance(Context context) { if (instance == null) { synchronized (RESTService.class) { @@ -601,29 +622,29 @@ savedInstanceState.Also it won't affect the performance even if there are large } ```
- - + + * 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?
* Let's start with some background on RecyclerView which is needed to understand ```onBindViewHolder()``` method inside RecyclerView.
- * RecyclerView is designed to display long lists (or grids) of items. Say you want to display 100 rows of something. 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 fit on screen and the remaining items would be off 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. + * RecyclerView is designed to display long lists (or grids) of items. Say you want to display 100 rows of something. 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 fit on screen and the remaining items would be off 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 off 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. + * 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 field 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.
- - -* How would you implement swipe animation in Android
+ * 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
``` @@ -632,95 +653,102 @@ savedInstanceState.Also it won't affect the performance even if there are large android:duration="700"/> ``` -
- - +
+ + * Arraymap/SparseArray vs HashMap in Android?
* [Article 1 on the subject](https://android.jlelse.eu/app-optimization-with-arraymap-sparsearray-in-android-c0b7de22541a) * [Article 2 on the subject](https://medium.com/@mohom.r/optimising-android-app-performance-with-arraymap-9296f4a1f9eb)
- - + + * How to reduce apk size?
* Enable proguard in your project by adding following lines to your release build type. * Enable shrinkResources. * Strip down all the unused locale resources by adding required resources name in “resConfigs”. * Convert all the images to the webp or vector drawables. * [Article on the subject](https://medium.com/exploring-code/how-you-can-decrease-application-size-by-60-in-only-5-minutes-47eff3e7874e) -
- - +
+ + * How to reduce build time of an Android app?
- * Check out this awesome [article](https://medium.com/exploring-code/how-to-decrease-your-gradle-build-time-by-65-310b572b0c43) on it. + * Check out this awesome [article](https://medium.com/exploring-code/how-to-decrease-your-gradle-build-time-by-65-310b572b0c43) on it. * What I got from the article: A few commands we can add to the gradle.properties file: * ```org.gradle.configureondemand=true``` - This command will tell gradle to only build the projects that it really needs to build. * Use Daemon - ```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. - * Increase Heap Size - ```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 + * Increase Heap Size - ```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'``` -
- - + 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](https://developer.android.com/topic/libraries/architecture/) - * Room - [Official documentation](https://developer.android.com/topic/libraries/architecture/room) - [Article on how to implement Room Db](https://medium.com/@anitaa_1990/5-steps-to-implement-room-persistence-library-in-android-47b10cd47b24) + * Room - [Official documentation](https://developer.android.com/topic/libraries/architecture/room) + [Article on how to implement Room Db](https://medium.com/@anitaa_1990/5-steps-to-implement-room-persistence-library-in-android-47b10cd47b24) [Sample implementation](https://github.com/anitaa1990/RoomDb-Sample) - - * Live Data - [Official documentation](https://developer.android.com/topic/libraries/architecture/livedata) + + * Live Data - [Official documentation](https://developer.android.com/topic/libraries/architecture/livedata) [Sample implementation](https://github.com/anitaa1990/GameOfThronesTrivia) - - * ViewModel - [Official documentation](https://developer.android.com/topic/libraries/architecture/viewmodel) + + * ViewModel - [Official documentation](https://developer.android.com/topic/libraries/architecture/viewmodel) [Sample implementation](https://github.com/anitaa1990/GameOfThronesTrivia) - - * Data Binding - [Official documentation](https://developer.android.com/topic/libraries/data-binding/) - [Sample implementation](https://github.com/anitaa1990/DataBindingExample) - + + * Data Binding - [Official documentation](https://developer.android.com/topic/libraries/data-binding/) + [Sample implementation](https://github.com/anitaa1990/DataBindingExample) + * Lifecycles - [Official documentation](https://developer.android.com/topic/libraries/architecture/lifecycle) -
- - +
+ + * 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). [Sample Implementation](https://github.com/anitaa1990/Inshorts) + * 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). [Sample Implementation](https://github.com/anitaa1990/Inshorts) * 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](https://github.com/anitaa1990/Trailers)

* RXJava - What is it? * [RxJava - Basics, Types of Operators, Types of Observables - Article](https://medium.com/@anitaa_1990/exploring-rxjava-in-android-e52ed7ef32e2) * [RxJava - Basics, Types of Operators, Types of Observables - Sample Implementation](https://github.com/anitaa1990/RxAndroid-Sample) - - + + * S.O.L.I.D Principles in Android development
- * [Answer](https://github.com/anitaa1990/Today-I-Learned/blob/master/android/solid_principle.md)
- + * [Answer](https://github.com/anitaa1990/Today-I-Learned/blob/master/android/solid_principle.md)
+

- - - -### Java Interview Questions + + + +### Java Interview Questions * Why is Java said to be platform independent?
* The execution of the code does not depend upon the OS
- - + +*
Inner vs Static Nested Classes?
+ +*
Why do we have Thread Pools in java?
+ +*
Does Java pass by reference or pass by value?
+ +*
how to implement Custom Exceptions?
+ * 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?
* 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. Since anonymous classes have no name, objects can not be instantiated from outside the class in which the anonymous class is defined. In fact, an anonymous object can only be instantiated from within the same scope in which it is defined. * Rules: * An anonymous class must always extend a super class or implement an interface but it cannot have an explicit extends or implements clause. * An anonymous class must implement all the abstract methods in the super class or the interface. * An anonymous class always uses the default constructor from the super class to create an instance. - * Example: - ``` + * Example: + ``` MyButton.setOnClickListener(new Button.OnClickListener { @override public void onClick(View view){ @@ -728,8 +756,8 @@ savedInstanceState.Also it won't affect the performance even if there are large } });
- - + + * Why is the main method static in java?
* The method is static because otherwise there would be ambiguity on which method to be called. If static is removed from the main method, Program compiles successfully . But at runtime throws an error “NoSuchMethodError”. * We can overload the main method in Java. But the program doesn’t execute the overloaded main method when we run your program, we need to call the overloaded main method from the actual main method only. To run a method without calling this main method, we would need to execute a static block. @@ -737,19 +765,19 @@ savedInstanceState.Also it won't affect the performance even if there are large * Note: Any method declared static will be executed even before the main class is executed. * Example: ``` - public class Hello { - static { - System.out.println("Hello, World!"); - } + 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?
* Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . * Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer. @@ -762,81 +790,81 @@ savedInstanceState.Also it won't affect the performance even if there are large * Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection. * Stack memory is short-lived whereas heap memory lives from the start till the end of application execution. * When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error. - * Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.
- - + * Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.
+ + * 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?
- * Encapsulation involves binding code and data together as a single unit. - * Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. + * Encapsulation involves binding code and data together as a single unit. + * Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. * For instance, a class can be an encapsulated class if all the variables in it are defined as Private and by providing getter and setter methods.
* What is Abstract class?
- * Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. + * Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. * If even a single method is abstract, the whole class must be declared abstract. * Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. * You can’t mark a class as both abstract and final. * Non-abstract methods can access a method that you declare as abstract.
- - + + * What are Interfaces?
- * Interfaces are only declared methods that an implementing class would need. - * Interfaces cannot be marked as final. Interface variables must be static or final. + * Interfaces are only declared methods that an implementing class would need. + * Interfaces cannot be marked as final. Interface variables must be static or final. * Interfaces cannot be instantiated directly. * Marker Interfaces: Marker interfaces are those which do not declare any required Methods. The java.io.Serializable interface is a typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.
- - + + * 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?
- * Polymorphism is when an object takes on multiple forms. For instance, String is a subclass of Object class. + * Polymorphism is when an object takes on multiple forms. For instance, String is a subclass of Object class. * Polymorphism manifests itself in Java in the form of multiple methods having the same name. * In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). * In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods). * Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. - * 2 forms of polymorphism: + * 2 forms of polymorphism: * Compile time polymorphism: The flow of control is decided during the compile time itself. By overloading. * Run time polymorphism: is done using inheritance and interface. The flow of control is decided during the runtime. Overriding: Overriding will have the same method name with the same parameters. One will be the parent class method and the other will be the child class method. Overloading occurs when the same method name is declared but with different parameters.
- - + + * What is Method overloading?
- * Method Overloading means to have two or more methods with same name in the same class with different arguments. + * Method Overloading means to have two or more methods with same name in the same class with different arguments. * Note: * Overloaded methods MUST change the argument list * Overloaded methods CAN change the return type * Overloaded methods CAN change the access modifier * Overloaded methods CAN declare new or broader checked exceptions * A method can be overloaded in the same class or in a subclass
- - + + * What is Method overriding?
* Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass * You can’t override a method marked public and make it protected * You cannot override a method marked final * You cannot override a method marked static * 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?
* Composition is typically "has a" or "uses a" relationship. In the below example, the Employee class has a Person. It does not inherit from Person but instead gets the Person object passed to it, which is why it is a "has a" Person. @@ -865,129 +893,129 @@ class Employee { } ```
- - + + * Difference between Encapsulation & Abstraction?
- * Abstraction focuses on the outside view of an object (i.e. the interface) - * Encapsulation (information hiding) prevents clients from seeing it’s inside view. + * Abstraction focuses on the outside view of an object (i.e. the interface) + * Encapsulation (information hiding) prevents clients from seeing it’s inside view. * Abstraction solves the problem in the design side while Encapsulation is the Implementation.
- - + + * Constructors vs Methods?
* Constructors must have the name as the class name and does not have a return type. It can be used to instantiate any objects in the class whereas methods have no such rule and is another member of the class. Constructors cannot be inherited but a derived class can call the super constructor of parent class. * ```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?
* Initialization 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 definitive value to a declared variable.
- - + + * Do objects get passed by reference or value in Java? Elaborate on that.
- * Java is always pass-by-value. When we pass the value of an object, we are passing the reference to it. + * Java is always pass-by-value. When we pass the value of an object, we are passing the reference to it. * Java creates a copy of the variable being passed in the method and then does the manipulations. Hence the change is not reflected in the main method. * But when you pass an object reference into a method, a copy of this reference is made, so it still points to the same object. This means, that any changes that you make to the insides of this object are retained, when the method exits. * Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.
- - + + * 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?
* String.intern() method can be used to to deal with String duplication problem in Java. By carefully using the intern() method you can save a lot of memories consumed by duplicate String instances. A string is duplicate if it contains the same content as another string but occupied different memory location. * By calling the intern() method on a string object, for instance “abc”, you can instruct JVM to put this String in the pool and whenever someone else creates "abc", this object will be returned instead of creating a new object. This way, you can save a lot of memory in Java, depending upon how many Strings are duplicated in your program. * When the intern method is invoked, if the String pool already contains that String object such that equals() return true, it will return the String object from the pool, otherwise it will add that object to the pool of unique String.
- - - + + + * String pool in Java:
- * String Pool in java is a pool of Strings stored in Java Heap Memory. + * String Pool in java is a pool of Strings stored in Java Heap Memory. * When we use double quotes to create a String, it first looks for String with same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference. * However using new operator, we force String class to create a new String object in heap space. We can use intern() method to put it into the pool or refer to other String object from string pool having same value. * For example, how many strings are getting created in below statement; ``` 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. + * Final modifiers - once declared cannot be modified. A blank final variable in Java is a final variable that is not initialized during declaration. * final Classes- A final class cannot have subclasses. * final Variables- A final variable cannot be changed once it is initialized. * final Methods- A final method cannot be overridden by subclasses.
- - + + * 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?
* Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. - * 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.
- - + * 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.
- - + * 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?
- * Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because they try to immediately throw Exception when they encounter failure. + * Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because they try to immediately throw Exception when they encounter failure. * On the other hand [fail-safe](http://javarevisited.blogspot.com/2011/10/java-iterator-tutorial-example-list.html) Iterators works on copy of collection instead of original collection.
- - + + * What does the keyword synchronized mean?
* When you have two threads that are reading and writing to the same 'resource', say a variable named 'test', you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to test. * 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?
- * Suppose two threads are working on a method. If two threads run on different processors each thread may have its own local copy of variable. If one thread modifies its value the change might not reflect in the original one in the main memory instantly. + * Suppose two threads are working on a method. If two threads run on different processors each thread may have its own local copy of variable. If one thread modifies its value the change might not reflect in the original one in the main memory instantly. * Now the other thread is not aware of the modified value which leads to data inconsistency.Essentially, volatile is used to indicate that a variable's value will be modified by different threads. “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself. * The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory" * An access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock.
- - + + * 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?
* In serialization, the JVM is responsible for the process of writing and reading objects. This is useful in most cases, as the programmers do not have to care about the underlying details of the serialization process. * However, the default serialization does not protect sensitive information such as passwords and credentials. * Thus externalization comes to give the programmers full control in reading and writing objects during serialization. * Implement the java.io.Externalizable interface - then you implement your own code to write object’s states in the ```writeExternal()``` method and read object’s states in the ```readExternal()``` method.
- - + + * 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?
- * The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete. + * The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete. * 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.
@@ -1001,40 +1029,40 @@ class Employee { * Arrays cannot hold generic data types whereas lists can. * Arrays can store all data types whereas lists cannot store primitive data types, only objects. * 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?
* A LinkedList contains both a head and a tail. The "Head" is the first item in the LinkedList, while the "Tail" is the last item. It is not a circular data structure, therefore the tail does not have its' pointer pointing at the Head - the pointer is just null. * No indices but each node has a pointer pointing to the next element. * They are dynamic in nature which means they allocate memory only when needed. * Insertion, deletion, updation easy * A linked list is a group of nodes which represent a sequence. Each node consists of a data and a link or reference to the next node in the sequence. - * Singly Linked List: has a node and a pointer to the next node in the sequence. + * Singly Linked List: has a node and a pointer to the next node in the sequence. * Doubly Linked List: has a node and 2 pointers - one to the next node and one to the previous node in the sequence. This is very convenient if you need to be able to traverse stored elements in both directions. * 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
- * A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. - * The left subtree of a node contains only values less than the parent node's value. + * A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. + * The left subtree of a node contains only values less than the parent node's value. * The right subtree of a node contains only values greater than or equal to the node's value. * Only if the above 2 criteria are matched, then the tree is said to be balanced. * Advantages of Binary tree over Linked List: In a linked list, the items are linked together through a single next pointer. In a binary tree, as long as the tree is balanced, the searchpath to each item is a lot shorter than that in a linked list. @@ -1043,78 +1071,78 @@ class Employee { * 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. + * 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. * The process of accessing data stored in a serial access memory is similar to manipulating data on a stack. - * A stack may be defined to have a bounded capacity i.e. if the stack is full and a new entity cannot be added, then it is considered to be in an overflow state. + * A stack may be defined to have a bounded capacity i.e. if the stack is full and a new entity cannot be added, then it is considered to be in an overflow state. * If the stack is empty and an entity cannot be popped, it is considered to be in an underflow state. * Efficiency of stacks: The time is not dependent of the no of items in the stack so it is very efficient. ```O(1)```.
- - - + + + * Queues:
- * Queues are an abstract collection that follow FIFO mechanism. The entities in the queue are kept in an order. - * Main functionalities include - * enqueue: Add an item to the end of the queue. Dequeue: remove an item from the start of the queue. - * Front: retrieves the first item from the queue. - * A queue may be defined to have a bounded capacity i.e. if the queue is full and a new entity cannot be added, then it is considered to be in an overflow state. + * Queues are an abstract collection that follow FIFO mechanism. The entities in the queue are kept in an order. + * Main functionalities include + * enqueue: Add an item to the end of the queue. Dequeue: remove an item from the start of the queue. + * Front: retrieves the first item from the queue. + * A queue may be defined to have a bounded capacity i.e. if the queue is full and a new entity cannot be added, then it is considered to be in an overflow state. * If the queue is empty and an entity cannot be popped, it is considered to be in an underflow state. * Efficiency of queues: The time is not dependent of the no of items in the queue so it is very efficient. O(1). - * A double ended queue (deque): is an abstract collection which differs from queue in a way that an item can be added/removed from either side of the queue. - * An input-restricted deque: is when deletion takes place at either end but insertion takes place at only one end. + * A double ended queue (deque): is an abstract collection which differs from queue in a way that an item can be added/removed from either side of the queue. + * An input-restricted deque: is when deletion takes place at either end but insertion takes place at only one end. * An output-restricted deque: is when insertion takes place at either end but deletion takes place only at one end. A common occurrence of deque is doubly linked list. * Priority queue: same as queue but has a priority associated with it. Items are retrieved based on their priority
- - + + * Blocking Queues:
- * A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. A thread trying to enqueue an item in a full queue is blocked until some other thread makes space in the queue. + * A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. A thread trying to enqueue an item in a full queue is blocked until some other thread makes space in the queue. * [Example on implementing a blocking queue](/src/queue/BlockingQueue.java)
- - + + * Difference between stacks & queues?
- *
- + *
+
- + * What is a deadlock in Java
* A deadlock occurs when a thread enters a waiting state because a requested system resource is held by another waiting process, which in turn is waiting for another resource held by another waiting process. * [Example on how deadlock occurs](/src/deadlock/ThreadLockDemo.java) * [Example on how to prevent deadlock](/src/deadlock/ThreadLockFixedDemo.java)
- - - + + + * 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?
- * Vectors are thread safe (synchronized) whereas arraylists are not. So performance of arraylists are better than vectors. * In ArrayList, you have to start searching for a particular element from the beginning of an Arraylist. But in the Vector, you can start searching for a particular element from a particular position in a vector. This makes the search operation in Vector faster than in ArrayList. Vectors have a default size of 10 whereas arraylists size can be dynamic. + * Vectors are thread safe (synchronized) whereas arraylists are not. So performance of arraylists are better than vectors. * In ArrayList, you have to start searching for a particular element from the beginning of an Arraylist. But in the Vector, you can start searching for a particular element from a particular position in a vector. This makes the search operation in Vector faster than in ArrayList. Vectors have a default size of 10 whereas arraylists size can be dynamic. * Insertion and deletion in ArrayList is slow compared to LinkedList? * ArrayList internally uses an array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array. - * During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node and updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
- - + * During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node and updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
+ + * Implementations of Map?
* TreeMap: sorted based on ascending order of keys. For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. - * HashTable: Does not allow null values. It is not fail-safe and it is synchronized whereas - * HashMap allows null values and it is fail-safe and it is not synchronized. + * HashTable: Does not allow null values. It is not fail-safe and it is synchronized whereas + * HashMap allows null values and it is fail-safe and it is not synchronized. * LinkedHashMap: This is a subclass of Hashmap. The order of insertion is preserved since it has a linkedList.
- - + + * Difference between Enumeration and Iterators?
- * Enumeration does not include remove() method whereas iterators do. Enumerators act as read only interface as it provides methods to read and traverse through a collection. + * Enumeration does not include remove() method whereas iterators do. Enumerators act as read only interface as it provides methods to read and traverse through a collection. * ListIterator: is just like an iterator except it allows access to the collection in either the forward or backward direction
- - + + * How Hashmap works in Java?
* HashMap in Java works on hashing principle. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. When we call put method, ```hashcode()``` method of the key object is called so that hash function of the map can find a bucket location to store Entry object. * If two different objects have the same hashcode: in this case, a linked list is formed at that bucket location and a new entry is stored as next node. After finding bucket location, we will call ```keys.equals()``` method to identify a correct node in LinkedList and return associated value object for that key in Java HashMap
- - - + + + * Generics in Java
* Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects. * Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects. @@ -1122,26 +1150,37 @@ class Employee { * Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime. * Before Generics, we need to type cast. ``` - List list = new ArrayList(); - list.add("hello"); - String s = (String) list.get(0); //typecasting + List list = new ArrayList(); + list.add("hello"); + String s = (String) list.get(0); //typecasting ``` * After Generics, we don't need to typecast the object. ``` - List list = new ArrayList(); - list.add("hello"); - String s = list.get(0); + List list = new ArrayList(); + list.add("hello"); + String s = list.get(0); ``` - * A class that can refer to any type is known as generic class. Here, we are using T type + * A class that can refer to any type is known as generic class. Here, we are using T type parameter to create the generic class of specific type. The T type indicates that it can refer to any type (like String, Integer, Employee etc.).The type you specify for the class, will be used to store and retrieve the data. * The ? (question mark) symbol represents wildcard element. It means any type. If we write , it means any child class of Number e.g. Integer, Float, double etc -
-
-
- +
+
+
+ +### System Design Interview Questions +* Design Whatsapp/Chat application/Facebook Messenger
+* Design a Location Tracking application
+* Design Uber/Ola
+* Design Twitter
+* Design BookMyShow
+ +
+
+
+ I will be adding more questions soon! If you would like to contribute to the Android Cheat Sheet, just make a pull request! - - - - - + + + + + diff --git a/src/arrays/FindMaximumSumPathInTwoArrays.java b/src/arrays/FindMaximumSumPathInTwoArrays.java new file mode 100644 index 0000000..f2062b1 --- /dev/null +++ b/src/arrays/FindMaximumSumPathInTwoArrays.java @@ -0,0 +1,95 @@ +package arrays; + + +public class FindMaximumSumPathInTwoArrays +{ + + /* + * Given two sorted arrays, such that the arrays may have some common elements. Find the sum of the maximum sum path to reach from the beginning of any array to end of any of the two arrays. We can switch from one array to another array only at common elements. + Note: The common elements do not have to be at the same indexes. + * Expected Time Complexity: O(m+n), where m is the number of elements in ar1[] and n is the number of elements in ar2[]. + * Input: ar1[] = {2, 3, 7, 10, 12},ar2[] = {1, 5, 7, 8} + * Output: 35 + * Step 1) Create some variables, result, sum1, sum2. Initialize result as 0. Also initialize two variables sum1 and sum2 as 0. Here sum1 and sum2 are used to store sum of element in ar1[] and ar2[] respectively. + * These sums are between two common points. + * Step 2) Now run a loop to traverse elements of both arrays. While traversing compare current elements of array 1 and array 2 in the following order: - + a)If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2. + b)If the current element of array 1 and array 2are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result. + c)This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that + if there is any common element it will be processed together.So the sum of elements between two common elements can be processed. + * */ + + // Utility function to find maximum of two integers + int max(int x, int y) + { + return (x > y) ? x : y; + } + + // This function returns the sum of elements on maximum path + // from beginning to end + int maxPathSum(int ar1[], int ar2[], int m, int n) + { + // initialize indexes for ar1[] and ar2[] + int i = 0, j = 0; + + // Initialize result and current sum through ar1[] and ar2[]. + int result = 0, sum1 = 0, sum2 = 0; + + // Below 3 loops are similar to merge in merge sort + while (i < m && j < n) + { + // Add elements of ar1[] to sum1 + if (ar1[i] < ar2[j]) + sum1 += ar1[i++]; + + // Add elements of ar2[] to sum2 + else if (ar1[i] > ar2[j]) + sum2 += ar2[j++]; + + // we reached a common point + else + { + // Take the maximum of two sums and add to result + result += max(sum1, sum2); + + // Update sum1 and sum2 for elements after this + // intersection point + sum1 = 0; + sum2 = 0; + + // Keep updating result while there are more common + // elements + while (i < m && j < n && ar1[i] == ar2[j]) + { + result = result + ar1[i++]; + j++; + } + } + } + + // Add remaining elements of ar1[] + while (i < m) + sum1 += ar1[i++]; + + // Add remaining elements of ar2[] + while (j < n) + sum2 += ar2[j++]; + + // Add maximum of two sums of remaining elements + result += max(sum1, sum2); + + return result; + } + + // Driver program to test above functions + public static void main(String[] args) + { + MaximumSumPath sumpath = new MaximumSumPath(); + int ar1[] = {2, 3, 7, 10, 12, 15, 30, 34}; + int ar2[] = {1, 5, 7, 8, 10, 15, 16, 19}; + int m = ar1.length; + int n = ar2.length; + System.out.println("Maximum sum path is :" + + sumpath.maxPathSum(ar1, ar2, m, n)); + } +} diff --git a/src/arrays/MergeTwoSortedArrays.java b/src/arrays/MergeTwoSortedArrays.java new file mode 100644 index 0000000..b517693 --- /dev/null +++ b/src/arrays/MergeTwoSortedArrays.java @@ -0,0 +1,63 @@ +package arrays; + +import java.util.ArrayList; +import java.util.List; + +public class MergeTwoSortedArrays +{ + + + /* + * We are given two sorted array. We need to merge these two arrays such that the initial numbers (after complete sorting) are in the first array and the remaining numbers are in the second array. Extra space allowed in O(1). + * Expected Time Complexity: O(m+n), where m is the number of elements in ar1[] and n is the number of elements in ar2[]. + * Input: ar1[] = {10},ar2[] = {2, 3} + * Output: ar1[] = {2},ar2[] = {3, 10} + * + * Extra space allowed in O(1) + * 1) Iterate through every element of ar2[] starting from last + element. Do following for every element ar2[i] + a) Store last element of ar1[i]: last = ar1[i] + b) Loop from last element of ar1[] while element ar1[j] is + smaller than ar2[i]. + ar1[j+1] = ar1[j] // Move element one position ahead + j-- + c) If any element of ar1[] was moved or (j != m-1) + ar1[j+1] = ar2[i] + ar2[i] = last + * */ + + static int arr1[] = new int[]{1, 5, 9, 10, 15, 20}; + static int arr2[] = new int[]{2, 3, 8, 13}; + + static void merge(int m, int n) + { + // Iterate through all elements of ar2[] starting from + // the last element + for (int i = n - 1; i >= 0; i--) + { + /* Find the smallest element greater than ar2[i]. Move all + elements one position ahead till the smallest greater + element is not found */ + int j, last = arr1[m - 1]; + for (j = m - 2; j >= 0 && arr1[j] > arr2[i]; j--) + arr1[j + 1] = arr1[j]; + + // If there was a greater element + if (j != m - 2 || last > arr2[i]) + { + arr1[j + 1] = arr2[i]; + arr2[i] = last; + } + } + } + + // Driver method to test the above function + public static void main(String[] args) + { + merge(arr1.length, arr2.length); + System.out.print("After Merging nFirst Array: "); + System.out.println(Arrays.toString(arr1)); + System.out.print("Second Array: "); + System.out.println(Arrays.toString(arr2)); + } +} diff --git a/src/arrays/Segregate0And1s.java b/src/arrays/Segregate0And1s.java new file mode 100644 index 0000000..17395a5 --- /dev/null +++ b/src/arrays/Segregate0And1s.java @@ -0,0 +1,57 @@ +package arrays; + +import java.util.ArrayList; +import java.util.List; + +public class Segregate0And1s +{ + + + /* + * You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once. + * Input: ar[] = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] + * Output: ar[] = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] + * Steps- + * 1) Count the number of 0s. Let count be C. + 2) Once we have count, we can put C 0s at the beginning and 1s at the remaining n – C positions in array. + * */ + // function to segregate 0s and 1s + + static void segregate0and1(int arr[], int n) + { + int count = 0; // counts the no of zeros in arr + + for (int i = 0; i < n; i++) + { + if (arr[i] == 0) + count++; + } + + // loop fills the arr with 0 until count + for (int i = 0; i < count; i++) + arr[i] = 0; + + // loop fills remaining arr space with 1 + for (int i = count; i < n; i++) + arr[i] = 1; + } + + // function to print segregated array + static void print(int arr[], int n) + { + System.out.print("Array after segregation is "); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // driver function + public static void main(String[] args) + { + int arr[] = new int[]{0, 1, 0, 1, 1, 1}; + int n = arr.length; + + segregate0and1(arr, n); + print(arr, n); + + } +} diff --git a/src/linkedlist/ReverseDoublyLinkedList.java b/src/linkedlist/ReverseDoublyLinkedList.java new file mode 100644 index 0000000..3671bb2 --- /dev/null +++ b/src/linkedlist/ReverseDoublyLinkedList.java @@ -0,0 +1,107 @@ +package linkedlist; + + +public class ReverseDoublyLinkedList +{ + + /* + * Runtime Complexity: + * Linear, O(n). + * As we can reverse the doubly linked list + * */ + + + static Node head; + + static class Node + { + + int data; + Node next, prev; + + Node(int d) + { + data = d; + next = prev = null; + } + } + + /* Function to reverse a Doubly Linked List */ + void reverse() + { + Node temp = null; + Node current = head; + + /* swap next and prev for all nodes of + doubly linked list */ + while (current != null) + { + temp = current.prev; + current.prev = current.next; + current.next = temp; + current = current.prev; + } + + /* Before changing head, check for the cases like empty + list and list with only one node */ + if (temp != null) + { + head = temp.prev; + } + } + + /* UTILITY FUNCTIONS */ + /* Function to insert a node at the beginning of the Doubly Linked List */ + void push(int new_data) + { + /* allocate node */ + Node new_node = new Node(new_data); + + /* since we are adding at the beginning, + prev is always NULL */ + new_node.prev = null; + + /* link the old list off the new node */ + new_node.next = head; + + /* change prev of head node to new node */ + if (head != null) + { + head.prev = new_node; + } + + /* move the head to point to the new node */ + head = new_node; + } + + /* Function to print nodes in a given doubly linked list + This function is same as printList() of singly linked list */ + void printList(Node node) + { + while (node != null) + { + System.out.print(node.data + " "); + node = node.next; + } + } + + public static void main(String[] args) + { + LinkedList list = new LinkedList(); + + /* Let us create a sorted linked list to test the functions + Created linked list will be 10->8->4->2 */ + list.push(2); + list.push(4); + list.push(8); + list.push(10); + + System.out.println("Original linked list "); + list.printList(head); + + list.reverse(); + System.out.println(""); + System.out.println("The reversed Linked List is "); + list.printList(head); + } +} diff --git a/src/sort/HeapSort.java b/src/sort/HeapSort.java new file mode 100644 index 0000000..c739258 --- /dev/null +++ b/src/sort/HeapSort.java @@ -0,0 +1,84 @@ +package sort; + +import java.util.Arrays; + +public class HeapSort +{ + + + /* + * 1. Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. * 2. The worst case time complexity of bubble sort is O(n2): this is because for each iteration n-1 comparisons will be done. + * 2.The best,average and worst case time complexity will be O(n log(n)): + * 4. The space time complexity will be O(1): + * */ + public void sort(int arr[]) + { + int n = arr.length; + + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i = n - 1; i > 0; i--) + { + // Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + + // To heapify a subtree rooted with node i which is + // an index in arr[]. n is size of heap + void heapify(int arr[], int n, int i) + { + int largest = i; // Initialize largest as root + int l = 2 * i + 1; // left = 2*i + 1 + int r = 2 * i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver program + public static void main(String args[]) + { + int arr[] = {12, 11, 13, 5, 6, 7}; + int n = arr.length; + + HeapSort ob = new HeapSort(); + ob.sort(arr); + + System.out.println("Sorted array is"); + printArray(arr); + } +} From 961f38d5e8c6619037b1b1f0046e8b12aad3394e Mon Sep 17 00:00:00 2001 From: niharika2810 <40764403+niharika2810@users.noreply.github.com> Date: Sun, 14 Jun 2020 00:25:05 +0530 Subject: [PATCH 2/4] Update README.md --- README.md | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 08bbff0..9974d07 100644 --- a/README.md +++ b/README.md @@ -196,21 +196,22 @@ Cheat Sheet for Android Interviews 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.
-* Application LifeCycle?
+*
Application LifeCycle?
-* How to achieve Interprocess communication in android?
+*
How to achieve Interprocess communication in android?
-* Why do we use Headless fragments?
+*
Why do we use Headless fragments?
-* Design patterns in Android
+*
Design patterns in Android
-* Map vs FlatMap operator in Rxjava?
+*
Map vs FlatMap operator in Rxjava?
-* Role of Handlers,Loopers and MessageQueue in Android?
+*
Role of Handlers,Loopers and MessageQueue in Android?
-* Why do we prefer Framelayout for Fragments?
+*
Why do we prefer Framelayout for Fragments?
+ +* How to make endless circular recyclerView?
-* How to make endless circular recyclerView?
* 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](https://developer.android.com/ndk/guides/abis)
@@ -725,13 +726,13 @@ savedInstanceState.Also it won't affect the performance even if there are large * Why is Java said to be platform independent?
* The execution of the code does not depend upon the OS
-*
Inner vs Static Nested Classes?
+*
Inner vs Static Nested Classes?
-* Why do we have Thread Pools in java?
+*
Why do we have Thread Pools in java?
-* Does Java pass by reference or pass by value?
+*
Does Java pass by reference or pass by value?
-* how to implement Custom Exceptions?
+*
how to implement Custom Exceptions?
* 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.
From cf4058209b0aa52d89b66022dc0c37169ee886f6 Mon Sep 17 00:00:00 2001 From: niharika2810 <40764403+niharika2810@users.noreply.github.com> Date: Sun, 14 Jun 2020 00:26:45 +0530 Subject: [PATCH 3/4] Update README.md Removed bold from system design questions --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 9974d07..ee274df 100644 --- a/README.md +++ b/README.md @@ -1169,11 +1169,11 @@ parameter to create the generic class of specific type. The T type indicates tha
### System Design Interview Questions -* Design Whatsapp/Chat application/Facebook Messenger
-* Design a Location Tracking application
-* Design Uber/Ola
-* Design Twitter
-* Design BookMyShow
+* Design Whatsapp/Chat application/Facebook Messenger
+* Design a Location Tracking application
+* Design Uber/Ola
+* Design Twitter
+* Design BookMyShow


From 5401e097417b6cffeba4dba83538ce15d5c68bde Mon Sep 17 00:00:00 2001 From: niharika2810 <40764403+niharika2810@users.noreply.github.com> Date: Sun, 14 Jun 2020 00:29:29 +0530 Subject: [PATCH 4/4] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ee274df..86ad10a 100644 --- a/README.md +++ b/README.md @@ -732,7 +732,7 @@ savedInstanceState.Also it won't affect the performance even if there are large * Does Java pass by reference or pass by value?
-* how to implement Custom Exceptions?
+* How to implement Custom Exceptions?
* 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.