- Retrofit/Volley :- Networking libraries which ease your task of writing long network requests and related boiler-plate code.
- Picasso/Glide :- Loading image into imageview from an url is made very simple using any one of these.
- Simple Facebook :- Will relatively ease your burden of implementing facebook social login.
- ActiveAndroid/GreenDAO :- Reduces the boilerplate code required for interacting with local Sqlite database.
Volley Vs Retrofit
Volley has flexible caching mechanism whereas Retrofit does not provide support for caching.
Volley support retrying mechanism whereas Retrofit does not provide support for retrying.
Volley is a networking library, developed by Google engineers.
It was introduced in Google IO 2013, it offers great features like synchronous requests, asynchronous requests,
prioritization, making multiple requests at the same time, ordered requests and of course caching. But one of the major problems faced by
developers using this library is that it lacks detailed official documentation.
On the other hand Retrofit is a clean, simple, and light library for Android by Square, Inc.
In other words, Retrofit is a REST client for Android, through which you can make easy to use interfaces which can turn
any Android app into a powerful one. What makes it different is that, Retrofit can perform Async and sync requests with automatic
JSON parsing without any effort. This feature alone makes it powerful enough to make a contender for this comparison.
2) In-Built Request Types
The data returned from a web service always complicates the implementation, but thankfully now with help of these libraries almost all types of responses can be captured. Android Volley can capture four types of responses automatically through these requests:
StringRequest – Make this type of request and the returned data is parsed and converted in to a String.
JsonObjectRequest – This type of request converts the response in to a JSONObject.
JsonArrayRequest – Make this type of request and response is automatically converted into a JSONArray.
ImageRequest – This type of request converts the response into a decoded bitmap automatically.
On the other hand Retrofit can parse many other types of responses automatically like:
Boolean – Web API response needs to be a String boolean.
Integer – Web API response needs to be an integer.
Date– Web API response should be Long format date.
String – Web API response needs to be in String format.
Object – Web API response needs to be in Json object.
Collections – Web API response needs to be in a String Format.
Interface some important points
1)final , static , synchronized,native and strictfp cannot be applied to interface methods since these are abstract methods
2)staic block , instance block not allowed in interface
3)constructor not applicable in interface
4)Volatile not used with variables in interface
5)Interface variable initialisation is mandatory
Overloading OverRiding
Method names must be same must be same
Method Sig &
Arg type must be diff must be same
Return type may/may not be diff must be same(Covariant allowed
from 1.5)
private static
final allowed Not allowed
Access
Modifier No restriction Increase allowed dnt decrease
Throws No restriction If child class has checked exception then parent class should have either same exception or parent of the exception declared in child class
System .out.println
System is a class present in java.lang package
Out is a static variable in system class of type PrintStream
Println is a method in PrintStream class
Improve web view performance
WebViewClient provided by Android has this magical method called shouldInterceptRequest,
which can be overridden. What it basically allows you to do is intercept any request
(to fetch HTML, CSS, JS, images, fonts etc) going from the WebView and gives you the ability to take some
actions before network calls are made.
shouldInterceptRequest returns a WebResourceResponse which is created by data loaded from the network.
All you need to explicitly create appropriate WebResourceResponse is MIME type, encoding format and input stream
(can be created from assets or files) of the resource. So, you can create a WebResourceResponse for CSS/JS request being made
if you have it stored somewhere in the app (may be in assets or file system) and return it instead of making a network call to get it!
Fragment vs custom views
All state transitions can be handled using fragemnts since they have lifecucle methods
Backstatck maintanance is easy in fragments
What is synchronous and asynchronous
So, the execution which happens independently, without interrupting the Normal flow of execution is called Asynchronous call.
This sequential behavior can be termed as Synchronous behavior.
While using sharedPreferences
commit() is instantaneous and performs disk writes. If we’re on the main UI thread apply() should be used since it’s asynchronous.
Regarding Main method in java
There are no modifiers in java.We have only specifiers
Cannot change main method in java , if we change the name of main method then jvm customization is needed.
Since Main method is configured in JVM
JVM should call this from any where and hence we declare it is public
main is class level method , with out obj creation also JVM should call this and hence it is static.
Main method is nowhere related to object
Main method wont return any thing to JVM and hence it has void return type
String[] args are command line arguments
Acceptable changes in main method
1)Order of modifiers is not important
static public is also valid
2)Declare string array in any acceptable form String []args String args[]
3)Instead of args[] any valid java modifier is allowed
4)var args allowed i.e repalce string array String... args
5)final , synchronized , strinctfp allowed in main method
Difference between merge and include
Let’s say that you have a layout, call it main_layout, with a LinearLayout as its root view. You also have a layout, include_layout that you want to include in the main_layout. It also has a LinearLayout as its root view.
Now when you include it, there will be two LinearLayouts in the main-layout. The second LinearLayout doesn’t serve any purpose as the main_layout’s LinearLayout takes care of arranging the views. The extra LinearLayout only slows the app up and wastes scarce resources.
Using <merge> as the root view of your included file solves the problem.
Http and Https
Whether it’s HTTP or HTTPS both are protocol designed to transfer information between computers over WWW (World Wide Web). The main difference comes into play when “S” is attached with the “HTTP.” Simply, HTTP (Hyper Text Transfer Protocol), does the same thing as HTTPS like transferring information like document, file, image, video between computers over internet, but it is not in an encrypted format, due to this it becomes vulnerable to attacks happens over internet. Apart from this, let see some other differences.
Important point:
When activity contains fragment and when onback is pressed then ondestroy is not called only onstop of fragment and activity are called.
When er start app again onrestart of activity gets called and life cycle continues
onrestart of act-->onstart of act-->onstart of fragment-->onresume of act-->onresume of fragment...
Upcasting
Ex: class A{}
class B extend A{}
A a1 = new B();
this operation is a upcasting. and it happens automatically.no need to do anything explicitly.
We use when we do not know exact runtime of the object
Child specific methods cannot be called
here we can call the methods defined/declared in A but during runtime it will call class B’s overridden methods.
if the method is not overridden in child’s class then only parent’s method which will be inherited to child will be called.
but same is not applicable to variables because variables decision happens at a compile time so always class A’s variables (not child’s inherited variables) will be accessed.
Downcasting : is not directly possible in Java.
ex:
Copy this code
Child c = new Parent();
for the above program will not work. it is compile time error.
Parent p = new Child();
Child c =(Child) p;
Accessing elements are faster with ArrayList, because it is index based. But accessing is difficult with LinkedList. It is slow access.
This is to access any element, you need to navigate through the elements one by one.
But insertion and deletion is much faster with LinkedList, because if you know the node,
just change the pointers before or after nodes. Insertion and deletion is slow with ArrayList,
this is because, during these operations ArrayList need to adjust the indexes according to deletion or insetion
if you are performing on middle indexes. Means, an ArrayList having 10 elements, if you are inserting at index 5,
then you need to shift the indexes above 5 to one more. -
Linked List
- Linked lists are used to implement queues, stacks, graphs, etc.
- In Linked Lists you don’t need to know the size in advance.
- Linked lists let you insert elements at the beginning and end of the list.
- To reach a particular node, you need to go through all those nodes that come before that node.
Insert at first position in linked list
Node *head;
void InsertNodeAtFront(int data)
{
/* 1. create the new node*/
Node *temp = new Node;
temp->data = data;
/* 2. insert it at the first position*/
temp->next = head;
/* 3. update the head to point to this new node*/
head = temp;
}
To display Singly Linked List from First to Last,
- Create a linked list using create().
- You cannot change the address stored inside global variable “start” therefore you have to declare one temporary variable -“temp” of type node
- To traverse from start to end, you should allot address of Starting node in Pointer variable i.e temp.
1
2
3
struct node *temp; //Declare temp
temp = start; //Assign Starting Address to temp
If the temp is NULL then you can say that last node is reached.
Find Middle element in linked list
As if you think carefully you can solve this problem by using two pointers as mentioned in my last post on How to find length of Singly Linked List in Java. By using two pointers, incrementing one at each iteration and other at every second iteration. When first pointer will point at end of Linked List, second pointer will be pointing at middle node of Linked List.
Volley Vs Retrofit
Volley has flexible caching mechanism whereas Retrofit does not provide support for caching.
Volley support retrying mechanism whereas Retrofit does not provide support for retrying.
Volley is a networking library, developed by Google engineers.
It was introduced in Google IO 2013, it offers great features like synchronous requests, asynchronous requests,
prioritization, making multiple requests at the same time, ordered requests and of course caching. But one of the major problems faced by
developers using this library is that it lacks detailed official documentation.
On the other hand Retrofit is a clean, simple, and light library for Android by Square, Inc.
In other words, Retrofit is a REST client for Android, through which you can make easy to use interfaces which can turn
any Android app into a powerful one. What makes it different is that, Retrofit can perform Async and sync requests with automatic
JSON parsing without any effort. This feature alone makes it powerful enough to make a contender for this comparison.
2) In-Built Request Types
The data returned from a web service always complicates the implementation, but thankfully now with help of these libraries almost all types of responses can be captured. Android Volley can capture four types of responses automatically through these requests:
StringRequest – Make this type of request and the returned data is parsed and converted in to a String.
JsonObjectRequest – This type of request converts the response in to a JSONObject.
JsonArrayRequest – Make this type of request and response is automatically converted into a JSONArray.
ImageRequest – This type of request converts the response into a decoded bitmap automatically.
On the other hand Retrofit can parse many other types of responses automatically like:
Boolean – Web API response needs to be a String boolean.
Integer – Web API response needs to be an integer.
Date– Web API response should be Long format date.
String – Web API response needs to be in String format.
Object – Web API response needs to be in Json object.
Collections – Web API response needs to be in a String Format.
Interface some important points
1)final , static , synchronized,native and strictfp cannot be applied to interface methods since these are abstract methods
2)staic block , instance block not allowed in interface
3)constructor not applicable in interface
4)Volatile not used with variables in interface
5)Interface variable initialisation is mandatory
Overloading OverRiding
Method names must be same must be same
Method Sig &
Arg type must be diff must be same
Return type may/may not be diff must be same(Covariant allowed
from 1.5)
private static
final allowed Not allowed
Access
Modifier No restriction Increase allowed dnt decrease
Throws No restriction If child class has checked exception then parent class should have either same exception or parent of the exception declared in child class
System .out.println
System is a class present in java.lang package
Out is a static variable in system class of type PrintStream
Println is a method in PrintStream class
WebViewClient provided by Android has this magical method called shouldInterceptRequest,
which can be overridden. What it basically allows you to do is intercept any request
(to fetch HTML, CSS, JS, images, fonts etc) going from the WebView and gives you the ability to take some
actions before network calls are made.
shouldInterceptRequest returns a WebResourceResponse which is created by data loaded from the network.
All you need to explicitly create appropriate WebResourceResponse is MIME type, encoding format and input stream
(can be created from assets or files) of the resource. So, you can create a WebResourceResponse for CSS/JS request being made
if you have it stored somewhere in the app (may be in assets or file system) and return it instead of making a network call to get it!
Fragment vs custom views
All state transitions can be handled using fragemnts since they have lifecucle methods
Backstatck maintanance is easy in fragments
What is synchronous and asynchronous
So, the execution which happens independently, without interrupting the Normal flow of execution is called Asynchronous call.
This sequential behavior can be termed as Synchronous behavior.
While using sharedPreferences
commit() is instantaneous and performs disk writes. If we’re on the main UI thread apply() should be used since it’s asynchronous.
Regarding Main method in java
There are no modifiers in java.We have only specifiers
Cannot change main method in java , if we change the name of main method then jvm customization is needed.
Since Main method is configured in JVM
JVM should call this from any where and hence we declare it is public
main is class level method , with out obj creation also JVM should call this and hence it is static.
Main method is nowhere related to object
Main method wont return any thing to JVM and hence it has void return type
String[] args are command line arguments
Acceptable changes in main method
1)Order of modifiers is not important
static public is also valid
2)Declare string array in any acceptable form String []args String args[]
3)Instead of args[] any valid java modifier is allowed
4)var args allowed i.e repalce string array String... args
5)final , synchronized , strinctfp allowed in main method
Difference between merge and include
Let’s say that you have a layout, call it main_layout, with a LinearLayout as its root view. You also have a layout, include_layout that you want to include in the main_layout. It also has a LinearLayout as its root view.
Now when you include it, there will be two LinearLayouts in the main-layout. The second LinearLayout doesn’t serve any purpose as the main_layout’s LinearLayout takes care of arranging the views. The extra LinearLayout only slows the app up and wastes scarce resources.
Using <merge> as the root view of your included file solves the problem.
Http and Https
Whether it’s HTTP or HTTPS both are protocol designed to transfer information between computers over WWW (World Wide Web). The main difference comes into play when “S” is attached with the “HTTP.” Simply, HTTP (Hyper Text Transfer Protocol), does the same thing as HTTPS like transferring information like document, file, image, video between computers over internet, but it is not in an encrypted format, due to this it becomes vulnerable to attacks happens over internet. Apart from this, let see some other differences.
Important point:
When activity contains fragment and when onback is pressed then ondestroy is not called only onstop of fragment and activity are called.
When er start app again onrestart of activity gets called and life cycle continues
onrestart of act-->onstart of act-->onstart of fragment-->onresume of act-->onresume of fragment...
Upcasting
Ex: class A{}
class B extend A{}
A a1 = new B();
this operation is a upcasting. and it happens automatically.no need to do anything explicitly.
We use when we do not know exact runtime of the object
Child specific methods cannot be called here we can call the methods defined/declared in A but during runtime it will call class B’s overridden methods.
if the method is not overridden in child’s class then only parent’s method which will be inherited to child will be called.
but same is not applicable to variables because variables decision happens at a compile time so always class A’s variables (not child’s inherited variables) will be accessed.
Downcasting : is not directly possible in Java.
ex:
Copy this code
Child c = new Parent();
for the above program will not work. it is compile time error.
Parent p = new Child();
Child c =(Child) p;
Accessing elements are faster with ArrayList, because it is index based. But accessing is difficult with LinkedList. It is slow access.
This is to access any element, you need to navigate through the elements one by one.
But insertion and deletion is much faster with LinkedList, because if you know the node,
just change the pointers before or after nodes. Insertion and deletion is slow with ArrayList,
this is because, during these operations ArrayList need to adjust the indexes according to deletion or insetion
if you are performing on middle indexes. Means, an ArrayList having 10 elements, if you are inserting at index 5,
then you need to shift the indexes above 5 to one more. -
Linked List
- Linked lists are used to implement queues, stacks, graphs, etc.
- In Linked Lists you don’t need to know the size in advance.
- Linked lists let you insert elements at the beginning and end of the list.
- To reach a particular node, you need to go through all those nodes that come before that node.
Node *head;
void InsertNodeAtFront(int data)
{
/* 1. create the new node*/
Node *temp = new Node;
temp->data = data;
/* 2. insert it at the first position*/
temp->next = head;
/* 3. update the head to point to this new node*/
head = temp;
}
To display Singly Linked List from First to Last,
- Create a linked list using create().
- You cannot change the address stored inside global variable “start” therefore you have to declare one temporary variable -“temp” of type node
- To traverse from start to end, you should allot address of Starting node in Pointer variable i.e temp.
1
2
3
|
struct node *temp; //Declare temp
temp = start; //Assign Starting Address to temp
|
If the temp is NULL then you can say that last node is reached.
Find Middle element in linked list
As if you think carefully you can solve this problem by using two pointers as mentioned in my last post on How to find length of Singly Linked List in Java. By using two pointers, incrementing one at each iteration and other at every second iteration. When first pointer will point at end of Linked List, second pointer will be pointing at middle node of Linked List.
Question 2: How to find if linked list has a loop ?
This question has bit of similarity with earlier algorithm and data structure interview question. I mean we can use two pointer approach to solve this problem. If we maintain two pointers, and we increment one pointer after processing two nodes and other after processing every node, we are likely to find a situation where both the pointers will be pointing to same node. This will only happen if linked list has loop.
This question has bit of similarity with earlier algorithm and data structure interview question. I mean we can use two pointer approach to solve this problem. If we maintain two pointers, and we increment one pointer after processing two nodes and other after processing every node, we are likely to find a situation where both the pointers will be pointing to same node. This will only happen if linked list has loop.
Question 3 : How to find 3rd element from end in a linked list in one pass?
This is another frequently asked linked list interview question. This question is exactly similar to finding middle element of linked list in single pass. If we apply same trick of maintaining two pointers and increment other pointer, when first has moved up to 3rd element, than when first pointer reaches to the end of linked list, second pointer will be pointing to the 3rd element from last in a linked list.
Read more: http://javarevisited.blogspot.com/2013/03/top-15-data-structures-algorithm-interview-questions-answers-java-programming.html#ixzz4m1ZyiBlH
What is fail -fast in java
A fail-fast system is nothing but immediately report any failure that is likely to lead to failure.
When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behavior with iterators.
Incase, you have called iterator on a collection object, and another thread tries to modify the collection object,
then concurrent modification exception will be thrown. This is called fail-fast.
Race Condition
A race condition is a situation in which two or more threads or processes are reading or writing some shared data,
and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and
subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread
tries to call a synchronized method on the same object, the second thread will block until the object is unlocked. -
Convert Map o list
public static void main(String a[]){ Map<String, String> wordMap = new HashMap<String, String>();
Set<Entry<String, String>> set = wordMap.entrySet();
List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(set); } -
Wrapper Classes
Everything in java is an object, except primitives. Primitives are int, short, long, boolean, etc.
Since they are not objects, they cannot return as objects, and collection of objects.
To support this, java provides wrapper classes to move primitives to objects.
Some of the wrapper classes are Integer, Long, Boolean, etc -
1) use == to compare primitive e.g. boolean, int, char etc, while use equals() to compare objects in Java.
2) == return true if two reference are of same object. Result of equals() method depends on overridden implementation.
3) For comparing String use equals() instead of == equality operator.
Android Application Architecture has the following components:
Services – like Network Operation
Intent - To perform inter-communication between activities or services
Resource Externalization - such as strings and graphics
Notification signaling users - light, sound, icon, notification, dialog etc.
Content Providers - They share data between applications
Imp point reg == and equals
== operator checks if two object refers to same memory location or not.
That is if two object refers to same memory location then == operator will evaluate to true. (Here you need to have clear idea about how String object are created, stored and assigned to variables...)
String args[] in java
In java when one supply parameter(s) from command line then this String[] args comes into play.
How many strings are created using "String s = new String("Radar");"
Considering only the given statement, i would say two objects are created.
"When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a new String instance on the heap and stores a reference to that object in the string constant pool."
So when the class containing this code is loaded, JVM finds the string literal "ABC", creates a string object and puts its reference into string constant pool. Now when the statement is executed, JVM is forced to create a new string object with contents "ABC" because of the new operator. This time no reference will be put into string constant pool because already there is reference for the same literal.
So two objects are created by the statement.
It holds the parameters passed from command line as an array of String objects.
String[ ] args parameter in java main()
In java when one supply parameter(s) from command line then this String[] args comes into play.
It holds the parameters passed from command line as an array of String objects.
Lets consider this example:
File: Example.java
class Example{
public static void main(String[] args){
for(int i=0; i<args.length; i++){
System.out.println(args[i])
}
}
}
Compile this program: javac Example.java
Run this program by passing command line argument: java Example 12 13 14
Then args will contain array of String as ["12","13","14"]
And when you loop through the args, the output will be:
12
13
14
Getting printed on new line because of ln in println where ln indicates new line.
Note:
args is not necessarily bound to be named so. What I mean to say is you can give it any name(eg, a or abc or xyz).
It could also be written as String... args
Difference : Iterator vs ListIterator
Iterator and ListIterator differ based on following parameters:
1. Traversal direction
Iterator allows to traverse the List, Set and Map in only forward direction. Iterator is unidirectional in nature.
ListIterator allows to traverse the List (remember only List) in both forward and backward direction. ListIterator is bidirectional.
2. Method
Iterator has next() method, using which forward traversal is possible.
ListIterator has next() method for forward traversal and previous() method for backward traversal.
3. Collection implementations that can be traversed
Iterator can traverse List, Set and Map.
ListIterator can only be used for List traversal.
4. Modifying the elements while traversing
Iterator can only remove the element during iteration. It has only remove() method.
ListIterator can add, remove and set elements during iteration.
5. Current position
Iterator cannot determine the current position of iteration during iterating over List.
ListIterator can determine the current position of iteration during iterating over List.
6. Retrieve index
Index of the element cannot be retrieved using Iterator.
Index of the element can be retrieved using ListIterator using previousIndex() and nextIndex() method.
7. Example
Click for iterator example
Click for ListIteratoriterator example
Java's platform independence explained
One of the most talked about point about java is it's platform independent nature.
Believe me this nature makes java really special as a programming language. So let's explore this platform independent term.
Platform independent means write once and run anywhere. It implies that it doesn't matter on what operating system(lets say,Windows OS) the code was written, it could be run on the other operating system(lets say Linux) conveniently and without any issue.
The only requirement is installation of JVM (Java Virtual Machine) in the system. JVM is the interpreter of the bytecode.
* JVM and bytecode's magic is the hand behind this platform independent concept of java.
How is this possible?
Whenever we write a program, say HelloWorld.java and compile it then a .class file is created with name HelloWorld.class.
This .class file contains bytecode instructions for JVM. Now you can run on the same system or you can happily port this bytecode on other operating system that has JVM and leave all your worries of completing your task of running the code on JVM.
Thus making java a portable in nature programming language.
Interesting!
Advantages of JVM
Portability - The bytecode could be ported to other system without any worry if JVM is present in the system.
Re-compilation not needed - bytecode doesn't need to be recompiled again in case the code is to be ported on to other operating system.
JVM uses JIT(just in time) compiler - Java uses a JIT compiler to compile Java bytecode to native machine code at runtime. The JIT compiler can do sophisticated optimizations for the specific CPU that the program is running on and it can use profiling information that wouldn't be available to an ahead-of-time compiler - in principle, a JIT compiler can therefore produce more optimal code than a "normal" compiler.
Now lets concentrate on security aspect of java. There are many security feature provided by the security manager present in JVM.
So as far as I have found out there are numerous angle which helps java to achieve security. I will explain all those aspects below:
1. At first security is provided by JVM(Java Virtual Machine) by checking the .class files for any malicious virus or threats that is presented to it before executing those files. So bytecode verification by JVM adds to security.
2. Memory security is provided by the Memory Management architecture of java. (Read more)
Here garbage collector starts its task of collecting the garbage objects as soon as it senses that out of memory condition is about to reach or even before it.
Programmer don't need to take any headache of releasing the memory space manually as is in other languages. Here JVM controls the garbage collector and it does this task for you. Manually programmer can also give instruction to garbage collector to run but then in that case also JVM has full decision control of whether to run it or not.(Read more)
Garbage collection is the part of effective memory management.
Java provides automatic garbage collection. Thus it frees the programmer from the headache of adding any memory management logic.
Before we proceed, can you tell me?
Where is the objects that you create gets stored?
Always remember, any object created in java gets its memory space in heap.
I guess, now you can think of where entire garbage collection process takes place. Definitely, its heap.
How garbage is collected in java?
Whenever there is any object that has no reference and is lying unreachable from the java program, it automatically qualifies for garbage collection.
When does garbage collector run?
Garbage collector is under the control of JVM. So it is upto JVM to decide when to run garbage collector. Whenever JVM gets the feeling that it is running out of the memory, it starts garbage collection to claim the space occupied by objects residing in heap without having any reference.
*Note : free() is used in C and delete() in C++ to collect garbage while java collects it automatically
Disadvantage of Java's Garbage collection process
The only downside of Garbage collector is that it can't be controlled completely by programmer. You may give instruction to run garbage collection process but its up to the JVM to start the process at its own whim.
Advantages of Java's Garbage collection process
Java provides better memory management due to automatic garbage collection technique.
It frees the programmer from taking pain to write the logic to collect garbage (but programmers can give instruction to JVM to run garbage collector, if they want).
Q. Which method is called before the garbage collection occurs?
finalize() method in java
As a java developer, you must be aware that it is garbage collector which is responsible to free the memory space ( heap) by collecting the garbage (object residing in memory having no reference, available object reference is set to null).
Now before collecting the garbage (object) wouldn't it be sweet and intelligent move of garbage collector to allow the object to perform any necessary task, which it may be required to do, before it is collected.
This is where finalize() method plays its role.
Before the object is about to get collected by garbage collector, collector provides last opportunity to object by calling finalize() to perform any clean up activity such as closing any open connection or releasing the System resource (if held) or other necessary task.
The finalize() method is defined in java.lang.Object class and thus is available to all classes for overriding purpose. Here is the general format of finalize() :
protected void finalize( ) {
//task to be performed before
//object is garbage collected goes here
}
You can override finalize( ) and provide your code inside it which needs to be executed before the object is garbage collected.
Who calls finalize() method?
It is responsibility of Garbage collector to call finalize() once for an object. Always remember, Garbage collector calls finalize() only once. And if object somehow escapes from being garbage collected then finalize() is not going to be called again.
You can explicitly call finalize() if you want.To do so you can call Runtime.getRuntime().runFinalization() OR Runtime.runFinalizersOnExit(true).
It may also happen in many case that finalize() would not get called at all.
Other Key Points :
1. The problem with finalize is that it is not guaranteed when it will be called by Garbage collector. It may also happen that it is not called. Even if it is called it is not guaranteed that object would get immediately collected.
So it is not recommended to put inside finalize() any critical code (for performing critical task). Because it is highly unreliable due to uncertainty of its execution behavior.
Difference:Collection vs Collections in java
Collection and Collections in java differs based on following parameters:
1. Basic
Collection is the base interface of java collection framework in java.util package.
Collections is a utility class in java.util package.
2. Purpose
Collection interface is the root of which interface like List, Set, Queue, etc form sub-interface.
Collections class consists of only static methods that can be used to perform operation on objects of type Collection.
For example,
· Collections.sort()
· Collections.binarySearch()
· Collections.synchronizedCollection()
Difference : ArrayList vs LinkedList
Array List and Linked List differ based on following parameters:
1. Insertion or Deletion of element
If there is need for insertion or deletion of an element from the List, then prefer Linked List as it provides faster insertion or deletion operation in comparison to Array List.
Reason:
Array List requires lots of index shifting to be done for any insertion or deletion operation to be performed as a result performance time increases. Take a glimpse of insertion(13 needs to be inserted at index 2) in diagram given below:
java radar: insertion in array list
Linked List does not require shifting of many nodes. It just effects three nodes. One which is to be inserted. And the other two are between which it needs to be inserted. Take a glimpse of insertion(node having element 2 needs to be inserted between 1 and 3) in diagram given below.
Java Radar : Insertion into Linked List
Since lots of element don't need to be shifted for performing insertion or deletion operation in case of Linked List (which is in case of Array List), so it performs faster insertion and deletion operation. An example for insertion in Linked List is given below.
Here is the detailed clear diagrammatic explanation of :
Array List insertion mechanism(click to learn)
Array List deletion mechanism(click to learn)
Linked List insertion mechanism(click to learn)
Linked List deletion mechanism(click to learn)
2. Searching element from List
If one needs to search element from the List then for better performance opt for Array List as it provides faster search operation in comparison to Linked List.
3. Memory consideration
Linked List consumes more memory space in comparison to Array List.
Reason :
Linked List has to maintain extra memory space for storing address data in both forward & backward pointer for each and every node apart from storing the element. Array List does not bother at all about storing any address detail so no extra memory requirement.
https://javaradar.blogspot.in/2017/03/difference-arraylist-vs-linkedlist.html
Difference : ArrayList vs HashSet
ArrayList and HashSet differs based on the following parameters:
1. Duplicate Object
ArrayList allows duplicate elements to be stored in it.
HashSet doesn’t allow duplicate element. All the element needs to be unique.
2. Order Maintenance
Being a List implementation, ArrayList maintains the insertion order.
In HashSet, insertion order is not maintained. (HashSet-> order not guaranteed, LinkedHashSet-> Order is maintained)
3. Null value
In ArrayList, one can store unlimited null values
In HashSet, only one null value is permitted.
4. Implementations
ArrayList class implements List interface.
HashSet implements Set interface.
5. Traversal
You can use both ListIterator and Iterator to traverse elements in ArrayList.
You cannot use ListIterator to iterate HashSet. To traverse HashSet use Iterator.
Java Difference : Iterator vs Enumeration
Iterator and Enumeration differ based on the following parameters:
1. Introduced
Enumeration was introduced as part of JDK1.0
Iterator was introduced from JDK1.2
2. Modifying Collection
Enumeration cannot be used to modify the elements in Collection while traversing.
Iterator can be used to remove the element in Collection while traversing (it can remove element using remove() )
3. Available methods
Enumeration: hasMoreElements(), nextElement()
Iterator: hasNext(), next(), remove()
4. Fail fast or Fail safe
Enumeration is fail safe by nature.
Iterator is fail fast by nature.
Note : Iterator being fail fast by nature is considered safe than enumeration as it throws ConcurrentModificationException, if any other thread tries to modify the Collection that is being traversed by Iterator.
5. Legacy concept
Enumeration is generally preferred for traversing over legacy classes like Vector, HashTable, etc.
Iterator is used to traverse over almost all classes in java Collection framework like ArrayList, LinkedList, HashMap, HashSet, etc.
Note: Iterator is preferred over Enumeration.
String is immutable in java
A very well known fact about java's String is that it is immutable. It means that once a String object is created it cannot be modified. Let's understand how?
For example,
String mobile = "Samsung";
Here we can see that a new String object with name Samsung is created and this object is referenced by variable named mobile.
And this object would be stored in a constant String pool.
Now change the above example as shown below,
String mobile = "Samsung Duos";
Again a new object is created with name Samsung Duos and is stored in the pool. And mobile variable now has reference to Samsung Duos instead of Samsung. But Samsung object still remains in the pool but with no reference.
Note : We have both Samsung and Samsung Duos object in the pool.
-------------------------------------------------------------------------------------------------------------------------
Suppose you again write, say
String company = "Samsung"; &&
String handset = "Samsung Duos";
This time as the Samsung and Samsung Duos object already exist in the pool so the same object would be used instead of creating new object. company would have reference to Samsung object and Samsung Duos to handset respectively.
Note : Samsung Duos object is now referred by both mobile and handset variable.
--------------------------------------------------------------------------------------------------------------------------
Think you have got the concept. Then have a look at the below given scenario :
String s1 = "Sita";
s1 += "Ram";
System.out.println(s1);
The above code works. So can you make out what's happening here?
At the beginning s1 = "Sita" and in the second line s1 = "SitaRam". So, Is the original String modified? Is the immutability rule violated?
And the answer is simply no. Remember what I said in the beginning. Same applies here as well. When you write
s1 = "Sita", a new object Sita is getting created and stored in the constant String pool. And your s1 refers to this String object.
When you concat Sita with Ram (s1 += "Ram";) at the same time a new String object is created and your variable s1 now refers to this object.
So overall concept is the string object is not getting modified rather when concatenation occurs a new object is created and the old reference changes to new one. Thus String object remains immutable throughout the journey after creation.
Advantages of String's immutability :
Existing object in the heap is referred by number of variables thus saving lot of memory space and relieving java from the task of creating new object again and again if it already exists in constant memory pool ( clearly explained above).
Due to immutable nature, the hash code of the String doesn't change and thus can be cached easily.
Due to immutable nature String objects are naturally thread safe.
ince String is immutable object in java, i.e it can't be changed so if we want to operate on string for example perform concatenate operation there must be someone to help. And the helper should be mutable (object value can be changed repeatedly). The rescuer provided by Java are StringBuffer and StringBuilder. So if both are mutable and perform same task then what is the difference between them. Let's find out.
StringBuffer() - If thread safety is your concern then use StringBuffer() method because each method in it is synchronized. And due to the synchronization effect, it doesn't allow two threads to access same method simultaneously. Only one thread can access a method at a time.
But this thread safety in StringBuffer comes at the cost of performance making it slower in terms of performing operation as compared to StringBuilder.
StringBuilder() - If you need faster operation and are least bothered about thread safety then use StringBuilder. It's obvious to be fast because it is not concerned about additional task of performing thread safety.
* Both store the created object in heap.
http://www.thejavageek.com/2013/06/19/the-string-constant-pool/
https://www.javatpoint.com/java-string-intern
Encapsulation binds together the data and functions that manipulate the data, keeping it safe from interference and misuse.
Real World Example: Every time you log into your email account( GMail, Yahoo, Hotmail or official mail), you have a whole lot of processes taking place in the backend, that you have no control over. So your password, would probably be retrieved in an encyrpted form, verified and only then you are given access. You do not have any control, over how the password is verified, and this keeps it safe from misuse.
Abstraction is a process of hiding the implementation from the user, only the functionality is exposed here. So you are aware only of what the application does, not how it does it.
Real World Example: When you log into your email, compose and send a mail. Again there is a whole lot of background processing involved, verifying the recipient, sending request to the email server, sending your email. Here you are only interested in composing and clicking on the send button. What really happens when you click on the send button, is hidden from you.
Throw and Throws
Throw to throw an excepion , can throw only one exception at a time
Throws --- Declaring exception (can declare more than one exception by seperating with comma)
Life Cycle of thread
Thread
newly created thread
start thread
runnable
running
dead
blocked
Difference b/w wait and sleep
sleep(): It is a static method on Thread class.
It makes the current thread into the "Not Runnable" state for specified amount of time.
During this time, the thread keeps the lock (monitors) it has acquired.
wait(): It is a method on Object class. It makes the current thread into the "Not Runnable" state.
Wait is called on a object, not a thread. Before calling wait() method, the object should be synchronized, means the object should be inside synchronized block.
The call to wait() releases the acquired lock. - See more at: http://www.java2novice.com/java_interview_questions/wait-sleep-difference/#sthash.ZZpQO9YM.dpuf
Factory Method Pattern
A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.
The Factory Method Pattern is also known as Virtual Constructor.
Advantage of Factory Design Pattern
Factory Method Pattern allows the sub-classes to choose the type of objects to create.
It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class.
Usage of Factory Design Pattern
When a class doesn't know what sub-classes will be required to create
When a class wants that its sub-classes specify the objects to be created.
When the parent classes choose the creation of objects to its sub-classes.
Parcelable and Serialization are used for marshaling and unmarshaling Java objects.
Differences between the two are often cited around implementation techniques and performance results.
Parcelable is well documented in the Android SDK; serialization on the other hand is available in Java.
It is for this very reason that Android developers prefer Parcelable over the Serialization technique.
· In Parcelable, developers write custom code for marshaling and unmarshaling so it creates less garbage objects in
comparison to Serialization. The performance of Parcelable over Serialization dramatically improves (around two times faster),
because of this custom implementation.
· Serialization is a marker interface, which implies the user cannot marshal the data according to their requirements.
In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API.
This helps identify the Java objects member and behavior, but also ends up creating a lot of garbage objects.
Due to this, the Serialization process is slow in comparison to Parcelable
Activity Life Cycle
When Activiy A starts
oncreate
onstart
onresume
when we call act b then
onpause of A Activity
Oncreate of B Activity
onstart of B Activity
onresume of B activity
onsaveins of A Activity
onStop of Activity A
onback of activity B then
onPause of Act B
on start , on resume of act A
onStop of Activity B
RDB
A relational database (RDB) is a collective set of multiple data sets organized by tables, records and columns.
RDBs establish a well-defined relationship between database tables. Tables communicate and share information, which facilitates data searchability,
organization and reporting.
RDBs use Structured Query Language (SQL), which is a standard user application that provides an easy programming interface for database interaction.
Raw Query and Query difference
rawQuery() directly accepts an SQL select statement as input.
We write query like select from table name where column = etc tc
query() provides a structured interface for specifying the SQL query.
we pass table name , column as a parameter
2.4. rawQuery() Example
The following gives an example of a rawQuery() call.
Cursor cursor = getReadableDatabase().
rawQuery("select * from todo where _id = ?", new String[] { id });
2.5. query() Example
The following gives an example of a query() call.
return database.query(DATABASE_TABLE,
new String[] { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION },
null, null, null, null, null);
Cursor Loader
The Cursor Loader class allows for the querying and filling of a Cursor do be done in a background thread.
This frees up the UI thread to handle user interactions.
Authority in Content Provider
The Authority is used to interact with a particular content provider, that means it must be unique. That's why is a good practice to declare it as your domain name (in reverse) plus the name of the package containing the provider, that way is less likely that other developer creates an app with a content provider declaring the same authority.
You declare it in the manifest so your app and other apps (if you let them) can manipulate data through your content provider in the form of a uri:
Enumerator and iterator difference
Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.
Also Iterator is more secure and safe as compared to Enumeration because it does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.
In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:
Interface Imp Point
If Same method is defined in two interfaces can we override this method in class implementing these interfaces.
•Yes implementing the method once is enough in class.
•A class cannot implement two interfaces that have methods with same name but different return type.
This is another frequently asked linked list interview question. This question is exactly similar to finding middle element of linked list in single pass. If we apply same trick of maintaining two pointers and increment other pointer, when first has moved up to 3rd element, than when first pointer reaches to the end of linked list, second pointer will be pointing to the 3rd element from last in a linked list.
Read more: http://javarevisited.blogspot.com/2013/03/top-15-data-structures-algorithm-interview-questions-answers-java-programming.html#ixzz4m1ZyiBlH
What is fail -fast in java
A fail-fast system is nothing but immediately report any failure that is likely to lead to failure.
When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behavior with iterators.
Incase, you have called iterator on a collection object, and another thread tries to modify the collection object,
then concurrent modification exception will be thrown. This is called fail-fast.
Race Condition
A race condition is a situation in which two or more threads or processes are reading or writing some shared data,
and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and
subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread
tries to call a synchronized method on the same object, the second thread will block until the object is unlocked. -
Convert Map o list
public static void main(String a[]){ Map<String, String> wordMap = new HashMap<String, String>();
Set<Entry<String, String>> set = wordMap.entrySet();
List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(set); } -
Wrapper Classes
Everything in java is an object, except primitives. Primitives are int, short, long, boolean, etc.
Since they are not objects, they cannot return as objects, and collection of objects.
To support this, java provides wrapper classes to move primitives to objects.
Some of the wrapper classes are Integer, Long, Boolean, etc -
1) use == to compare primitive e.g. boolean, int, char etc, while use equals() to compare objects in Java.
2) == return true if two reference are of same object. Result of equals() method depends on overridden implementation.
3) For comparing String use equals() instead of == equality operator.
Android Application Architecture has the following components:
Services – like Network Operation
Intent - To perform inter-communication between activities or services
Resource Externalization - such as strings and graphics
Notification signaling users - light, sound, icon, notification, dialog etc.
Content Providers - They share data between applications
Imp point reg == and equals
== operator checks if two object refers to same memory location or not.
That is if two object refers to same memory location then == operator will evaluate to true. (Here you need to have clear idea about how String object are created, stored and assigned to variables...)
String args[] in java
In java when one supply parameter(s) from command line then this String[] args comes into play.
How many strings are created using "String s = new String("Radar");"
Considering only the given statement, i would say two objects are created.
"When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a new String instance on the heap and stores a reference to that object in the string constant pool."
So when the class containing this code is loaded, JVM finds the string literal "ABC", creates a string object and puts its reference into string constant pool. Now when the statement is executed, JVM is forced to create a new string object with contents "ABC" because of the new operator. This time no reference will be put into string constant pool because already there is reference for the same literal.
So two objects are created by the statement.
It holds the parameters passed from command line as an array of String objects.
In java when one supply parameter(s) from command line then this String[] args comes into play.
It holds the parameters passed from command line as an array of String objects.
Lets consider this example:
File: Example.java
class Example{
public static void main(String[] args){
for(int i=0; i<args.length; i++){
System.out.println(args[i])
}
}
}
Compile this program: javac Example.java
Run this program by passing command line argument: java Example 12 13 14
Then args will contain array of String as ["12","13","14"]
And when you loop through the args, the output will be:
12
13
14
Getting printed on new line because of ln in println where ln indicates new line.
Note:
args is not necessarily bound to be named so. What I mean to say is you can give it any name(eg, a or abc or xyz).
It could also be written as String... args
Difference : Iterator vs ListIterator
Iterator and ListIterator differ based on following parameters:
1. Traversal direction
Iterator allows to traverse the List, Set and Map in only forward direction. Iterator is unidirectional in nature.
ListIterator allows to traverse the List (remember only List) in both forward and backward direction. ListIterator is bidirectional.
2. Method
Iterator has next() method, using which forward traversal is possible.
ListIterator has next() method for forward traversal and previous() method for backward traversal.
3. Collection implementations that can be traversed
Iterator can traverse List, Set and Map.
ListIterator can only be used for List traversal.
4. Modifying the elements while traversing
Iterator can only remove the element during iteration. It has only remove() method.
ListIterator can add, remove and set elements during iteration.
5. Current position
Iterator cannot determine the current position of iteration during iterating over List.
ListIterator can determine the current position of iteration during iterating over List.
6. Retrieve index
Index of the element cannot be retrieved using Iterator.
Index of the element can be retrieved using ListIterator using previousIndex() and nextIndex() method.
7. Example
Click for iterator example
Click for ListIteratoriterator example
Java's platform independence explained
One of the most talked about point about java is it's platform independent nature.
Believe me this nature makes java really special as a programming language. So let's explore this platform independent term.
Platform independent means write once and run anywhere. It implies that it doesn't matter on what operating system(lets say,Windows OS) the code was written, it could be run on the other operating system(lets say Linux) conveniently and without any issue.
The only requirement is installation of JVM (Java Virtual Machine) in the system. JVM is the interpreter of the bytecode.
* JVM and bytecode's magic is the hand behind this platform independent concept of java.
How is this possible?
Whenever we write a program, say HelloWorld.java and compile it then a .class file is created with name HelloWorld.class.
This .class file contains bytecode instructions for JVM. Now you can run on the same system or you can happily port this bytecode on other operating system that has JVM and leave all your worries of completing your task of running the code on JVM.
Thus making java a portable in nature programming language.
Interesting!
Advantages of JVM
Portability - The bytecode could be ported to other system without any worry if JVM is present in the system.
Re-compilation not needed - bytecode doesn't need to be recompiled again in case the code is to be ported on to other operating system.
JVM uses JIT(just in time) compiler - Java uses a JIT compiler to compile Java bytecode to native machine code at runtime. The JIT compiler can do sophisticated optimizations for the specific CPU that the program is running on and it can use profiling information that wouldn't be available to an ahead-of-time compiler - in principle, a JIT compiler can therefore produce more optimal code than a "normal" compiler.
Now lets concentrate on security aspect of java. There are many security feature provided by the security manager present in JVM.
So as far as I have found out there are numerous angle which helps java to achieve security. I will explain all those aspects below:
1. At first security is provided by JVM(Java Virtual Machine) by checking the .class files for any malicious virus or threats that is presented to it before executing those files. So bytecode verification by JVM adds to security.
2. Memory security is provided by the Memory Management architecture of java. (Read more)
Here garbage collector starts its task of collecting the garbage objects as soon as it senses that out of memory condition is about to reach or even before it.
Programmer don't need to take any headache of releasing the memory space manually as is in other languages. Here JVM controls the garbage collector and it does this task for you. Manually programmer can also give instruction to garbage collector to run but then in that case also JVM has full decision control of whether to run it or not.(Read more)
Garbage collection is the part of effective memory management.
Java provides automatic garbage collection. Thus it frees the programmer from the headache of adding any memory management logic.
Before we proceed, can you tell me?
Where is the objects that you create gets stored?
Always remember, any object created in java gets its memory space in heap.
I guess, now you can think of where entire garbage collection process takes place. Definitely, its heap.
How garbage is collected in java?
Whenever there is any object that has no reference and is lying unreachable from the java program, it automatically qualifies for garbage collection.
When does garbage collector run?
Garbage collector is under the control of JVM. So it is upto JVM to decide when to run garbage collector. Whenever JVM gets the feeling that it is running out of the memory, it starts garbage collection to claim the space occupied by objects residing in heap without having any reference.
*Note : free() is used in C and delete() in C++ to collect garbage while java collects it automatically
Disadvantage of Java's Garbage collection process
The only downside of Garbage collector is that it can't be controlled completely by programmer. You may give instruction to run garbage collection process but its up to the JVM to start the process at its own whim.
Advantages of Java's Garbage collection process
Java provides better memory management due to automatic garbage collection technique.
It frees the programmer from taking pain to write the logic to collect garbage (but programmers can give instruction to JVM to run garbage collector, if they want).
Q. Which method is called before the garbage collection occurs?
finalize() method in java
As a java developer, you must be aware that it is garbage collector which is responsible to free the memory space ( heap) by collecting the garbage (object residing in memory having no reference, available object reference is set to null).
Now before collecting the garbage (object) wouldn't it be sweet and intelligent move of garbage collector to allow the object to perform any necessary task, which it may be required to do, before it is collected.
This is where finalize() method plays its role.
Before the object is about to get collected by garbage collector, collector provides last opportunity to object by calling finalize() to perform any clean up activity such as closing any open connection or releasing the System resource (if held) or other necessary task.
The finalize() method is defined in java.lang.Object class and thus is available to all classes for overriding purpose. Here is the general format of finalize() :
protected void finalize( ) {
//task to be performed before
//object is garbage collected goes here
}
You can override finalize( ) and provide your code inside it which needs to be executed before the object is garbage collected.
Who calls finalize() method?
It is responsibility of Garbage collector to call finalize() once for an object. Always remember, Garbage collector calls finalize() only once. And if object somehow escapes from being garbage collected then finalize() is not going to be called again.
You can explicitly call finalize() if you want.To do so you can call Runtime.getRuntime().runFinalization() OR Runtime.runFinalizersOnExit(true).
It may also happen in many case that finalize() would not get called at all.
Other Key Points :
1. The problem with finalize is that it is not guaranteed when it will be called by Garbage collector. It may also happen that it is not called. Even if it is called it is not guaranteed that object would get immediately collected.
So it is not recommended to put inside finalize() any critical code (for performing critical task). Because it is highly unreliable due to uncertainty of its execution behavior.
Difference:Collection vs Collections in java
Collection and Collections in java differs based on following parameters:
1. Basic
Collection is the base interface of java collection framework in java.util package.
Collections is a utility class in java.util package.
2. Purpose
Collection interface is the root of which interface like List, Set, Queue, etc form sub-interface.
Collections class consists of only static methods that can be used to perform operation on objects of type Collection.
For example,
· Collections.sort()
· Collections.binarySearch()
· Collections.synchronizedCollection()
Difference : ArrayList vs LinkedList
Array List and Linked List differ based on following parameters:
1. Insertion or Deletion of element
If there is need for insertion or deletion of an element from the List, then prefer Linked List as it provides faster insertion or deletion operation in comparison to Array List.
Reason:
Array List requires lots of index shifting to be done for any insertion or deletion operation to be performed as a result performance time increases. Take a glimpse of insertion(13 needs to be inserted at index 2) in diagram given below:
java radar: insertion in array list
Linked List does not require shifting of many nodes. It just effects three nodes. One which is to be inserted. And the other two are between which it needs to be inserted. Take a glimpse of insertion(node having element 2 needs to be inserted between 1 and 3) in diagram given below.
Java Radar : Insertion into Linked List
Since lots of element don't need to be shifted for performing insertion or deletion operation in case of Linked List (which is in case of Array List), so it performs faster insertion and deletion operation. An example for insertion in Linked List is given below.
Here is the detailed clear diagrammatic explanation of :
Array List insertion mechanism(click to learn)
Array List deletion mechanism(click to learn)
Linked List insertion mechanism(click to learn)
Linked List deletion mechanism(click to learn)
2. Searching element from List
If one needs to search element from the List then for better performance opt for Array List as it provides faster search operation in comparison to Linked List.
3. Memory consideration
Linked List consumes more memory space in comparison to Array List.
Reason :
Linked List has to maintain extra memory space for storing address data in both forward & backward pointer for each and every node apart from storing the element. Array List does not bother at all about storing any address detail so no extra memory requirement.
https://javaradar.blogspot.in/2017/03/difference-arraylist-vs-linkedlist.html
Difference : ArrayList vs HashSet
ArrayList and HashSet differs based on the following parameters:
1. Duplicate Object
ArrayList allows duplicate elements to be stored in it.
HashSet doesn’t allow duplicate element. All the element needs to be unique.
2. Order Maintenance
Being a List implementation, ArrayList maintains the insertion order.
In HashSet, insertion order is not maintained. (HashSet-> order not guaranteed, LinkedHashSet-> Order is maintained)
3. Null value
In ArrayList, one can store unlimited null values
In HashSet, only one null value is permitted.
4. Implementations
ArrayList class implements List interface.
HashSet implements Set interface.
5. Traversal
You can use both ListIterator and Iterator to traverse elements in ArrayList.
You cannot use ListIterator to iterate HashSet. To traverse HashSet use Iterator.
Java Difference : Iterator vs Enumeration
Iterator and Enumeration differ based on the following parameters:
1. Introduced
Enumeration was introduced as part of JDK1.0
Iterator was introduced from JDK1.2
2. Modifying Collection
Enumeration cannot be used to modify the elements in Collection while traversing.
Iterator can be used to remove the element in Collection while traversing (it can remove element using remove() )
3. Available methods
Enumeration: hasMoreElements(), nextElement()
Iterator: hasNext(), next(), remove()
4. Fail fast or Fail safe
Enumeration is fail safe by nature.
Iterator is fail fast by nature.
Note : Iterator being fail fast by nature is considered safe than enumeration as it throws ConcurrentModificationException, if any other thread tries to modify the Collection that is being traversed by Iterator.
5. Legacy concept
Enumeration is generally preferred for traversing over legacy classes like Vector, HashTable, etc.
Iterator is used to traverse over almost all classes in java Collection framework like ArrayList, LinkedList, HashMap, HashSet, etc.
Note: Iterator is preferred over Enumeration.
String is immutable in java
A very well known fact about java's String is that it is immutable. It means that once a String object is created it cannot be modified. Let's understand how?
For example,
String mobile = "Samsung";
Here we can see that a new String object with name Samsung is created and this object is referenced by variable named mobile.
And this object would be stored in a constant String pool.
Now change the above example as shown below,
String mobile = "Samsung Duos";
Again a new object is created with name Samsung Duos and is stored in the pool. And mobile variable now has reference to Samsung Duos instead of Samsung. But Samsung object still remains in the pool but with no reference.
Note : We have both Samsung and Samsung Duos object in the pool.
-------------------------------------------------------------------------------------------------------------------------
Suppose you again write, say
String company = "Samsung"; &&
String handset = "Samsung Duos";
This time as the Samsung and Samsung Duos object already exist in the pool so the same object would be used instead of creating new object. company would have reference to Samsung object and Samsung Duos to handset respectively.
Note : Samsung Duos object is now referred by both mobile and handset variable.
--------------------------------------------------------------------------------------------------------------------------
Think you have got the concept. Then have a look at the below given scenario :
String s1 = "Sita";
s1 += "Ram";
System.out.println(s1);
The above code works. So can you make out what's happening here?
At the beginning s1 = "Sita" and in the second line s1 = "SitaRam". So, Is the original String modified? Is the immutability rule violated?
And the answer is simply no. Remember what I said in the beginning. Same applies here as well. When you write
s1 = "Sita", a new object Sita is getting created and stored in the constant String pool. And your s1 refers to this String object.
When you concat Sita with Ram (s1 += "Ram";) at the same time a new String object is created and your variable s1 now refers to this object.
So overall concept is the string object is not getting modified rather when concatenation occurs a new object is created and the old reference changes to new one. Thus String object remains immutable throughout the journey after creation.
Advantages of String's immutability :
Existing object in the heap is referred by number of variables thus saving lot of memory space and relieving java from the task of creating new object again and again if it already exists in constant memory pool ( clearly explained above).
Due to immutable nature, the hash code of the String doesn't change and thus can be cached easily.
Due to immutable nature String objects are naturally thread safe.
ince String is immutable object in java, i.e it can't be changed so if we want to operate on string for example perform concatenate operation there must be someone to help. And the helper should be mutable (object value can be changed repeatedly). The rescuer provided by Java are StringBuffer and StringBuilder. So if both are mutable and perform same task then what is the difference between them. Let's find out.
StringBuffer() - If thread safety is your concern then use StringBuffer() method because each method in it is synchronized. And due to the synchronization effect, it doesn't allow two threads to access same method simultaneously. Only one thread can access a method at a time.
But this thread safety in StringBuffer comes at the cost of performance making it slower in terms of performing operation as compared to StringBuilder.
StringBuilder() - If you need faster operation and are least bothered about thread safety then use StringBuilder. It's obvious to be fast because it is not concerned about additional task of performing thread safety.
* Both store the created object in heap.
http://www.thejavageek.com/2013/06/19/the-string-constant-pool/
https://www.javatpoint.com/java-string-intern
Encapsulation binds together the data and functions that manipulate the data, keeping it safe from interference and misuse.
Real World Example: Every time you log into your email account( GMail, Yahoo, Hotmail or official mail), you have a whole lot of processes taking place in the backend, that you have no control over. So your password, would probably be retrieved in an encyrpted form, verified and only then you are given access. You do not have any control, over how the password is verified, and this keeps it safe from misuse.
Abstraction is a process of hiding the implementation from the user, only the functionality is exposed here. So you are aware only of what the application does, not how it does it.
Real World Example: When you log into your email, compose and send a mail. Again there is a whole lot of background processing involved, verifying the recipient, sending request to the email server, sending your email. Here you are only interested in composing and clicking on the send button. What really happens when you click on the send button, is hidden from you.
Throw and Throws
Throw to throw an excepion , can throw only one exception at a time
Throws --- Declaring exception (can declare more than one exception by seperating with comma)
Life Cycle of thread
Thread
newly created thread
start thread
runnable
running
dead
blocked
Difference b/w wait and sleep
sleep(): It is a static method on Thread class.
It makes the current thread into the "Not Runnable" state for specified amount of time.
During this time, the thread keeps the lock (monitors) it has acquired.
wait(): It is a method on Object class. It makes the current thread into the "Not Runnable" state.
Wait is called on a object, not a thread. Before calling wait() method, the object should be synchronized, means the object should be inside synchronized block.
The call to wait() releases the acquired lock. - See more at: http://www.java2novice.com/java_interview_questions/wait-sleep-difference/#sthash.ZZpQO9YM.dpuf
Factory Method Pattern
A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.
The Factory Method Pattern is also known as Virtual Constructor.
Advantage of Factory Design Pattern
Factory Method Pattern allows the sub-classes to choose the type of objects to create.
It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class.
Usage of Factory Design Pattern
When a class doesn't know what sub-classes will be required to create
When a class wants that its sub-classes specify the objects to be created.
When the parent classes choose the creation of objects to its sub-classes.
Parcelable and Serialization are used for marshaling and unmarshaling Java objects.
Differences between the two are often cited around implementation techniques and performance results.
Parcelable is well documented in the Android SDK; serialization on the other hand is available in Java.
It is for this very reason that Android developers prefer Parcelable over the Serialization technique.
· In Parcelable, developers write custom code for marshaling and unmarshaling so it creates less garbage objects in
comparison to Serialization. The performance of Parcelable over Serialization dramatically improves (around two times faster),
because of this custom implementation.
· Serialization is a marker interface, which implies the user cannot marshal the data according to their requirements.
In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API.
This helps identify the Java objects member and behavior, but also ends up creating a lot of garbage objects.
Due to this, the Serialization process is slow in comparison to Parcelable
Activity Life Cycle
When Activiy A startsoncreate
onstart
onresume
when we call act b then
onpause of A Activity
Oncreate of B Activity
onstart of B Activity
onresume of B activity
onsaveins of A Activity
onStop of Activity A
onback of activity B then
onPause of Act B
on start , on resume of act A
onStop of Activity B
RDB
A relational database (RDB) is a collective set of multiple data sets organized by tables, records and columns.
RDBs establish a well-defined relationship between database tables. Tables communicate and share information, which facilitates data searchability,
organization and reporting.
RDBs use Structured Query Language (SQL), which is a standard user application that provides an easy programming interface for database interaction.
Raw Query and Query difference
rawQuery() directly accepts an SQL select statement as input.
We write query like select from table name where column = etc tc
query() provides a structured interface for specifying the SQL query.
we pass table name , column as a parameter
2.4. rawQuery() Example
The following gives an example of a rawQuery() call.
Cursor cursor = getReadableDatabase().
rawQuery("select * from todo where _id = ?", new String[] { id });
2.5. query() Example
The following gives an example of a query() call.
return database.query(DATABASE_TABLE,
new String[] { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION },
null, null, null, null, null);
Cursor Loader
The Cursor Loader class allows for the querying and filling of a Cursor do be done in a background thread.
This frees up the UI thread to handle user interactions.
Authority in Content Provider
The Authority is used to interact with a particular content provider, that means it must be unique. That's why is a good practice to declare it as your domain name (in reverse) plus the name of the package containing the provider, that way is less likely that other developer creates an app with a content provider declaring the same authority.
You declare it in the manifest so your app and other apps (if you let them) can manipulate data through your content provider in the form of a uri:
Enumerator and iterator difference
Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.
Also Iterator is more secure and safe as compared to Enumeration because it does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.
In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:
Interface Imp Point
If Same method is defined in two interfaces can we override this method in class implementing these interfaces.
•Yes implementing the method once is enough in class.
•A class cannot implement two interfaces that have methods with same name but different return type.
Two methods of passing object by Intent (Serializable,Parcelable)
https://www.javacodegeeks.com/2014/01/android-tutorial-two-methods-of-passing-object-by-intent-serializableparcelable.html
Transient variables value will not be saved to file and hence cannot be retrieved in the new object. Similarly static variable values are also not serialized since they belongs to class and not object.
A Service helps you to execute tasks in the background. Like downloading a file or tracking user location changes.
It is an Application Componenet with no user interface. It has a simple life cycle and comes with a set of features.
There are two types of Services
Bound Service This kind of service is bound to a component like an Activity and runs as long as the Activity runs.
Started Service This kind of service can run indefinitely. Even when the Activity that started is is destroyed.
You can create a new service by extending either the Service Class or the IntentService Class.
IntentService allows you to create a started service.
One of the major changes in Android Marshmallow is the new permission system. In earlier versions we were declaring the permission in the AndroidManifest.xml file. But with Android Marshmallow we need to ask the permission at run time. In this post I will show you a simple Android Marshmallow Permissions Example. So lets begin.
Material Design, its a comprehensive guide of UI Widgets introduced since Android 5.0 and it improves the visual appeal of the apps.
Android’s latest release, Lollipop (Android 5.0 API Level 21) includes the new RecyclerView and CardView widgets. They’re also made available for use on devices running API Level 7 and above through the Support Libraries.
The RecyclerView provides a more advanced and flexible way of displaying lists than the old ListView.
The CardView widget enables you to display views inside a card. You can design the card so that its look is consistent across your app.
Displaying Lists
The RecyclerView widget is essentially a container that you can use to display large sets of data. It’s very efficient as it only displays a few items at a time. Views that are no longer needed are recycled and reused. Not having to keep on inflating views saves CPU resources and valuable memory is saved by not having to keep views alive in the background.Android RecyclerView is a more advanced, powerful and flexible version of the ListView. RecyclerView is similar to ListView when it comes to implementation except the fact that it forces us to use a RecyclerView.ViewHolder class to hold the elements which was not a compulsion in ListView.
As the name suggests, a RecyclerView is used to reuse cells when scrolling up and down by recycling the items in the list. Another improvement in RecyclerView is that it allows us to set the LayoutManagers dynamically at runtime unlike the ListView which was only available in a Vertical scrolling List. RecyclerView allows us to set the following types of Layouts at runtime.
- LinearLayoutManager : it supports both vertical and horizontal lists
- StaggeredLayoutManager : it supports staggered lists
- GridLayoutManager : it supports displaying grids as seen in GalleryView earlier
The RecyclerView.ItemAnimator class provides better support to animating the views unlike the ListViews
The RecyclerView.ItemDecorator class provides better support when it comes to adding borders and dividers thereby giving huge control to us
Hence a RecyclerView is more customisable when compared to ListView and gives greater control to the users.
The RecyclerView is available in the support library. So we need to modify our gradle script to add the following dependency.
The RecyclerView is available in the support library. So we need to modify our gradle script to add the following dependency.
1
2
3
| dependencies { compile 'com.android.support:recyclerview-v7:21.0.0-rc1' }
CardView widget allows us to control the background color, shadow, corner radius, elevation etc. For using the custom attributes in XML, we need to add the following namespace declaration to the parent layout. |
- card_view:cardCornerRadius : Used to set the corner radius in our layouts
- card_view:cardBackgroundColor : Used to set the background color of the view
Advatages of string being immutable
Security and String pool being primary reason of making String immutableNested layout /Direct hierarchy which to prefer
The benefits, as small as they might seem, are multiplied several times because this layout is used for every item in a list.Most of the difference is due to the use of layout_weight in the LinearLayout design, which can slow down the speed of measurement. It is just one example of how each layout has appropriate uses and you should carefully consider whether using layout weight is necessary.
In some complex layouts, the system may waste effort measuring the same UI element more than once. This phenomenon is called double taxation. For more information about double taxation and how to prevent it, see Performance and View Hierarchies.
ConstraintLayout allows you to build complex layouts without having to nest View and ViewGroup elements.
By using ConstraintLayout instead, you can achieve the same effect just by adding a constraint from the baseline of the TextView to the baseline of the EditText without creating another ViewGroup:
Android oreo features
PIPImprovement in notifications(like dots... , categorize , snoozing , settimeout after which you can cancel,messaging styles, background color etc)
AutoFill Framework
Connectivity
Wi-Fi Aware
Android 8.0 (API level 26) adds support for Wi-Fi Aware, which is based on the Neighbor Awareness Networking (NAN) specification. On devices with the appropriate Wi-Fi Aware hardware, apps and nearby devices can discover and communicate over Wi-Fi without an Internet access point.
Sharing
SmartSharing
Android 8.0 (API level 26) learns about users' personalized sharing preferences and better understands for each type of content which are the right apps to share with. For example, if a user takes a photo of a receipt, Android 8.0 can suggest an expense-tracking app; if the user takes a selfie, a social media app can better handle the image. Android 8.0 automatically learns all these patterns according to users' personalized preferences.
Security & Privacy
Permissions
Android 8.0 (API level 26) introduces several new permissions related to telephony:
The ANSWER_PHONE_CALLS permission allows your app to answer incoming phone calls programmatically. To handle an incoming phone call in your app, you can use the acceptRingingCall() method.
The READ_PHONE_NUMBERS permission grants your app read access to the phone numbers stored in a device.
These permission are both classified as dangerous and are both part of the PHONE permission group.
Behavioural
The startService() method now throws an IllegalStateException if an app targeting Android 8.0 tries to use that method in a situation when it isn't permitted to create background services.
The Keystore itself is encrypted using the user’s own lockscreen pin/password, hence, when the device screen is locked the Keystore is unavailable. Keep this in mind if you have a background service that could need to access your application secrets.
Internal storage.
External storage.
Content providers
By default, files that you create on internal storage are accessible only to your app. Android implements this protection, and it's sufficient for most applications.
Files created on external storage, such as SD cards, are globally readable and writable. Because external storage can be removed by the user and also modified by any application, don't store sensitive information using external storage.
Using content providers
Content providers offer a structured storage mechanism that can be limited to your own application or exported to allow access by other applications. If you do not intend to provide other applications with access to your ContentProvider, mark them as android:exported=false in the application manifest. Otherwise, set the android:exported attribute to true to allow other apps to access the stored data.
When creating a ContentProvider that is exported for use by other applications, you can specify a single permission for reading and writing, or you can specify distinct permissions for reading and writing. You should limit your permissions to those required to accomplish the task at hand. Keep in mind that it’s usually easier to add permissions later to expose new functionality than it is to take them away and impact existing users.
If you are using a content provider for sharing data between only your own apps, it is preferable to use the android:protectionLevel attribute set to signature protection. Signature permissions do not require user confirmation, so they provide a better user experience and more controlled access to the content provider data when the apps accessing the data are signed with the same key.
Content providers can also provide more granular access by declaring the android:grantUriPermissions attribute and using the FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION flags in the Intent object that activates the component. The scope of these permissions can be further limited by the <grant-uri-permission> element.
When accessing a content provider, use parameterized query methods such as query(), update(), and delete() to avoid potential SQL injection from untrusted sources. Note that using parameterized methods is not sufficient if the selection argument is built by concatenating user data prior to submitting it to the method.
Service Important things android
Android – How to bind service from another application?
1)Declare intent filter in service tag in manifest and export the service by using export attribute
2)Declare a service class which extends android Service Class and use handler and a messanger
Handler receives message from client
3)Activity or client app should use service connection interface and the send message using Messanger send method which gets received in handler of service
http://joerichard.net/android/android-how-to-bind-service-from-another-application/
Implicit intents do not declare the class name of the component to start, but instead declare an action to perform. The action specifies the thing you want to do, such as view, edit, send, or get something. Intents often also include data associated with the action, such as the address you want to view, or the email message you want to send. Depending on the intent you want to create, the data might be a Uri, one of several other data types, or the intent might not need data at all.
If your data is a Uri, there's a simple Intent() constructor you can use to define the action and data.
For example, here's how to create an intent to initiate a phone call using the Uri data to specify the telephone number:
Uri number = Uri.parse("tel:5551234");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
When your app invokes this intent by calling startActivity(), the Phone app initiates a call to the given phone number.
queryIntentActivities()
To allow other apps to start your activity, you need to add an <intent-filter> element in your manifest file for the corresponding <activity> element.
We can call another activity of second App from first App by using <intent-filter> action name (This intent filter action name is defined in the manifets of second app to the activity which we are going to call)
http://hmkcode.com/android-start-another-activity-of-another-application/
Firebase is a cloud service provider. It is now under google and this service can replace your whole server side part of your application. In many tutorials we had used MySQL and PHP for our database. But if we will use Firebase we do not need any server side code or configuration. We can directly use firebase. Firebase comes with a bundle of many features.
Nice article well explained . there is good linkedlist examples collection
ReplyDeletevisit Java Linked list examples