Java Interview Questions and Answers for Freshers 2019

In this tutorial, we have covered almost 50+ important core Java Interview Questions and Answers for Freshers and experienced candidates.

This post on Java Interview Questions and Answers for Freshers is prepared to help you understand the basic concepts of Java programming for interview purposes. All the important JAVA concepts are explained here with examples for your easy understanding.

java interview questions and answers for freshers
java interview questions and answers for freshers

Java Interview Questions and Answers for Freshers

Q1) What are the types of access modifier in Java

Ans) There are four different types of modifiers:

Modifer Accessible in the same package Accessible in different package
Private No No
Protected Yes Yes, only if the class extends the main class
Default Yes No
Public Yes Yes

Q2) What is the use of final keyword?

Ans) The final keyword can be assigned to

  1. Class level variable
  2. method
  3. class
  4. Objects

If a final is assigned to a variable, the variable behaves as a constant. It means that the value of variable once set cannot be changed.

final int i=1;
i =5; // error

If a final is assigned to a method then it cannot be overridden in its child class.

class Parent {

final void print(){

 System.out.println(“Inside”);

}

}

class Child extends Parent{

public final void print(){ // error cannot override final method

 System.out.println(“Inside”);
}

}

If a class is made as final, then no other class can extend it and make it as parent class. E.g. String Class.

Final objects are instantiated only once. i.e

final Map map = new HashMap();

map.put(“key”,”value”);

map = new HashMap();  // error

Q3) What is use of synchronized keyword?

Ans) This keyword is used to prevent concurrency. Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.

public void synchronized method(){}
public void synchronized static method(){}
public void myMethod(){

 synchronized (this){ // synchronized keyword on block of code
 }

}

Q4) What is volatile keyword?

Ans) If you are working with the multithreaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn’t know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

Q5) What is a transient variable?

Ans) If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. When an object is deserialized the transient variables retains the default value depending on the type of variable declared and hence lost its original value.

Q6) What is a strictfp modifier?

Ans) Strictfp is used with variable only . It is used to restrict floating point calculations ( fp ) to ensure portability ( platform Independent ). When this modifier is specified, the JVM adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the consistent value independent of the platform. That is, if you want the answers from your code (which uses floating point values) to be consistent in all platforms, then you need to specify the strictfp modifier.

Q7) What is a static variable?

Ans) Static keyword can be used with the variables and methods but not with the class but there are static class. Anything declared as static is related to class and not objects.

Static variable : Multiples objects of a class shares the same instance of a static variable.Consider the example:

public class Counter{

  private static int count=0;

 private int nonStaticcount=0;

  public void incrementCounter(){

  count++;

  nonStaticcount++;

  }

  public int getCount(){

 return count;

 }

 public int getNonStaticcount(){

 return nonStaticcount;

 }

 public static void main(String args[]){

  Counter countObj1 = new Counter();

 Counter countObj2 = new Counter();

  countObj1.incrementCounter();

  countObj1.incrementCounter();

  System.out.println(“Static count for Obj1: “+countObj1.getCount());

  System.out.println(“NonStatic count for Obj1: “+countObj1.getNonStaticcount());

  System.out.println(“Static count for Obj2: “+countObj2.getCount())

  System.out.println(“NonStatic count for Obj2: “+countObj2.getNonStaticcount())

  }

Output

Static count for Obj1: 2

NonStatic count for Obj1: 2

Static count for Obj2: 2

NonStatic count for Obj2: 0

In the above program obj1 and obj2 share the same instance of static variable count hence if the value is incremented by one object , the incremented value will be reflected across the other objects.

Q8) What is a static method?

Ans)A method defined as static is called static method. A static method can be accessed without creating the objects. Just by using the Class name the method can be accessed.

Static method can only access static variables and not local or global non-static variables. For eg:

public class Test{
public static void printMe(){
System.out.println(“Hello World”);
}
}
public class MainClass{
 public static void main(String args[]){
  Test.printMe()

    }
 }
OutPut:
Hello World

Also static method can call only static methods and not non static methods. But non-static methods can call static mehtods.

Q9) 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 not be intialized since the object is not created and this could result in an error.

Q10) What is static class ?

Ans) A class cannot be declared static. But a class can be said a static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using Class name only

Q9) What is throw keyword?

Ans) Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.

  public void parent(){
  try{
   child();
  }catch(MyCustomException e){ }
  }


  public void child{
  String iAmMandatory=null;
   if(iAmMandatory == null){
    throw new MyCustomException(“Throwing exception using throw keyword”);
   }
  }

Q10) What is use of throws keyword?

Ans) If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the throws clause at the function declaration.

  public void parent(){
  try{
   child();
  }catch(MyCustomException e){ }
  }


  public void child throws MyCustomException{
   //put some logic so that the exception occurs.
  }

Key Concepts in Java

Q1) Why is main() method static?

Ans) To access the static method the object of the class is not needed. The method can be access directly with the help of ClassName. So when a program is started the jvm search for the class with main method and calls it without creating an object of the class.

Q2) What is the difference between staticmethods and instancemethods?

Ans) instance method belongs to the instance of a class therefore it requires an instance before it can be invoked, whereas static method belongs to the class itself and not to any class instance so it doesn’t need an instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use static (early) binding.
When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time. On the other hand, when the JVM invokes a static method, it selects the method to invoke based on the actual class of the object, which may only be known at compile time.

Q3) Can static block throw exception?

Ans) Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit. If System.exit() is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.

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 multiple interfaces.
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 called phantom 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 equal

 Objects are not 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() .

Key Concepts in Java

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?

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. All recursive 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 rleach 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.

Conclusion

These are some of the core JAVA interview questions that cover both the basic and advanced Java concepts for programming as well as developer interview, and these are ones which have been answered by our JAVA experts.

I hope that this tutorial would have given you a great insight into JAVA core coding concepts in detail. The explanations given above will really enrich your knowledge and increase your understanding of JAVA programming.

Get ready to crack an interview confidently !!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *