Wednesday, December 30, 2015

Android Services

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.

two forms

       - Started ( run in the background indefinitely )
       - Bounded ( client-server interface that allows components to interact )

- A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). 


      Creating a Started Service

            - Service
            - IntentService

- The return value from onStartCommand() escribes how the system should continue the service in the event that the system kills it

  1. START_NOT_STICKY - do not recreate the service, unless there are pending intents to deliver. 
  2. START_STICKY - started with null when there is no pending request. delivers intent when there is pending request.
  3. START_REDELIVER_INTENT - recreate the service with the last intent that was delivered to the service

    Creating a Bound Service
           - Local Binder ( if the service is private to the app )
           - Messenger
           - AIDL

     AIDL
          - By default, AIDL supports the following data types:

  - All primitive types in the Java programming language (such as int, long, char, boolean, and so on)
  -  String, CharSequence, List, Map


Binder - Internal

 ( Source )

Activities Android

- Container of UI

  Starting Activity
- startActivity / startActivityForResult / setResult/ onActivityResult

Implementing the lifecycle callbacks

Saving activity state
- onSaveInstanceState (Bundle)
- onCreate(Bundle) or onRestoreInstanceState(Bundle)

Handling configuration changes

Coordinating activities

   Tasks and Back Stack
- A task is a collection of activities that users interact with when performing a certain job.
- The activities are arranged in a stack (the back stack), in the order in which each activity is opened.
- When the user touches an icon in the application launcher that application's task comes to the foreground. If no task exists for the application (the application has not been used recently), then a new task is created and the "main" activity for that application opens as the root activity in the stack.
- When new activity is started, it's pushed in to back stack. The previous activity stopped and system retains it current user interface state. When user presses back key , activity which is in top of back stack is popped and destroyed by system and previous activity just resumes its state. 

Managing Tasks
- Application allows users to start a particular activity from more than one activity, a new instance of that activity is created and pushed onto the stack . one activity in your application might be instantiated multiple times. you can modify this behaviour if you do not want an activity to be instantiated more than once using below methods.
 
- standard ( default )

- singleTop 
- instantiated multiple times.
- launched into the task that called startActivity ((unless the Intent object contains a FLAG_ACTIVITY_NEW_TASK instruction)
- if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the "singleTop" activity is in the target task, but not at the top of the stack, or if it's at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack.
                                - Ex : Search Activity
 
- singleTask
- begins a task and always at the root of the activity stack
- the device can hold only one instance of the activity at a time — only one such task.
- allows other activities to be part of its task.

- singleInstance
- begins a task and always at the root of the activity stack
- the device can hold only one instance of the activity at a time — only one such task.
- permits no other activities to be part of its task.
                              - Ex: Activity for Launcher

Using Intent flags
- When starting an activity, you can modify the default association of an activity to its task by including flags in the intent  that you deliver to startActivity()
- FLAG_ACTIVITY_NEW_TASK
- FLAG_ACTIVITY_SINGLE_TOP
- FLAG_ACTIVITY_CLEAR_TOP


Note:
             - Similarly, if you navigate up (NavUtils.navigateUpTo(this, upIntent)) to an activity on the current stack, the behavior is determined by the parent activity's launch mode. If the parent activity has launch mode singleTop (or the up intent contains FLAG_ACTIVITY_CLEAR_TOP), the parent is brought to the top of the stack, and its state is preserved. The navigation intent is received by the parent activity's onNewIntent() method. If the parent activity has launch mode standard (and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP), the current activity and its parent are both popped off the stack, and a new instance of the parent activity is created to receive the navigation intent.
            - "singleTask" and "singleInstance", should be used only when the activity has an ACTION_MAIN and a CATEGORY_LAUNCHER filter.


Clearing the back stack 
- If the user leaves a task for a long time, the system clears the task of all activities except the root activity. When the user returns to the task again, only the root activity is restored. There are some activity attributes that you can use to modify this behavior

- alwaysRetainTaskState: retains all activities in its stack even after a long period, if this attribute is set to "true" in the root activity of a task.
- clearTaskOnLaunch: The user always returns to the task in its initial state, even after a leaving the task for only a moment.
- finishOnTaskLaunch: This attribute is like clearTaskOnLaunch, but it operates on a single activity, not an entire task.


LaunchMode Use case example
      http://inthecheesefactory.com/blog/understand-android-activity-launchmode/en

Tuesday, December 29, 2015

Android Topics for Interview preparation

1. Activity
        - LaunchModes
        - Fragment
        - Loader
        - AsyncTask

2. Service
      - Started
      - Bounded
             - AIDL
             - Messenger
             - Parcelable

3. ContentProvider
            - SQLITE
            - Filesharing

4. Receivers
           - Ordered broadcast
           - Sticky/ non-Sticky 

Others
      - Handler
      - SharedPreference
      - Bundle & Methods to pass data between activities
      - Notification on status bar
      - Push Notification
      - Account Manager/ Sync Adapter
      - Permission
      - Rest API (Volley, JSON etc..)
      - Tools
            - hierarchyviewer
            - DDMS ( RAM Analyser, Thread monitoring etc..)
            - Traceview
            - HPROF
      - Custom View/ Layout
      - Android Architecture
      - NotificationListenerService
      - Writing app widgets
      - Search widget framework
      - System service
      - Handling Bitmap
      - Intent/ Intent-Filters
      - Material design
      - Android Run Time

Android Studio
     - Lint
     - Proguard

Sunday, December 27, 2015

HashSet Java Interview Questions

1. How Hashset  works internally in Java or how HashSet works in java?

2. What copy technique internally used by HashSet clone() method ? 

3. Why HashSet does not have get(Object o) method ?

4. What is the difference between HashSet and TreeSet ?

5. What is and when to use Collections.emptySet() . What is the advantage of having emptySet in Collections class ?

6. What is the default initial capacity and initial load factor of HashSet object?

7. HashMap is not thread Safe so we have ConcurrentHashMap(thread safe).
   Why Java do not have ConcurrentHashSet class just like ConcurrentHashMap , as we know HashSet is also not thread  safe and internally use HashMap.
   
8.  What is HashSet ? What are the properties of HashSet object?

9. Why does HashSet implementation in Sun Java use HashMap as its backing?

10. What interfaces are implemented by the HashSet Class ? Which is the superclass of HashSet Class?

[ Source ]   
   

Java Interview Questions


  1. What does RandomAccess mean?
  2. What is thread contention?
  3. Java 8 New Features? Lambda Expressions , Optional Class , Defender Methods
  4. What is Atomic in Java?
  5. 133 Core Java Interview Questions Answers?
  6. What is the difference between ArrayList.clear() and ArrayList.removeAll()? [ Ans... ]
  7. What are checked/unchecked exceptions?
    • All Unchecked exceptions are direct sub classes of RuntimeException class. Unchecked exceptions are to fix app data error.
  8. Comparable vs Comparator?
  9. What is marker interface?
  10. Java 7 features?


Array List Interview Questions

How to remove duplicates from ArrayList in Java? 

How to reverse ArrayList in Java?


Difference between an array and ArrayList in Java?

How to synchronize ArrayList in Java?


When to use ArrayList and LinkedList in Java?


Difference between ArrayList and HashSet in Java?


How to loop over ArrayList in Java?


Difference between Vector and ArrayList in Java?


How to create and initialize ArrayList in one line?


How to sort ArrayList in Java?


Difference between HashMap and ArrayList in Java?


How to use ArrayList in Java?


How to convert ArrayList to String in Java?


How to get sublist from ArrayList in Java?


Difference between length() of array and size() of ArrayList in Java?


What is CopyOnWriteArrayList in Java?


How to remove objects from ArrayList in Java? 


How to make ArrayList read only in Java?


How to sort ArrayList in descending order in Java?


Reference

Fail Fast Vs Fail Safe Iterator In Java

Concurrent Modification
           When one or more thread is iterating over the collection, in between, one thread changes the structure of the collection (either adding the element to the collection or by deleting the element in the collection or by updating the value at particular position in the collection) is known as Concurrent Modification

Fail fast Iterator

          Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly

Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.  So , original data structure remains  structurally unchanged .Hence , no ConcurrentModificationException throws by the fail safe iterator.

Java Collections

History

          Java 1.0 -> Vector, Dictionary, HashTable, Stack, Enumeration
          Java 1.2 -> Collection, Iterator, List, Set, Map, ArrayList, HashSet, TreeSet, HashMap, WeakHashMap
          Java 1.4 -> Random Access, IdentityHashMap, LinkedHashMap, LinkedHashSet
          Java 1.5 -> Queue, concurrent package
          Java 1.6 -> Deque, ConcurrentSkipListSet & Map ....
          Java 1.7 -> TransferQueue, LInkedTransferQueue

List
  • ArrayList
  • LinkedArrayList
  • CopyOnWriteArrayList ( concurrent )

  • ArrayList
    LInkedList
    CopyOnWriteArrayList
    Data Structure
    Array
    Linked List
    Array
    Iterator
    Fail-fast
    Fail-fast
    Fail-Safe
    Null
    Yes
    Yes
    Yes
    Add
    O(I)
    O(I)
    O(n)
    Remove
    O(n)
    O(I)
    O(n)
    Get
    O(I)
    O(n)
    O(I)
    Contains
    O(n)
    O(n)
    O(n)

      ArrayList
                 - Default capacity 10
                 - Indexed access

Set



















Queue



       PriorityQueue
               - represented as a balanced binary heap.
               - default initial capacity 11

      BlockingQueue

      DelayQueue


TransferQueue
     - Producers may wait for consumers to receive elements. TransferQueue may be useful for example in message passing applications in which producers sometimes await receipt of elements by consumers
     - Similar to SynchronousQueue
             


Deque ( double ended queue )
      - A linear collection that supports element insertion and removal at both ends.

      Implementations
      - LinkedList
      - ArrayDeque
      - LinkedBlockingDeque

Map



      WeakHashMap
          - Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use.  
     
IdentityHashMap is a variant on HashMap which tests equality by reference instead of equality by value. Basically, keys and values are compared for equality by checking if their references are equal rather than by calling the "equals" function.

     ConcurrentHashMap 
            - Reference Jenkov JavaHungry

Thursday, December 24, 2015

Quick Sort

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
/**
 * Simple Quick sort
 * 
 * Time Complexity: 
 *    Average - O(nLogn)
 *    Worst case - O(n^2)
 * 
 * Note:
 *   - Is in-place algorithm
 *   - 39% more compare than merge sort
 *   - Faster than merge sort in practice because of less data movement 
 * 
 * @author ramesh
 *
 */
public class Quicksort {
 private static final int ARRAY_DEFAULT_SIZE = 20;

 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);

  List<String> list = new ArrayList<String>(ARRAY_DEFAULT_SIZE);

  while (scanner.hasNext()) {
   String item = scanner.next();

   if (item.equals("exit"))
    break;
   else {
    list.add(item);
   }
  }

  String ip_array[] = new String[list.size()];
  for (int i = 0; i < ip_array.length; i++) {
   ip_array[i] = list.get(i);
  }

  sort(ip_array);

  for (int i = 0; i < ip_array.length; i++) {
   System.out.println(ip_array[i]);
  }

  scanner.close();
 }

 private static void sort(Comparable[] ip_array) {
  sort(ip_array, 0, ip_array.length - 1);
 }

 private static void sort(Comparable[] ip_array, int lo, int hi) {
  if (hi <= lo)
   return;

  int partition = partition(ip_array, lo, hi);

  sort(ip_array, lo, partition - 1);
  sort(ip_array, partition + 1, hi);
 }

 private static int partition(Comparable[] ip_array, int lo, int hi) {
  int right_index = hi+1;
  int left_index = lo;

  Comparable v = ip_array[lo];

  while (true) {

   while (isLess(ip_array[++left_index], v)) {
    if (left_index == hi)
     break;
   }

   while (isLess(v, ip_array[--right_index])) {
    if (right_index == lo)
     break;
   }

   if (right_index <= left_index)
    break;

   exch(ip_array, right_index, left_index);
  }

  exch(ip_array, lo, right_index);

  return right_index;
 }

 private static void exch(Comparable[] ip_array, int right_index, int left_index) {
  Comparable temp = ip_array[right_index];
  ip_array[right_index] = ip_array[left_index];
  ip_array[left_index] = temp;

 }

 private static boolean isLess(Comparable a, Comparable b) {
  return a.compareTo(b) < 0;
 }
}

Merge Sort


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
 * 
 * Simple merge sort
 * 
 * Time Complexity: Worse case - O(nLogn)
 * Auxiliary Space: O(n) 
 * Application: Used in External Sorting
 * 
 * Note
 *   - Merge sort is optimal with respect to # compares,
 *     But not optimal with respect to space usage
 * 
 *   - Merge sort is generally considered better when data is huge and stored in external storage
 * 
 * @author ramesh
 *
 */

public class Merge {

 private static final int ARRAY_DEFAULT_SIZE = 20;

 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);

  List<String> list = new ArrayList<String>(ARRAY_DEFAULT_SIZE);

  while (scanner.hasNext()) {
   String item = scanner.next();

   if (item.equals("exit"))
    break;
   else {
    list.add(item);
   }
  }

  String ip_array[] = new String[list.size()];
  for (int i = 0; i < ip_array.length; i++) {
   ip_array[i] = list.get(i);
  }

  sort(ip_array);
  
  for (int i = 0; i < ip_array.length; i++) {
   System.out.println(ip_array[i]);
  }

  scanner.close();
 }

 private static void sort(Comparable[] a) {
  Comparable[] aux = new Comparable[a.length];
  sort(a, aux, 0, a.length-1);
 }

 private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
  if (hi <= lo)
   return;

  int mid = lo + (hi - lo) / 2;

  sort(a, aux, lo, mid);
  sort(a, aux, mid + 1, hi);

  merge(a, aux, lo, mid, hi);
 }

 private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
  for (int i = lo; i <= hi; i++) {
   aux[i] = a[i];
  }

  int first_index = lo;
  int second_index = mid + 1;

  for (int i = lo; i <= hi; i++) {

   if (first_index > mid) {
    a[i] = aux[second_index++];
   } else if (second_index > hi) {
    a[i] = aux[first_index++];
   } else if (aux[first_index].compareTo(aux[second_index]) < 0) {
    a[i] = aux[first_index++];
   } else {
    a[i] = aux[second_index++];
   }
  }
 }
}

Heap Sort

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
 * 
 * 
 * Time Complexity: O(nLogn)
 * 
 * 
 * Note:
 *   - Heap sort is an in-place algorithm.
 *   - 
 * 
 * Application
 *   - Priority Queues
 * 
 * @author ramesh
 *
 */
public class Heapsort {
 private static final int ARRAY_DEFAULT_SIZE = 20;

 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);

  List<String> list = new ArrayList<String>(ARRAY_DEFAULT_SIZE);

  while (scanner.hasNext()) {
   String item = scanner.next();

   if (item.equals("exit"))
    break;
   else {
    list.add(item);
   }
  }

  String ip_array[] = new String[list.size()];
  for (int i = 0; i < ip_array.length; i++) {
   ip_array[i] = list.get(i);
  }

  sort(ip_array);

  for (int i = 0; i < ip_array.length; i++) {
   System.out.println(ip_array[i]);
  }

  scanner.close();
 }

 private static void sort(Comparable[] a) {
  int N = a.length;
  for (int i = N / 2; i >= 1; i--) {
   sink(a, i, N);
  }

  while (N > 1) {
   exch(a, 1, N--);
   sink(a, 1, N);
  }
 }

 private static void exch(Comparable[] ip_array, int right_index, int left_index) {
  Comparable temp = ip_array[right_index - 1];
  ip_array[right_index - 1] = ip_array[left_index - 1];
  ip_array[left_index - 1] = temp;
 }

 private static void sink(Comparable[] a, int k, int N) {
  while (k * 2 <= N) {
   int j = k * 2;
   if (j < N && isLess(a, j, j + 1))
    j++;
   if (!isLess(a, k, j))
    break;
   exch(a, j, k);
   k = j;
  }
 }

 private static boolean isLess(Comparable[] pq, int i, int j) {
  return pq[i - 1].compareTo(pq[j - 1]) < 0;
 }
}