Total Pageviews

Tuesday, 26 January 2016

What is a final modifier? Explain other Java modifiers?

A final class can’t be extended i.e. A final class may not be subclassed. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (i.e. it is a constant).
Statics
Note: Be prepared for tricky questions on modifiers like, what is a “volatile”? Or what is a “const”? Etc. The reason it is tricky is that Java does have these keywords “const” and “volatile” as reserved, which means you can’t name your variables with these names but modifier “const” is not yet added in the language and the modifier “volatile” is very rarely used.
The “volatile” modifier is used on member variables that may be modified simultaneously by other threads. Since other threads cannot see local variables, there is no need to mark local variables as volatile. E.g. volatile int number; volatile private List listItems = null; etc. The modifier volatile only synchronizes the variable marked as volatile whereas “synchronized” modifier synchronizes all variables.
Java uses the final modifier to declare constants. A final variable or constant declared as “final” has a value that is immutable and cannot be modified to refer to any other objects other than one it was initialized to refer to. So the “final” modifier applies only to the value of the variable itself, and not to the object referenced by the variable. This is where the “const” modifier can come in very useful if added to the Java language. A reference variable or a constant marked as “const” refers to an immutable object that cannot be modified. The reference variable itself can be modified, if it is not marked as “final”. The “const” modifier will be applicable only to non-primitive types. The primitive types should continue to use the modifier “final”.

What is serialization? How would you exclude a field of a class from serialization or what is a transient variable? What is the common use?

Serialization is a process of reading or writing an object. It is a process of saving an object’s state to a sequence of bytes, as well as a process of rebuilding those bytes back into a live object at some future time. An object is marked serializable by implementing the java.io.Serializable interface, which is only a marker interface -- it simply allows the serialization mechanism to verify that the class can be persisted, typically to a file.
Serial
Transient variables cannot be serialized. The fields marked transient in a serializable object will not be transmitted in the byte stream. An example would be a file handle or a database connection. Such objects are only meaningful locally. So they should be marked as transient in a serializable class. 
Serialization can adversely affect performance since it:
  • Depends on reflection.
  • Has an incredibly verbose data format.
  • Is very easy to send surplus data.
When to use serialization? Do not use serialization if you do not have to. A common use of serialization is to use it to send an object over the network or if the state of an object needs to be persisted to a flat file or a database. Deep cloning or copy can be achieved through serialization. This may be fast to code but will have performance implications.
The objects stored in an HTTP session should be serializable to support in-memory replication of sessions to achieve scalability . Objects are passed in RMI (Remote Method Invocation) across network using serialization.

What is the main difference between a String and a StringBuffer class?

String
String is immutable: you can’t modify a string object but can replace it by creating a new
instance. Creating a new instance is rather expensive.
//Inefficient version using immutable String
String output = “Some text”
Int count = 100;
for(int I =0; i<count; i++) {
output += i;
}
return output;
The above code would build 99 new String objects, of which 98 would be thrown away immediately. Creating new objects is not efficient.
StringBuffer / StringBuilder
StringBuffer is mutable: use StringBuffer or StringBuilder when you want to modify the contents. StringBuilder was added in Java 5 and it is identical in all respects to StringBuffer except that it is not synchronised, which makes it slightly faster at the cost of not being thread-safe.
//More efficient version using mutable StringBuffer
StringBuffer output = new StringBuffer(110);
Output.append(“Some text”);
for(int I =0; i<count; i++) {
output.append(i);
}
return output.toString();
The above code creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer expands as needed, which is costly however, so it would be better to initilise the StringBuffer with the correct size from the start as shown.
Another important point is that creation of extra strings is not limited to ‘overloaded mathematical operators’ (“+”) but there are several methods like concat(), trim(), substring(), and replace() in String classes that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations, which offer better performance.

What are the benefits of the Java collection framework?

Collection framework provides flexibility, performance, and robustness.
  • 􀂃Polymorphic algorithms – sorting, shuffling, reversing, binary search etc.
  • Set algebra - such as finding subsets, intersections, and unions between objects.
  • Performance - collections have much better performance compared to the older Vector and Hashtable classes with the elimination of synchronization overheads.
  • Thread-safety - when synchronization is required, wrapper implementations are provided for temporarily synchronizing existing collection objects.
  • Immutability - when immutability is required wrapper implementations are provided for making a collection immutable.
  • Extensibility - interfaces and abstract classes provide an excellent starting point for adding functionality and features to create specialized object collections.

When is a method said to be overloaded and when is a method said to be overridden?

Method Overloading
Overloading deals with multiple methods in the same class with the same name but different method signatures.
class MyClass {
    public void getInvestAmount(int rate) {…}
    public void getInvestAmount(int rate, long principal)
    { … }
}
Both the above methods have the same method names but different method signatures, which mean the methods are overloaded.
Overloading lets you define the same operation in different ways for different data.
Method Overriding
Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.
class BaseClass{
    public void getInvestAmount(int rate) {…}
}
class MyClass extends BaseClass {
    public void getInvestAmount(int rate) { …}
}
Both the above methods have the same method names and the signatures but the method in the subclass MyClass overrides the method in the superclass BaseClass.
Overriding lets you define the same operation in different ways for different object types.

Why there are some interfaces with no defined methods (i.e. marker interfaces) in Java?

The interfaces with no defined methods act like markers. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently. Example Serializable , Cloneable etc

What is the difference between an abstract class and an interface and when should you use them?

What is the difference between an abstract class and an interface and when should you use them?
In design, you want the base class to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behaviour), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword. If anyone tries to make an object of an abstract class, the compiler prevents it.
The interface keyword takes this concept of an abstract class a step further by preventing any method or function implementation at all. You can only declare a method or function but not provide the implementation. The class, which is implementing the interface, should provide the actual implementation. The interface is a very useful and commonly used aspect in OO design, as it provides the separation of interface and implementation and enables you to:
  • Capture similarities among unrelated classes without artificially forcing a class relationship.
  • Declare methods that one or more classes are expected to implement.
  • Reveal an object's programming interface without revealing its actual implementation.
  • 􀂃 Model multiple interface inheritance in Java, which provides some of the benefits of full on multiple inheritances, a feature that some object-oriented languages support that allow a class to have more than one superclass.
diamond
Abstract class
  • Have executable methods and abstract methods.
  • Can only subclass one abstract class.
  • Can have instance variables, constructors and any visibility: public, private, protected, none (aka package).
Interface
  • Have no implementation code. All methods are abstract.
  • A class can implement any number of interfaces.
  • Cannot have instance variables, constructors and can have only public and none (aka package) visibility.
When to use an abstract class?: In case where you want to use implementation inheritance then it is usually provided by an abstract base class. Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some default behaviour and force subclasses to provide any specific behaviour. Care should be taken not to overuse implementation inheritance.
When to use an interface?: For polymorphic interface inheritance, where the client wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently, you should prefer using interface to abstract. CO Coding to an interface reduces coupling and interface inheritance can achieve code reuse with the help of object composition. Another justification for using interfaces is that they solve the ‘diamond problem’ of traditional multiple inheritance as shown in the figure. Java does not support multiple inheritances. Java only supports multiple interface inheritance. Interface will solve all the ambiguities caused by this ‘diamond problem’.