April 06, 2016

Java Interview Questions

What is Association, Aggregation and Composition?
Association is a relationship between two separate classes which can be of any type say one to one, one to may etc. It joins two entirely separate entities.

Aggregation is a special form of association which is a unidirectional one way relationship between classes (or entities), for e.g. Wallet and Money classes. Wallet has Money but money doesn’t need to have Wallet necessarily so its a one directional relationship. In this relationship both the entries can survive if other one ends. In our example if Wallet class is not present, it does not mean that the Money class cannot exist.

Composition is a restricted form of Aggregation in which two entities (or you can say classes) are highly dependent on each other. For e.g. Human and Heart. A human needs heart to live and a heart needs a Human body to survive. In other words when the classes (entities) are dependent on each other and their life span are same (if one dies then another one too) then its a composition. Heart class has no sense if Human class is not present.

What is Constructors in Java?
Constructor is a block of code that allows you to create an object of class. Constructor looks like a method but unlike methods, constructors don’t have any return type not even void.

Types of Constructors
1). Default constructor: If you do not define any constructor in your class, java generates one for you by default. This constructor is known as default constructor. You would not find it in your source code but it would present there.
2). no-arg constructor: Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body does nothing.
3). Parameterized constructor: Constructor with arguments is known as parameterized constructor.

  • Every class has a constructor whether it’s normal one or an abstract class (but we cannot initialize an abstract class).
  • Constructor overloading is possible but overriding is not possible.  
  • A constructor can also invoke another constructor of the same class – By using this(). If you wanna invoke a arg-constructor then give something like: this(parameter list).
 What is Constructor Chaining?
Constructor chaining is nothing but a scenario where in one constructor calls the constructor of its super class implicitly or explicitly. Suppose there is a class which inherits another class, in this case if you create the object of child class then first super class(or parent class) constructor will be invoked and then child class constructor will be invoked.

What is the difference between JVM, JRE and JDK in Java programming language?
JVM(Java Virtual Machine) is at heart of Java programming language and provide several feature to Java programmer including Memory Management and Garbage Collection, Security and other system level services. Java Virtual Machine can be customized e.g we can specify starting memory or maximum memory of heap size located inside JVM at the time of JVM creation. If we supplied invalid argument to java command it may refuse to create Java Virtual Machine by saying "failed to create Java virtual machine: invalid argument". In short Java Virtual Machine or JVM is the one who provides Platform independence to Java.

When our Java project builds, it translates the source code (contained in *.java source files) to Java bytecode (*.class files). This bytecode is a collection of compact instructions; easier for a machine to interpret, but is less readable. When we run a Java application on our computer, cellphone, or any other Java-enabled platform, we essentially pass this Java bytecode to the Java Virtual Machine.

The interpreter in the Java Virtual Machine usually starts compiling the entire bytecode at runtime. That means, JVM is responsible for converting byte code into machine specific code and that's why you have different JVM for Windows, Linux or Solaris but one JAR can run on all this operating system.

JRE(Java Runtime Environment) is a set of software tools for development of Java applications. It combines the Java Virtual Machine (JVM), platform core classes and supporting libraries. JRE is part of the Java Development Kit (JDK), but can be downloaded separately. JRE was originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle Corporation.

JDK(Java Development Kit) contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc… Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method. Just like JRE, JDK is also platform specific and you need to use separate installer for installing JDK on Linux and Windows.

In short the difference is:
1). JRE and JDK come as installer while JVM are bundled with them.
2). JRE only contain environment to execute java program but doesn’t contain other tool for compiling java program.
3). JVM comes along with both JDK and JRE and created when you execute Java program by giving “java” command.

What is difference between Path and Classpath?
Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

What are the different access modifiers in Java?
Java has four access modifier :
  • private access modifier is accessible only within class. It can be applied to member field, method or nested class in Java.
  • Top level class can not be declared as private.
  • private is the highest form of Encapsulation Java API provides and should be used as much as possible.
  • If a method is declared as private, then it cannot be overridden.
  • private keyword can also be applied to the constructor and if you make constructor private you prevent it from being sub-classed.
  • The protected access modifier is accessible within package and outside the package but through inheritance only.
  • The protected access modifier can be applied on the data member, method and constructor and can't be applied on the class.
  • public access modifier is accessible everywhere.
  • It has the widest scope among all other modifiers.
  • It is provided by Java if no access modifier is specified.
  • Package or default access level is second highest restrictive access modifier after private.
  • Any variable, method or class declared is only accessible on the package it belongs. 
What is Polymorphism?
Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations.

Its the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references.

Types of Polymorphism in Java:
1) Method Overloading
2) Method Overriding

Method Overloading :
  • It is also known as compile time polymorphism or Static polymorphism.
  • In this we can define two or more methods of same name in a class, provided that there argument list or parameters are different.
  • Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method.
  • When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
  • An overloaded method can throw different exceptions.
  • It can have different access modifiers.
  • Constructors can be overloaded
Method Overriding :
  • It is also known as run time polymorphism or Dynamic polymorphism.
  • Its the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. 
  • Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. 
  • The argument list of overriding method must be same as that of the method in parent class. The data types of the arguments and their sequence should be maintained as it is in the overriding method.
  • Overriding method can have different return type.
  • Overriding method must not have more restrictive access modifier. For e.g. if the Access Modifier of base class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier as all of the three are more restrictive than public.
  • Abstract methods must be overridden
  • private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.
  • Overriding method (method of child class) can throw any unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. We will discuss this in detail with example in the upcoming tutorial. 
  • non static methods cannot be overridden as static and vice-versa.
  • Constructors cannot be overridden.

Can you override static method in Java?
Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior. Static methods are resolved at compile time rather than runtime. Though you can declare and define static method of same name and signature in child class, this will hide the static method from parent class, that's why it is also known as method hiding in Java.

Suppose you have declared a Father class, which is extended by Son. Both the classes have method 'static void sayHello()'.

Father f=new Son();

This will always call sayHello() method from Father class. (if sayHello() was not declared static then, sayHello() from Son will be called)

Can we change the argument list of an overriding method?
No, you cannot.

Can we override a private method in Java?
No, you cannot. Since the private method is only accessible and visible inside the class they are declared, it's not possible to override them in subclasses. Though, you can override them inside the inner class as they are accessible there

Can we have a non-abstract method inside interface?
From Java 8 onward you can have a non-abstract method inside interface, prior to that it was not allowed as all method was implicitly public abstract. From JDK 8, you can add static and default method inside an interface.

Can we overload or override the main method in Java?
No, since main() is a static method, you can only overload it, you cannot override it because the static method is resolved at compile time without needing object information hence we cannot override the main method in Java.

What is Covariant return?
Before 1.5, when you override a superclass method, the name, argument types and return type of the overrding method has to be exactly same as that of superclass method. Overriding method is said to be invariant with respect to argument types and return type.

But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.

The covariant return type in java, allows narrowing down return type of the overridden method. This feature will help to avoid down casting on the client side.

What will be the output of this programme?
public static void printIt(Integer i)
    System.out.println("Printing Integer value :"+i);
public static void printIt(int i)
    System.out.println("Printing int value :"+i);
public static void main(String[] args) {

It will print :
Printing int value :7

What will happen when you throw exception while overriding method?
public class Parent {
    public void printIt(int i)
        System.out.println("Printing int value in Parent :"+i);

public class Child extends Parent {
    public void printIt(int i) throws IOException
        System.out.println("Printing int value in Child :"+i);

You will get an compile time error : 'Exception IOException is not compatible with throws clause in Parent.printIt(int)'

How compiler handles the exceptions in overriding?
  • The overriding methods can throw any runtime Exception, here in the case of runtime exception overriding method (subclass method) should not worry about exception being thrown by superclass method.
  • If superclass method does not throw any exception then while overriding, the subclass method can not throw any new checked exception but it can throw any runtime exception
  • Different exceptions in java follow some hierarchy tree(inheritance). In this case, if superclass method throws any checked exception, then while overriding the method in subclass we can not throw any new checked exception or any checked exception which are higher in hierarchy than the exception thrown in superclass method

If the method in parent class throws RuntimeException, can the overriding method throws IOException?

If an overridden is throwing some exception, is it mandatory to mention throws in overriding method?
No, its not mandatory.

What is Encapsulation?
It means binding the data with the code that manipulates it, it keeps the data and the code safe from external interference

By Encapsulation we can keep all the related members (variables and methods) together in an object.

The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. However if we setup public getter and setter methods to update (for e.g. void setUserName(String userName))and read (for e.g.  int getUserName()) the private data fields then the outside class can access those private data fields via public methods.

This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as 'Data Hiding' or 'Information Hiding'.

The idea of encapsulation is to keep classes separated and prevent them from having tightly coupled with each other.

Encapsulated code should have following characteristics:
  • Everyone knows how to access it.
  • Can be easily used regardless of implementation details.
  • There shouldn’t any side effects of the code, to the rest of the application.
Difference between Abstraction and Encapsulation in Java?
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Abstraction is the concept of hiding irrelevant details.In other words make complex system simple by hiding the unnecessary detail from the user.

Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

What is Inheritance?
It is the mechanism by which an object acquires the some/all properties of another object. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it.

The existing (or original) class is called the base class or super class or parent class. The new class which inherits from the base class is called the derived class or sub class or child class. Inheritance implements the “Is-A” or “Kind Of/ Has-A” relationship.

Advantages of Inheritance:
# Inheritance is a mechanism of defining a new class based on an existing class, which enables reuse of code. That means code in base class need not be rewritten in the derived class.
# It also provides scope for refinement of the existing class.

Types of Inheritance
Multilevel Inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class.
Multiple Inheritance refers to the concept of one class inheriting from more than one base class. The problem with “multiple inheritance” is that the derived class will have to manage the dependency on two base classes.

*Multi-level inheritance is allowed in Java but multiple inheritance is not.

What is an Inner class?
Inner class are defined inside the body of another class (known as outer class). These classes can have access modifier or even can be marked as abstract and final.

All the Inner classes have special relationship with outer class instances. This relationship allows them to have access to outer class members including private members too.

There are four types of Inner classes:
1) Inner class
2) Method-local inner class
3) Anonymous inner class
4) Static nested class

How clone method works in Java?
The clone() method from java.lang.Object class is used to create a copy of an Object in Java. This copy is known as a clone of original instance. Constructor is not called during cloning of Object in Java.

clone() method is declared as protected and native in Object class. Since its convention to return clone() of an object by calling super.clone() method, any cloning process eventually reaches to java.lang.Object clone() method.

A clone object should follow basic characteristics:
1). a.clone() != a, which means original and clone are two separate object in Java heap.
2). a.clone().getClass() == a.getClass()
3). a.clone().equals(a), which means clone is exact copy of original object.

Above three characteristic is followed by a well behaved, correctly overridden clone() method in Java, but it's not enforced by the cloning mechanism. Which means, an object returned by clone() method may violate any of these rules.

By following the convention of returning an object by calling super.clone(), when overriding clone() method, you can ensure that it follows first two characteristics. In order to follow the third characteristic, you must override equals method to enforce logical comparison, instead of physical comparison exists in java.lang.Object.

clone() method, first checks if the corresponding object implements Cloneable interface, which is a marker interface. If that instance doesn't implement Cloneable then it throws a checked exception CloneNotSupportedException. Else, java.lang.Object's clone() method creates a shallow copy of the object and returned it to the caller.

Since Object class' clone() method creates copy by creating new instance, and then copying field-by-field, similar to assignment operator, it's fine for primitives and Immutable object, but not suited if your class contains some mutable data structure e.g. Collection classes like ArrayList or arrays. In that case, both original object and copy of the object will point to the same object in the heap. You can prevent this by using the technique known as deep cloning, on which each mutable field is cloned separately.

Which classes in java are immutable?
String and all wrapper classes in java.lang  (such as Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger) are immutable. Also LocalDate, LocalTime and LocalDateTime classes (since 1.8) are also immutable.

What are the advantages of immutability?
  • Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
  • Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
  • The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
  • The best use of the immutable objects is as the keys of a map.
Does Declaring an object 'final' makes it immutable?
Only declaring primitive types as final makes them immutable. Making objects final means that the object handler cannot be used to target some other object but the object is still mutable.

How to create Immutable Class and Object in Java?
First of all let us understand what immutable class or object is?  Immutable classes are those class, whose object can not be modified once created, it means any modification on immutable object will result in another immutable object. e.g. java.lang.String, once created can not be modified. All modification (e.g. trim, uppercase, lowercase) in String result in new object.

Example of immutable class: SecretDetails is immutable, because the state of class can not be changed once created, we havedeclated all of it’s fields as final.

public final class SecretDetails {
    private final String employeename;
    private final int employeeage;

    public SecretDetails(String employeename, int employeeage) {
        this.employeename = employeename;
        this.employee = employee;
    public String getEmployeename(){
        return employeename;
    public String getEmployeeage(){
        return employeeage;

What if your immutable class includes a mutable classes like java.util.Date?
Despite storing Date into final field, it can be modified internally, if internal date is returned to the client. In order to preserve immutability in such cases, its advised to return copy of original object, which is also one of the Java best practice.

ALSO READ: Why String is immutable or Final in Java?

e.g in ImmutableReminder if getRemindingDate() returns actual Date object than despite remindingDate being final variable, internals of Date can be modified by client code. By returning clone() or copy of remindingDate, we avoid that danger and preserves immutability of class.

public final class ImmutableReminder{
    private final Date remindingDate;
    public ImmutableReminder (Date remindingDate) {
        if(remindingDate.getTime() < System.currentTimeMillis()){
            throw new IllegalArgumentException("Can not set reminder for past time: " + remindingDate);
        this.remindingDate = new Date(remindingDate.getTime());
    public Date getRemindingDate() {
        return (Date) remindingDate.clone();


OR add a getter method for Date like this:

public Date getRemindingDate() {
    return new Date(this.remindingDate.getTime());

Here are few things that we must consider for making an immutable class:
  • Make your class final.
  • Make all the fields private and final.
  • Don't declare any methods that change the state of your instance (no setter's)
  • If you have mutable fields in your class, like List, or Date, making them final won't suffice. You should return a defensive copy from their getters, so that their state isn't mutated by calling methods.
Advantages of Immutable Objects:
1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.
2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.
3) Immutable object boost performance of Java application by reducing synchronization in code.
4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers.

However, immutable object has disadvantage of creating garbage as well. Since immutable object can not be reused and they are just a use and throw.

How  do you prevent SQL Injection in Java Code?
In SQL Injection attack, malicious user pass SQL meta-data combined with input which allowed them to execute sql query of there choice.

ALSO READ: JDBC Interview Questions And Answers

PreparedStatement can be used to avoid SQL injection in Java code. Use of the PreparedStatement for executing SQL queries not only provides better performance but also shield your Java and J2EE application from SQL Injection attack. All the parameters passed as part of place-holder will be escaped automatically by JDBC Driver.

What is an interface and what are the advantages and disadvantage of using interfaces in Java?
  • With interfaces, we can achieve abstraction in Java along with abstract class.
  • Interface in java is declared using keyword interface and it represent a Type like any Class in Java. A reference variable of type interface can point to any implementation of that interface in Java.
  • All variables declared inside interface is implicitly public final variable or constants. which brings a useful case of using Interface for declaring Constants.
  • All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword. You can not define any concrete method in interface. That's why interface is used to define contracts in terms of variables and methods and you can rely on its implementation for performing job.
  • Interfaces allow several classes to share a standard set of methods and constants without requiring these methods and constants to be implemented by a common superclass.
  • Interfaces are mainly used to provide polymorphic behavior and a standard framework for accessing classes.
  • Interfaces function to break up the complex designs and clear the dependencies between objects.
  • Java interfaces are slower.
  • Interface should be used multiple number of times else there is hardly any use of having them.
Can you override private or static method in Java?
You can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding.

What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
finally block will execute even if you put return statement in try block or catch block, but finally block won't run if you call System.exit from try or catch.

Can you access non static variable in static context?

What do the expression 1.0 / 0.0 will return? will it throw Exception? any compile time error?
It will not throw ArithmeticExcpetion and return Double.INFINITY.

What is the difference between StringBuffer and StringBuilder in Java?
StringBuilder in Java was introduced in JDK 1.5 and the only difference between both of them is that StringBuffer methods e.g. length(), capacity() or append() are synchronized while corresponding methods in StringBuilder are not synchronized. Thats why, concatenation of String using StringBuilder is faster than StringBuffer.

What are Wrapper classes?
A wrapper class wraps (encloses) around a data type and gives it an object appearance. They include methods to unwrap the object and give back the data type.
int intCount = 100;
Integer wrapperIntCount = new Integer(intCount); //this is called Boxing
int intCountBack = wrapperIntCount.intValue(); //thats unBoxing

There are mainly two uses with wrapper classes:
1) To convert simple data types into objects, i.e to give object form to a data type.
2) To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.

#All wrapper classes have typeValue() method. This method returns the value of the object as its primitive type.
#The valueOf() method is available in all wrapper classes except Character.

The 8 primitive types and its wrapper classes are:
byte : - Byte
int : - Integer
short : - Short
long  : - Long
float : - Float
double : - Double
char  : - Character
boolean : - Boolean

Why we need Wrapper classes?
Java is an object-oriented language and can view everything as an object. The primitive data types (like int) are not objects, they do not belong to any class,they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language. For example, upto JDK1.4, the data structures accept only objects to store. A data type is to be converted into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced wrapper classes.

What is Static variables, methods, class and block?
Static variables are class variables i.e., there will be only one copy for each class and not one copy for each object of the class and these variables will be accessed without instantiating the class. Static Variables make program memory efficient.

Static methods are class methods because  belongs to the class rather than object of a class. They can be accessed without creating an instance of the class. Static methods cannot access instance variables, they can access only static variables.

Static classes: If you declare a top-level class as a static class, then Java will throw a compilation error. Only inner classes that are member classes can be declared as static. If we declare member classes as static, we can use it as a top-level class outside the context of top-level class. One catch here is "The static keyword does not do to a class declaration what it does to a variable or a method declaration." - what it means is say for example you have a static variable, then to access that static variable you will use the notation
but when you want to use the static inner class, you need to instantiate like
<>.<> newClass = new <>.<>();

Static blocks
are also called Static initialization blocks is a normal block of code enclosed in braces{ }, and preceded by the static keyword. A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. And this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes.

If you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM.

If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.

What are the advantages of static blocks?

  • If you’re loading drivers and other items into the namespace. For ex, Class class has a static block where it registers the natives.
  • If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded.
  • Security related issues or logging related tasks
What are the limitations for static blocks?
  • There is a limitation of JVM that a static initializer block should not exceed 64K.
  • You cannot throw Checked Exceptions.
  • You cannot use this keyword since there is no instance.
  • You shouldn’t try to access super since there is no such a thing for static blocks.
  • You should not return anything from this block.
  • Static blocks make testing a nightmare.
Can we execute a program without main() method?
Yes, in previous version of JDK before 1.7, we can use static block to execute a program. But in JDK7 and above, we will get 'Main method not found in class, please define the main method as:', when we execute the class.

What is static import in Java 5?
Static import is introduced in Java 5 along with other features like Generics, Enum, Autoboxing and Unboxing and variable argument methods. 

The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.

For example without static import you will access static constant MAX_VALUE of Integer class as Integer.MAX_VALUE but by using static import you can import Integer.MAX_VALUE and refer it as MAX_VALUE. Similar to regular import statements, static import also allows wildcard * to import all static members of a class. e.g:

import static java.lang.Integer.MIN_VALUE;
import static java.lang.System.out;
import static java.lang.Math.*;

public class StaticImportTest {
public static void main(String args[]) {
//using out instead of System.out
out.println("Minimum value of int variable in Java without static import : " + Integer.MIN_VALUE);

//instead of double var1= Math.sqrt(5.0);
double var1= sqrt(5.0);
  • Static import statements are written as "import static" in code and not "static import".
  • If you import two static fields with same name explicitly e.g. Integer.MAX_VALUE and Long.MAX_VALUE then Java will throw compile time error. But if other static modifier is not imported explicitly e.g. you have imported java.lang.Long.*, MAX_VALUE will refer to Integer.MAX_VALUE.
  • Static import doesn't improve readability as expected, as many Java programmer prefer Integer.MAX_VALUE which is clear that which MAX_VALUE are you referring.
  • You can apply static import statement not only on static fields but also on static methods in Java.
  • If you are going to use static variables/methods a lot then it’s fine to use static imports.
  • Static Imports makes the code confusing and less readable so if you are going to use static members very few times in your code then probably you should avoid using it.  
What is Generics in Java ?
Generics is introduced in J2SE 5 to deal with type-safe objects. Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, provides compile time type-safety and ensures that you only insert correct Type in collection and avoids ClassCastException in runtime.

Because of the Generics type casting is not required. e.g

Before Generics:
List list = new ArrayList(); 
list.add("Neuschwanstein Castle"); 
String s = (String) list.get(0);//typecasting 

After Generics:
List list = new ArrayList(); 
list.add("Neuschwanstein Castle"); 
String s = list.get(0);

Generics provides compile-time checking, e.g:
List list = new ArrayList(); 
list.add("Neuschwanstein Castle"); 
list.add(108);//Compile Time Error 

Generic Class: A class that can refer to any type is known as generic class. e.g:
class MyGenericClass
    T obj; 
    void add(T obj){this.obj=obj;} 
    T get(){return obj;} 

In the above example, T type indicates that it can refer to any type (like String, Integer, Student, LoadingOrder etc.). The type you specify for the class, will be used to store and retrieve the data.

class MyGenericClassTest{ 
public static void main(String args[]){ 
MyGenericClass m=new MyGenericClass(); 
//m.add("Nathan");//Compile time error 

The type parameters naming conventions are important to learn generics thoroughly. The commonly type parameters are as follows:
T - Type, E - Element, K - Key, N - Number, V - Value
As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters

Generic Methods
are those methods that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods −

All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).

Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.

The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).

// generic method printArray
public static < E > void printArray( E[] inputArray ) {
      for(E element : inputArray) {
         System.out.printf("%s ", element);

What is bounded and unbounded wildcards in Generics Java?

The ? (question mark) symbol represents wildcard element. It means any type. If we write < ? extends Number > , it means any child class of Number e.g. Integer, Float, double etc. Now we can call the method of Number class through any child class object.

Bounded and unbounded wildcards in Generics are two types of wildcard available on Java. Any Type can be bounded either upper or lower of the class hierarchy in Generics by using bounded wildcards. In short and represent bounded wildcards while represent an unbounded wildcard in generics.

Can we use Generics with Array?
Array doesn't support Generics.

Can you pass List < String >   to a method which accepts List < Object >

No, it will result in compilation error.

Difference between List and List< object > in Java?

List < ? > is List of unknown type while List < Object >  is essentially List of any Type. You can assign List < String > , List < Integer >  to List < ? >  but you can not assign List < String >  to List < Object > .

What is Re-factoring in Software?
- Re-factoring is the continuous process of changing a software system in such a way that it does not alter the external behavior of the code yet improves the internal structure of the code.
- It is advisory that developers should have habit to apply re-factoring as continuous process to improve the code structure.
- Re-factoring helps to keep the code clone and minimize the chances of introducing bugs.
- Re-factoring made the internal structure of the software, easier to understand and cheaper to enhance the functionality of the software.

If a class is declared without any access modifiers, where can the class be accessed?
  • A class declared without any access modifiers is said to have package access.
  • Such a class can only be accessed by other classes and interfaces defined within the same package.
What is the difference between a soft reference and a weak reference in Java?
Garbage Collector reclaims memory from objects which are eligible for garbage collection and this eligibility is decided based upon which kind of references are pointing to that object.
For those uninitiated, there are four kind of reference in Java: Strong, weak, soft, phantom.

Strong Reference is most simple as we use it in our day to day programming life e.g. in the code, String city = "Nuremberg" , reference variable city has strong reference to String object "Nuremberg". Any object which has Strong reference attached to it is not eligible for garbage collection, because these are objects which is needed by Java program.

Weak Reference are represented using java.lang.ref.WeakReference class. You can create weak by:
City city = new City(); // strong reference
WeakReference weakCity = new WeakReference(city); //weak reference
/* as soon as you declare 'city=null', City object will become eligible for garbage collection
city = null;

If instead of WeakReference, Soft Reference is used then City object is not garbage collected until JVM absolutely needs memory. Soft reference in Java is represented using java.lang.ref.SoftReference class. e.g:
City city = new City(); // strong reference
SoftReference softCity = new SoftReference(city); //soft reference
city = null;

That means, Garbage collector can collect an object if only weak references are pointing towards it and they are eagerly collected, on the other hand Objects with SoftReference are collected when JVM absolutely needs memory. SoftReference are more suitable for caches and WeakReference are more suitable for storing meta data

WeakHashMap is an example of WeakReference, which is another implementation of Map interface like HashMap or TreeMap but with one unique feature. WeakHashMap wraps keys as WeakReference which means once strong reference to actual object removed, WeakReference present internally on WeakHashMap doesn't prevent them from being Garbage collected.

Phantom reference is available in java.lang.ref package and is represented by java.lang.ref.PhantomReference class. Object which only has Phantom reference pointing them can be collected whenever Garbage Collector likes it.
City city = new City(); // strong reference
PhantomReference phantomCity = new PhantomReference(city);
city = null;

In the order of strength, the references can be arranged as, Strong References > Soft References > Weak References > Phantom References

What is the purpose of the Runtime class?
Runtime class is an example of Singleton  design pattern and is used to access fhe java runtime system. The runtime information – memory availability, invoking the garbage collector is possible by using Runtime class.

  • Runtime.freeMemory() - Returns the free memory of
  • Runtime.maxMemory() - Returns the memory that JVM can use at the maximum.
  • Runtime.gc() - Invoking garbage collector

Some other facilities that are provided by Runtime class are:
Reading data through key board
Using system properties and environment variables
Running non-java programs from within a java application.

Explain the difference between static and dynamic class loading.
1. The static class loading is done through the new operator.
2. Dynamic class loading is achieved through Run time type identification,also called as reflection.
3. This is done with the help of the following methods:
getClass(); getName(); getDeclaredFields();
4. Instance can also be created using forName() method. It loads the class into the current class memory.

What is static and dynamic class loading in Java?
Static Class Loading: Creating objects and instance using new keyword is known as static class loading. The retrieval of class definition and instantiation of the object is done at compile time.
Dynamic Class Loading: Loading classes use Class.forName () method. Dynamic class loading is done when the name of the class is not known at compile time.

What will be the output of this program?
Integer a=100, b=100;
Integer c=1000, d=1000;

The first sysout will return true, whereas the second will return false.

Whenever you compile a number literal in Java and assign it to a Integer ('Integer a=100') the compiler emits Integer a =Integer.valueOf(100);

Above line of code is also generated when you use autoboxing. valueOf is implemented such that certain numbers are 'pooled', and it returns the same instance for values smaller than 128. In Java valueOf is implemented as:
public static Integer valueOf(int i) {
    if(i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
        return new Integer(i);

That means Integer objects with the values -128 to 127 are immutable (that is, for one particular integer value, say 27, all Integer objects instantiated through your program with the value 27 points to the exact same object).

If you want to increase IntegerCache, then you need to configure 'IntegerCache.high' with the system property.

If you set this, then 'System.out.println(c==d)' will return true.

For those uninitiated, == operator compares by reference (does the variables point to the same object). Its better never rely on two references being identical, always compare them with .equals() method. So c.equals(d) will print true for all logically equal values of c,d.
What is J2EE(Java 2 Platform Enterprise Edition)?
J2EE is a platform-independent, Java-centric environment from Sun for developing, building and deploying Web-based enterprise applications online. The J2EE platform consists of a set of services, APIs, and protocols that provide the functionality for developing multitiered, Web-based applications.

A few key features and services of J2EE:
  • At the client tier, J2EE supports pure HTML, as well as Java applets or applications. It relies on Java Server Pages and servlet code to create HTML or other formatted data for the client.
  • Enterprise JavaBeans (EJBs) provide another layer where the platform's logic is stored. An EJB server provides functions such as threading, concurrency, security and memory management. These services are transparent to the author.
  • Java Database Connectivity (JDBC), which is the Java equivalent to ODBC, is the standard interface for Java databases.
  • The Java servlet API enhances consistency for developers without requiring a graphical user interface.
Can an Interface implement another Interface?
Intefaces doesn't provide implementation hence a interface cannot implement another interface.

Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

Can a class be defined inside an Interface?
Yes it's possible.

Can an Interface be defined inside a class?
Yes it's possible.

Name the eight primitive Java types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.

What is a String Pool ?
String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

How many objects are created with this code ?
String city =new String("Munich");

Two objects will be created. One object creates memory in heap with new operator and second in stack constant pool with "Munich".

Which are the different segments of memory ?
  • Stack Segment : contains local variables and Reference variables(variables that hold the address of an object in the heap)
  • Heap Segment : contains all created objects in runtime, objects only plus their object attributes (instance variables)
  • Code Segment :  The segment where the actual compiled Java bytecodes resides when loaded.
Describe what happens when an object is created in Java ?
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Why do member variables have default values whereas local variables don't have any default value?
member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.

Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains wil complain about it. And the JVM will internally load the class only once no matter how many times you import the same class.

What is a class loader? What are the different class loaders used by JVM ?
Part of JVM which is used to load classes and interfaces. Bootstrap , Extension and System are the class loaders used by JVM.

Bootstrap ClassLoader is responsible for loading standard JDK class (like java.lang, java.util etc) files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents, if you call String.class.getClassLoader() it will return null and any code based on that may throw NullPointerException in Java. Bootstrap class loader is also known as Primordial ClassLoader in Java. 

Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form JAVA_HOME/jre/lib/ext directory or any other directory pointed by java.ext.dirs system property. Extension ClassLoader in JVM is implemented by  sun.misc.Launcher$ExtClassLoader.

System or Application class loader is the third default class loader used by JVM to load Java classes and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR. Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader class. Also, except Bootstrap class loader, which is implemented in native language mostly in C,  all  Java class loaders are implemented using java.lang.ClassLoader.

Difference between loadClass and Class.forName ?
loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it.

Explain java.lang.OutOfMemoryError?
This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

What is PermGen or Permanent Generation? How to deal with java.lang.OutOfMemoryError?
There are two memory regions in the JVM: the heap and the stack. Local variables and methods reside on the stack, everything else on the heap.

Java objects are created in Heap and Heap is divided into three parts or generations for the sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of the heap.  New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent minor garbage collection if an object survives its gets moved to survivor 1 and then survivor 2 before major garbage collection moved that object to old or tenured generation.

Since permanent generation is a separate region, it is not considered part of the Java Heap space. Objects in this space are relatively permanent. Perm space is used to keep information (metadata) for loaded classes and few other advanced features like String Pool(for highly optimized string equality testing), which usually get created by String.intern() methods.
Without getting into details, Classloaders deploy and undeploy classes all the time. For example, this happens when an application is deployed or undeployed on a webserver. On web servers, all applications have their own Classloader. When an application is deployed or undeployed, its class definitions and Classloader are respectively put into and removed from the permanent generation heap.

  • -Xms : Sets the initial heap size for when the JVM starts.
  • -Xmx : Sets the maximum heap size.
  • -Xmn : Sets the size of the Young Generation.
  • -XX:PermSize : Sets the starting size of the Permanent Generation.
  • -XX:MaxPermSize : Sets the maximum size of the Permanent Generation

StudentDetails std = new StudentDetails(); after executing the line above memory status will be like this.
Heap: stores "new StudentDetails()"
Stack: stores information about "std"
Perm Space: stores information about StudentDetails class

OutOfMemoryError: PermGen Space error occurs when the permanent generation heap is full. Although this error can occur in normal circumstances, usually, this error is caused by a memory leak. In short, such a memory leak means that a classloader and its classes cannot be garbage collected after they have been undeployed/discarded.

You can avoid OutOfMemoryError: PermGen by:
1). Increasing the maximum size of the permgen heap

Permanent generation of the heap is used to store String pool and various Metadata required by JVM related to Class, method and other java primitives. Since in most of JVM default size of Perm Space is around "64MB" you can easily run out of memory if you have too many classes or a huge number of Strings in your project. It doesn't depend on –Xmx value, so no matter how big your total heap size you can run OutOfMemory in perm space.

You can specify the size of permanent generation using JVM options "-XX: PermSize" and  "-XX: MaxPermSize" based on your project need, e.g: export JVM_ARGS="-Xmx1024m -XX:MaxPermSize=256m"

2. Make sure you do not write classes that have static variables keeping references to class definitions and the like.

You can solve java.lang.OutOfMemoryError: Java heap space in 2 ways:

1). increase the maximum heap size by using JVM options "-Xmx512M". Its better to keep -Xmx to -Xms ration either 1:1 or 1:1.5 if you are setting heap size in your java application. e,g:

export JVM_ARGS="-Xms1024m -Xmx1024m"

2). If you are still getting the error even after increasing the heap size then, best way is to check your application (can use Eclipse Memory Analyzer to examine your heap dump) and look for any memory leak.

What are the available types of Garbage Collectors in Java?
1). Serial Garbage Collector: It is the default for client style machines in Java SE 5 and 6. It works by holding all the application threads in ‘Stop the World’ fashion ( the execution of application is paused while the collection of garbage takes place). It is designed for the single-threaded environments and uses just a single thread for garbage collection. The way it works by freezing all the application threads while doing garbage collection may not be suitable for a server environment. It is best suited for simple command-line programs.

Turn on the -XX:+UseSerialGC JVM argument to use the serial garbage collector.

2). Parallel garbage collector: It is also called as throughput collector. Unlike serial garbage collector, this uses multiple threads for garbage collection. Similar to serial garbage collector this also freezes all the application threads while performing garbage collection.

The number of garbage collector threads can be controlled with command-line options: -XX:ParallelGCThreads=< desired number >

3). Concurrent Mark Sweep (CMS) garbage collector : It uses multiple threads to scan the heap memory to mark instances for eviction and then sweep the marked instances. It attempts to minimize the pauses due to garbage collection by doing most of the garbage collection work concurrently with the application threads.

In comparison with parallel garbage collector, CMS collector uses more CPU to ensure better application throughput. If we can allocate more CPU for better performance then CMS garbage collector is the preferred choice over the parallel collector.

To enable the CMS Collector use -XX:+UseConcMarkSweepGC and to set the number of threads use -XX:ParallelCMSThreads=< desired number >

4). G1 garbage collector : The Garbage First or G1 garbage collector is available in Java 7 and is designed to be the long term replacement for the CMS collector. The G1 collector is a parallel, concurrent, and incrementally compacting low-pause garbage collector that has quite a different layout from the other garbage collectors described previously.

It is used for large heap memory areas. It separates the heap memory into regions and does collection within them in parallel. G1 also does compacts the free heap space on the go just after reclaiming the memory. But CMS garbage collector compacts the memory on stop the world (STW) situations. G1 collector prioritizes the region based on most garbage first.

Turn on the –XX:+UseG1GC JVM argument to use the G1 garbage collector.

What is difference between ParNew and DefNew Young Generation Garbage collector?
ParNew and DefNew is two young generation garbage collector. ParNew is a multi-threaded GC used along with concurrent Mark Sweep while DefNew is single threaded GC used along with Serial Garbage Collector.

-K Himaanshu Shuklaa..

No comments:

Post a Comment

RSSChomp Blog Directory