1)Difference between listview and recyclerview
i) ViewHolder Pattern
In a ListView, it was recommended to use the ViewHolder pattern but it was never a compulsion. In case of RecyclerView, this is mandatory using the RecyclerView.ViewHolder class. This is one of the major differences between the ListView and the RecyclerView.
It makes things a bit more complex in RecyclerView but a lot of problems that we faced in the ListView are solved efficiently.
Reuse cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.
ii) LayoutManager
This is another massive enhancement brought to the RecyclerView. In a ListView, the only type of view available is the vertical ListView. There is no official way to even implement a horizontal ListView.
Now using a RecyclerView, we can have a
i) LinearLayoutManager - which supports both vertical and horizontal lists,
ii) StaggeredLayoutManager - which supports Pinterest like staggered lists,
iii) GridLayoutManager - which supports displaying grids as seen in Gallery apps.
And the best thing is that we can do all these dynamically as we want.
iii) Item Animator
ListViews are lacking in support of good animations, but the RecyclerView brings a whole new dimension to it. Using the RecyclerView.ItemAnimator class, animating the views becomes so much easy and intuitive.
iv) Item Decoration
In case of ListViews, dynamically decorating items like adding borders or dividers was never easy. But in case of RecyclerView, the RecyclerView.ItemDecorator class gives huge control to the developers but makes things a bit more time consuming and complex.
v) OnItemTouchListener
Intercepting item clicks on a ListView was simple, thanks to its AdapterView.OnItemClickListener interface. But the RecyclerView gives much more power and control to its developers by the RecyclerView.OnItemTouchListener but it complicates things a bit for the developer.
In simple words, the RecyclerView is much more customizable than the ListView and gives a lot of control and power to its developers.
What is final in Java?
Final in java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase performance of Java application.
What is final keyword in Java?
Final keyword, final variable, final method and class in java exampleFinal is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise compilation error if you try to re-initialized final variables in java.
What is final variable in Java?
Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant. Here is an example of final variable in Java
public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error
Final variables are by default read-only.
What is final method in Java
Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time. Here is an example of final method in Java:
class PersonalLoan{
public final String getName(){
return "personal loan";
}
}
class CheapPersonalLoan extends PersonalLoan{
@Override
public final String getName(){
return "cheap personal loan"; //compilation error: overridden method is final
}
}
What is final Class in Java
Java class with final modifier is called final class in Java. Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes. Here is an example of final class in java
final class PersonalLoan{
}
class CheapPersonalLoan extends PersonalLoan{ //compilation error: cannot inherit from final class
}
Benefits of final keyword in Java
Here are few benefits or advantage of using final keyword in Java:
1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.
2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.
3. Final keyword allows JVM to optimized method, variable or class.
Final and Immutable Class in Java
Final keyword helps to write immutable class. Immutable classes are the one which can not be modified once it gets created and String is primary example of immutable and final class which I have discussed in detail on Why String is final or immutable in Java. Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead. You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in java.
Example of Final in Java
Java has several system classes in JDK which are final, some example of final classes are String, Integer, Double and other wrapper classes. You can also use final keyword to make your code better whenever it required. See relevant section of java final tutorial for example of final variable, final method and final class in Java.
Important points on final in Java
1. Final keyword can be applied to member variable, local variable, method or class in Java.
2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.
3. You can not reassign value to final variable in Java.
4. Local final variable must be initializing during declaration.
5. Only final variable is accessible inside anonymous class in Java.
6. Final method can not be overridden in Java.
7. Final class can not be inheritable in Java.
8. Final is different than finally keyword which is used on Exception handling in Java.
9. Final should not be confused with finalize() method which is declared in object class and called before an object is garbage collected by JVM.
10. All variable declared inside java interface are implicitly final.
11. Final and abstract are two opposite keyword and a final class can not be abstract in java.
12. Final methods are bonded during compile time also called static binding.
13. Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".
14. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.
15. As per Java code convention final variables are treated as constant and written in all Caps e.g.
private final int COUNT=10;
16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:
private final List loans = new ArrayList();
loans.add(“home loan”); //valid
loans.add("personal loan"); //valid
loans = new Vector(); //not valid
That’s all on final in Java. We have seen what final variable, final method is and final class in Java and what does those mean. In Summary whenever possible start using final in java it would result in better and faster code.
Difference between Hashtable and HashMap in Java
Hashtable vs HashMap in Java
Hashtable and HashMap are two hash based collection in Java and used to store objects as key value pair. Despite being hash based and similar in functionality there are a significant difference between Hashtable and HashMap and without understanding those difference if you use Hashtable in place of HashMap than you may run into series of subtle programs which is hard to find and debug.Unlike Difference between ArrayList and HashMap, Difference between Hashtable and HashMap are more subtle because both are similar kind of collection. Before seeing difference between HashMap and Hashtable let's see some common things between HashMap and Hashtable in Java.
Similarities between Hashtable and HashMap in Java
There are lot of similar things between Hashtable and HashMap in Java which is good to know and these also helps to find exactly what is different between HashMap and Hashtable in Java:
1) Both Hashtable and HashMap implements java.util.Map interface.
2) Hashtable and HashMap both are a hash based collection and works on the principle of hashing.
3) Hashtable and HashMap both provide constant time performance for put and get method if objects are distributed uniformly across bucket.
4) From JDK 4 both Hashtable and HashMap are part of Java collection framework.
Difference between Hashtable and HashMap in Java
What is Difference between HashMap and Hashtable in Java CollectionDespite being so similar there are some differences between Hashtable and HashMap in Java which separates them completely, let's have a look :
1) First and most significantly different between Hashtable and HashMap are that HashMap is not thread-safe while Hashtable is a thread-safe collection.
2) The second important difference between Hashtable and HashMap is performance since HashMap is not synchronized it perform better than Hashtable.
3) The third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.
These were some important difference on Hashtable and HashMap in Java. If you know any other difference which is not included here then feels free to add them in the comment section. Remember this is an important question on Java interview and good to prepare it well.
AIDL
Each Android app run in it’s own process. So one application can’t directly access another app’s memory space. If you want to access some data from one application to another application, then we need to use inter process communication (IPC) like other platforms. So in Android IPC is otherwise known as AIDL. For this purpose Android provides a technique called Android Interface Definition Language (AIDL). It is a lightweight implementation of IPC just like C/C++ languages.
So to communicate between process or you say between applications, we need to implement AIDL in our Android application. In other words you can say the AIDL technique is a light weighted client server architecture in form of a service, which helps multiple applications to communicate between them self. To do so we need the below steps.
1. AIDL interface- Define a AIDL interface which will be the interface between your applications.
2. Implement the the remote service- Remote service holds your data/method to expose to other applications for accessing data.
3. Expose the remote service to other local clients- The data/method we need to share with other applications needs to be expose so that other application can access and share data from the remote service.
Java - How to use Singleton Class ?
The Singleton's purpose is to control object creation, limiting the number of obejcts to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources.
Example
// File Name: Singleton.java
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){ }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
Here is the main program file where we will create singleton object:
// File Name: SingletonDemo.java
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance( );
tmp.demoMethod( );
}
}
Difference between Singleton Pattern vs Static Class in Java
similarities
both can be used without creating object
both provide only one instance
1)Why you use Singleton instead of Static Methods?
2)Can you replace Singleton with static class?
3)what are differences between Singleton pattern and static in Java?
static class is a Java class, which only contains static methods
While Singleton classes are those, which has only one instance during application life cycle
1) Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.
2) One more difference between Singleton and static is, ability to override. Since static methods in Java cannot be overridden, they leads to inflexibility. On the other hand, you can override methods defined in Singleton class by extending it.
3) Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to mock and thus easy to test. It’s easier to write JUnit test for Singleton than static classes, because you can pass mock object whenever Singleton is expected, e.g. into constructor or as method arguments.
4) If your requirements needs to maintain state than Singleton pattern is better choice than static class, because
maintaining state in later case is nightmare and leads to subtle bugs.
5) Singleton classes can be lazy loaded if its an heavy object, but static class doesn't have such advantages and always eagerly loaded.
6) Many Dependency Injection framework manages Singleton quite well e.g. Spring, which makes using them very easy.
These are some differences between static class and singleton pattern, this will help to decide between two, which situation arises. In next section we will when to choose Singleton pattern over static class in Java.
Main advantage of Singleton over static is that former is more object oriented than later. With Singleton, you can use Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. If we talk about java.lang.Runtime, which is a Singleton in Java, call to getRuntime() method return different implementations based on different JVM, but guarantees only one instance per JVM, had java.lang.Runtime an static class, it’s not possible to return different implementation for different JVM.
That’s all on difference between Singleton and static class in Java. When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.
What is Singleton class? Have you used Singleton before?
Singleton is a class which has only one instance in whole application and provides a getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.
Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?
Here they check whether candidate has enough experience on usage of singleton or not. Does he is familiar of advantage/disadvantage or alternatives available for singleton in Java or not.
Answer : Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class , since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application, if you want to show popup with message you can have one PopUp class on whole GUI application and anytime just get its instance, and call show() with message.
Can you write code for getInstance() method of a Singleton class in Java?
Most of the java programmer fail here if they have mugged up the singleton code because you can ask lots of follow-up question based upon the code they have written. I have seen many programmer write Singleton getInstance() method with double checked locking but they are not really familiar with the caveat associated with double checking of singleton prior to Java 5.
Answer : Until asked don’t write code using double checked locking as it is more complex and chances of errors are more but if you have deep knowledge of double checked locking, volatile variable and lazy loading than this is your chance to shine. I have shared code examples of writing singleton classes using enum, using static factory and with double checked locking in my recent post Why Enum Singletons are better in Java, please see there.
Singleton design pattern Interview Questions in Java
Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer?
This is really nice question and I mostly asked to just quickly check whether candidate is aware of performance trade off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the time its just read only access so locking of critical section is always better option. read more about synchronization on How Synchronization works in Java
Answer : This is again related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to getInstance() will be synchronized and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton, It’s better to only synchronize critical section and not whole method. Singleton pattern is also closely related to factory design pattern where getInstance() serves as static factory method.
What is lazy and early loading of Singleton and how will you implement it?
This is another great Singleton interview question in terms of understanding of concept of loading and cost associated with class loading in Java. Many of which I have interviewed not really familiar with this but its good to know concept.
Answer : As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.
Give me some examples of Singleton pattern from Java Development Kit?
This is open question to all, please share which classes are Singleton in JDK. Answer to this question is java.lang.Runtime
Answer : There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:
Java.lang.Runtime with getRuntime() method
Java.awt.Toolkit with getDefaultToolkit()
Java.awt.Desktop with getDesktop()
What is double checked locking in Singleton?
One of the most hyped question on Singleton pattern and really demands complete understanding to get it right because of Java Memory model caveat prior to Java 5. If a guy comes up with a solution of using volatile keyword with Singleton instance and explains it then it really shows it has in depth knowledge of Java memory model and he is constantly updating his Java knowledge.
Answer : Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization. See here to learn more about double-checked-locking in Java.
public static Singleton getInstance(){
if(_INSTANCE == null){
synchronized(Singleton.class){
//double checked locking - because second check of Singleton instance with lock
if(_INSTANCE == null){
_INSTANCE = new Singleton();
}
}
}
return _INSTANCE;
}
Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.
How do you prevent for creating another instance of Singleton using clone() method?
This type of questions generally comes some time by asking how to break singleton or when Singleton is not Singleton in Java.
Answer : Preferred way is not to implement Cloneable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as “Can not create clone of Singleton class”.
How do you prevent for creating another instance of Singleton using reflection?
Open to all. In my opinion throwing exception from constructor is an option.
Answer: This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”
How do you prevent for creating another instance of Singleton during serialization?
Another great question which requires knowledge of Serialization in Java and how to use it for persisting Singleton classes. This is open to you all but in my opinion use of readResolve() method can sort this out for you.
Answer: You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance. I have shared code on how to do it in my post Enum as Singleton in Java. This is also one of the reason I have said that use Enum to create Singleton because serialization of enum is taken care by JVM and it provides guaranteed of that.
When is Singleton not a Singleton in Java?
There is a very good article present in Sun's Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible.
Apart from these questions on Singleton pattern, some of my reader contribute few more questions, which I included here. Thank you guys for your contribution.
Why you should avoid the singleton anti-pattern at all and replace it with DI?
Answer : Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container.
Why Singleton is Anti pattern
With more and more classes calling getInstance() the code gets more and more tightly coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden dependencies. Also, there would be no need for this clumsy double checked locking if you call getInstance less often (i.e. once).
How many ways you can write Singleton Class in Java?
Answer : I know at least four ways to implement Singleton pattern in Java
Singleton by synchronizing getInstance() method
Singleton with public static final field initialized during class loading.
Singleton generated by static nested class, also referred as Singleton holder pattern.
From Java 5 on-wards using Enums
How to write thread-safe Singleton in Java?
Answer : Thread safe Singleton usually refers to write thread safe code which creates one and only one instance of Singleton if called by multiple thread at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using Enum or Singleton initialized by class loader.