Core Java FAQ's

Q1) What is polymorphism?

Ans) Polymorphism gives us the ultimate flexibility in extensibility. The abiltiy to define more than one function with the same name is called Polymorphism. In java,c++ there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class.

Overloading occurs when several methods have same names with

  •  Overloading is determined at the compile time.
  •  Different method signature and different number or type of parameters.
  •  Same method signature but different number of parameters.
  •  Same method signature and same number of parameters but of different type

Example of Overloading
     int add(int a,int b)
     float add(float a,int b)
     float add(int a ,float b)
     void add(float a)
     int add(int a)
     void add(int a)                 //error conflict with the method int add(int a)

Example: Overloading

Class BookDetails{
            String title;
            String publisher;
            float price;

setBook(String title){ }
setBook(String title, String publisher){ }
setBook(String title, String publisher,float price){ }
}

Example: Overriding

class BookDetails{
 String title;

setBook(String title){ }

}

class ScienceBook extends BookDetails{

 setBook(String title){}  //overriding

setBook(String title, String publisher,float price){ }  //overloading

}

Q2) What is inheritance?

Ans) Inheritance is the property which allows a Child class to inherit some properties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class.

public class Parent{

public String parentName;
public int parentage;
public String familyName;
}

public class Child extends Parent{

public String childName;
public int childAge;

public void printMyName(){
System.out.println(“ My name is “+ chidName+” “ +familyName)
}

}

In above example the child has inherit its family name from the parent class just by inheriting the class.

Q3) What is multiple inheritance and does java support?

Ans) If a child class inherits the property from multiple classes is known as multiple inheritance.
Java does not allow to extend multiple classes but to overcome this problem it allows to implement multiple Interfaces.

Q4) What is abstraction?

Ans) Abstraction is way of converting real world objects in terms of class. For example creating a class Vehicle and injecting properties into it. E.g

public class Vehicle {

public String colour;
public String model;
}

Q5) What is encapsulation?


Ans) The encapsulation is achieved by combining the methods and attribute into a class. The class acts like a container encapsulating the properties. The users are exposed mainly public methods.The idea behind is to hide how thinigs work and just exposing the requests a user can do.

Q6) What is Association?

Ans) Association is a relationship between two classes. In this relationship the object of one instance perform an action on behalf of the other class. The typical behaviour can be invoking the method of other class and using the member of the other class.

public class MyMainClass{

public void init(){

new OtherClass.init();

}

}

Q7) What is Aggregation?


Ans) Aggregation has a relationship between two classes. In this relationship the object of one class is a member of the other class. Aggregation always insists for a direction.

public class MyMainClass{

OtherClass otherClassObj = new OtherClass();

}

Q8) What is Composition?

Ans) Composition is a special type of aggregation relationship with a difference that its the compulsion for the OtherClass object (in previous example) to exist for the existence of MyMainClass.

Q4 What is difference between abstract class and interface?

Ans) 1) A class is called abstract when it contains at least one abstract method. It can also contain n numbers of concrete method.Interface can contain only abstract( non implemented) methods.
2) The abstract class can have public,private,protect or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesnt have any variables it only has constants.
3) A class can extend only one abstract class but a class can implement multipleinterfaces.
4) If an interface is implemented its compulsory to implement all of its methods but if an abstract class is extended its not compulsory to implement all methods. 5) The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

Q5) Explain with example to describe when to use abstract class and interface?

Ans) Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementaion for tyres will be provided.


public abstract class Car{

public abstract String getCarName();

public final int getNoOfTyres(){
   return 4;
}

}

Consider a scenario where Cars can have any number of tyres and other features can also be different. In this case interface will be created.


public interface Car{

public abstract String getCarName();
public abstract int getNoOfTyres();
}

Q6) Does java support multiple interitance? Why?

Ans) Java doesnt support multiple inheritance but it provide a way through which it can enact it.
Consider the scenario is C++

Class A{

public void add(){
// some text
}
}

Class B{

public void add(){
// some text
}
}

Class C extends A,B{

public static void main(String arg[]){

C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.
}

This problem is called Diamond problem.

This problem in java is taken care with the use of interfaces
In Java similar problem would look like:

interface A{
add();
}

interface B{
add();
}

class C implements A,B{

add(){
// doesnt matter which interface it belong to
}
}

Q7) Can this keyword be assigned null value?

Ans) No

Q8) What are the different types of references in java?

Ans) Java has a more expressive system of reference than most other garbage-collected programming languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. The java.lang.ref package defines three other types of references—soft, weak, and phantom references. Each type of reference is designed for a specific use.

A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable), but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector. Semantically, a soft reference means "keep this object unless the memory is needed."

A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable anywhere else. Another possible application of weak references is the string intern pool. Semantically, a weak reference means "get rid of this object when nothing else references it."


A PhantomReference is used to reference objects that have been marked for garbage collection and have been finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is referenced by a phantom reference is calledphantom reachable. This allows for more flexible cleanup than is possible with the finalization mechanism alone. Semantically, a phantom reference means "this object is no longer needed and has been finalized in preparation for being collected."

Q9) How to change the heap size of a JVM?


Ans) The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program

Q10) What is difference between instanceof and isInstance(Object obj)?

Ans) Differences are as follows:

1) instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.

if (obj instanceof MyType) {
...
}else if (MyType.class.isInstance(obj)) {
...
}

2) instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.

Q11) Java supports pass by value or pass by reference?

Ans) Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive data types or objects. For the data type the actual value is passed.
Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects.Consider the example:

 public void tricky(Point arg1, Point arg2)
 {
   arg1.x = 100;
   arg1.y = 100;
   Point temp = arg1;
   arg1 = arg2;
   arg2 = temp;
 }
 public static void main(String [] args)
 {
   Point pnt1 = new Point(0,0);
   Point pnt2 = new Point(0,0);
   System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
   System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
   System.out.println(" ");
   tricky(pnt1,pnt2);
   System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
   System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
 }

OutPut:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0

The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.

Q12) What is memory leak?

Ans) A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.

Q13) What is the difference between equals() and ==?


Ans) == operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects.
But since the method can be overriden like for String class. equals() method can be used to compare the values of two objects.

 String str1 = "MyName";
 String str2 = "MyName";
 String str3 = str2;

 if(str1 == str2){
 System.out.println("Objects are equal")
 }else{
 System.out.println("Objects are not equal")
 }

 if(str1.equals(str2)){
 System.out.println("Objects are equal")
 }else{
 System.out.println("Objects are not equal")
 }

 Output:

 Objects are not equal
 Objects are equal


 String str2 = "MyName";
 String str3 = str2;

 if(str2 == str3){
 System.out.println("Objects are equal")
 }else{
 System.out.println("Objects are not equal")
 }

 if(str3.equals(str2)){
 System.out.println("Objects are equal")
 }else{
 System.out.println("Objects are not equal")
 }

 OutPut:
 Objects are equal
 Objects are equal

Q14) How to make sure that Childclass method actually overrides the method of the superclass?


Ans) The @Override annotation can be added to the javadoc for the new method. If you accidently miss an argument or capitalize the method name wrong, the compiler will generate a compile-time error.

Q15) How to find the size of an object?


Ans)The heap size of an object can be found using -

         Runtime.totalMemory()-Runtime.freeMemory() .

Q16) Can an abstract class have a static method?

Ans) Yes an abstract class have a static method and it can be accessed by any other class(even not a concrete class).

Q17) Can an abstract class have a constructor?

Ans) Yes an abstract class have a default and parameterized constructors.

Q18) Why static methods cannot access non static variables or methods?


Ans) A static method cannot access non static variables or methods because static methods doesnt need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be intialized since the object is not created and this could result in an error.

Q19) What is difference between stringbuffer and stringbuilder?

Ans) The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among StringBuffer and StringBuilder

1)If your text can change and will only be accessed from a single thread, use a StringBuilder 2)because StringBuilder is unsynchronized.

If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

Q20) Consider a scenario in which the admin want to sure that if some one has written System.exit() at some part of application then before system shutdown all the resources should be released. How is it possible?


Ans) This is possible using Runtime.getRuntime().addShutdownHook(Thread hook).

Straight from Java Spec:
This method registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

1. The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
2. The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.
Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.

Q21) What is the difference between final, finally and finalize() in Java?

Ans)
final - constant declaration. A final variable act as constant, a final class is immutable and a final method cannot be ovrriden.
finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.
finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Q22) How does Java allocate stack and heap memory?


Ans) Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.
In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code.

Q23) Explain re-entrant, recursive and idempotent methods/functions?

Ans) A method in stack is re-entrant allowing multiple concurrent invocations that do not interfere with each other.
A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms. Allrecursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server.

Q24)Can a private variable or method of a class can be accessed?

Ans) Yes its possible using reflection.

Q25)What is difference between static block and the init block?
Or
Difference between
Static {} and {}

Ans) The static block is loaded when the class is loaded by the JVM for the 1st time only whereas init {} block is loaded every time class is loaded. Also first the static block is loaded then the init block.

public class LoadingBlocks {

   static{
    System.out.println("Inside static");
   }

   {
    System.out.println("Inside init");
   }
   public static void main(String args[]){
    new LoadingBlocks();
    new LoadingBlocks();
    new LoadingBlocks();
   }
}

Output:

Inside static
Inside init
Inside init
Inside init

Q26)Why inner class can access only final variable?


Ans) Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.
Anonymous inner classes require final variables because of the way they are implemented in Java. An anonymous inner class (AIC) uses local variables by creating a private instance field which holds a copy of the value of the local variable. The inner class isn't actually using the local variable, but a copy. It should be fairly obvious at this point that a "Bad Thing"รข„¢ can happen if either the original value or the copied value changes; there will be some unexpected data synchronization problems. In order to prevent this kind of problem, Java requires you to mark local variables that will be used by the AIC as final (i.e., unchangeable). This guarantees that the inner class' copies of local variables will always match the actual values.

Q27)What is fully abstract class?

Ans) An abstract class which has all methods as abstract and all fields are public static final.

Q28)What is dynamic binding and static binding?


Ans) Method invocation
The Java programming language provides two basic kinds of methods: instance methods and class (or static) methods. The difference are:
1. Instance methods require an instance before they can be invoked, whereas class methods do not.
2. Instance methods use dynamic (late) binding, whereas class methods use static (early) binding.
When the Java virtual machine invokes a class method, it selects the method to invoke based on the type of the object reference, which is always known at compile-time. On the other hand, when the virtual machine invokes an instance method, it selects the method to invoke based on the actual class of the object, which may only be known at run time.

Q29) What is Java Reflection?

Ans)Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.
Drawbacks of Reflection: Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
Performance Overhead: Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
Security Restrictions: Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
Exposure of Internals: Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

Q30) When an obj is passed through a function , one can set the properties but cannot set a new memory location?


Ans) It is because when u pass an object the address value is passed and stored in some new address . like if address 1234 is passed , it is stored in 4567 location. So if u change in the value of an object it will take the address from 4567 and do 1234.setXXX(). If u set the object to null it will set 4567=null.
       
Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email