Core java interview questions

Several time i have been asked about the list of Core Java Interview questions. So here i will list down some of Interview Question that i or my friends have faced in Interviews.

Note*: I have also added some question that i use to ask in my interviews too 😛

Interview Question

Que : Java is platform independent language. What is the meaning of it?

Answer :

Que: How many methods are there in Object class?

Answer: There are total 9 methods

  1. equals()
  2. hashcode()
  3. clone()
  4. wait() (3 variant)
  5. notify()
  6. notifyAll()
  7. toString()

Que: Wait, notify and notify all these methods are related to Thread then why is it part of Object class?

Answer: These methods are related to Locks and LOCKS has nothing to do with Threads. Locks are associated with object hence these methods are part of Object class and not Thread class.

Que: Can we create a private class??

Answer: No. Class can have only public or default access modifier.

Que: What others modifiers are there which can be applied to class?

Answers: Non Access Modifiers that can be applied to Classes are

  1. Final
  2. Static
  3. Abstract
  4. Strictfp

Que : Java supports Pass by Value or Pass by Reference??

Answer : Pass by value.

Que: What do you mean by Platform Independence in Java?

Answer : I would better write an article for this. Once done i ll point to that article. Sorry 🙁

Que : What is the difference between == and equals method?

Answer :  You better look at here for detail answer.

Que : What is the difference between comparable and comparator interface?

Answer :

Que : What is the use of Marker Interfaces when there is no method in Marker Interface?

Answer :

Que: What is the difference between ArrayList and LinkedList?

Ans:

Que: How(Steps) to Create Immutable Class?

Ans: Some Rules needs to be followed in order to create Immutable class.
1- Make constructor private
2- Provide static method to get instance to class.
3- Throw CloneNotSupported exception.
4- Make class Final.

How to implement Singleton pattern?

Single instance per JVM 4 thing needs to followed in order to achieve it.
1- Make constructor private.
2- Provide Static method to get singleton object
3- Make a private referrence variable
4- Check for ref type in static method if it is null then make a reference and assign it and return else just return.
5- make the static method as synchronized.(when 2 thread access the same time they will see ref as null and end up in creating two reference so avoid that situation need to make static method as synchronized)
6- Provide the implementation for Clone() method and throw CloneNotSupportedException exception from method (If singleton class extend some other class which is supporting the Clone method in that case we need to do this otherwise Clone method will create another instance).

Class & Object

Que: Why wait and Notify is in Object Class and not in Thread

Ans: In Multi Threaded model Java uses locks to implement exclusive access to object & lock is related to object and not Thread. These methods work on the locks of the object i.e. the reason why these methods are in Object class and not in Thread.

Que: What is inline class?

Ans:

Que: What is Class

Ans: Class is a template for multiple objects with similar features(State & Behavior) and it is a blue print for objects

Que: What is Constructor

Ans: Special kind of method that determines how an object is initialized when created.

Que: What is the difference between Constructor & Method?

Ans: Differences are

  • Constructor needs to have the name of Class. Method can have any name even the Class name.
  • Constructor can not return any value like Method.
  • Constructor will be invoked implicitly when object of Class is created. While method needs to be invoked.

Que: What is the use of Class.ForName and how it works.

Ans: Every object has a corresponding class object. This class object instance is shared among all instances of that class type. Class.forName loads & Returns the Class object associated with the class/interface with the given string name. It will also load the class if it is not already loaded in JVM. From Java Docs Instances of the class Class represent classes and interfaces in a running Java application. Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader. It is mainly used in reflection to get the details of class. Note: If Class has Static block, ananymous block and constructor then only static block will get executed while executing this code.

Que: How to increase JVM size?

Ans: in order to overcome heap size problem -Xxm1024m tag can be used to increase heap size.

Que: Does class ‘Class’ extends Object?

Ans: Java has a class named “Class” it also extends Object class. It also implements Serialization Interface. It represent classes and interfaces in a running Java application

Note: everything in Java except primitives extend Object class.

Que: What is compile-time loading and run-time loading?

Ans:

Inner Class

Que: An inner class can not access method variable in which it is defined but can access if it is final why?

Ans: Inner classes are class within Class. Inner class instance has special relationship with Outer class. This special relationship gives inner class access to member of outer class as if they are the part of outer class.
Inner class instance has access to all member of the outer class(Public, Private & Protected)
For more Details Go to Core Java Inner Class Section.

Que: Different type of Inner classes?

Ans: Type of Inner Class

1- Static
2- Method Local
3- Anonymous
4- Other then above these normal inner class

Variable

Que: Why final instance variable don’t get default value ? what specialty occurred with final variable??

Ans: Once final variable assigned value it can not be changed this is the reason why Final variable don’t get default value.

Que: Use of intern() method in String object.

Ans: Intern method checks if given string object(using equals method) is already present in the string pool or not. If yes method will return the String from the pool otherwise given String object is added to the pool and a reference to this String object is returned. In any case this method can’t be used to check if String object is already available in String pool or not.

Que: Java support pass-by value or pass-by reference?

Ans: Pass-by value.

Static & this

Que: What is static in Java?

Ans: Static means class level. Static field would be class level and all instance of the class will have access to the same Single variable. Static variable and method can be accessed without creating any reference.

Que: Is there any way to make static method from Super class to Instance method in subclass?

Ans:No, We can only hide the static method from Super class.

Que: What are the different type of execute() methods available, which can be used with JDBC connection for executing proc/stmt?

Ans:

Que: What is pros and cons of using synchronization?

Ans: Synchronization is used to restrict a particular section of code to be executed by single thread one at a time only. But this feature also make other Thread wait for one single thread to complete its processing which in turn delays the processing time.

Que: Method name which can be used to call garbage collection?

Ans: System.gc()
It Runs the garbage collector. It is equivalent to “Runtime.getRuntime().gc()“.

Que: What is Final?

Ans: Final is a modifier which can be applied on Class / Method / Variable.

  1. Final class can not be extended.
  2. Final method can not be overridden.
  3. Final variables value can’t be changed once assigned.

Que: Can we declare Main method as private?

Ans: Yes you can declare main method as private.

Que: What is the use of static keyword for Main method and what will happen if we remove static keyword from signature?

Ans: Static method can be accessed without creating any object. In this way main method provides entry point for Application. If we remove static keyword it will not be access by JVM and Application can not be started.

Que: Can we have several main method in the same class?

Ans: Yes a class can have several main() method. But main method from the public class in the same file will be accessed while running the app.

Que: Does importing of package also import subpackage?

Ans: No.

Que: What are the different steps in Serialization?

Ans:

Que: In process to serialize what happens to the object inside the class?

Ans: Object inside object will be serialized or not si depend on if given object is itself serilized or not.

Que: What happens to static field while serialization?

Ans:

Que: What are wrapper classes and what is use of it?

Ans: In Java everything except primitives are object. These primitives don’t get the benefit of being object. Wrapper classes are created to provide the same to primitives. Integer class is wrapper for int primitive.

Que: Execution of finally with respect to return and system exit

Ans: There will be only one case when finally block will not get executed and that would be System.exit()(If called from try block) other then this in every condition finally block will get executed.

Que: What is Observer and Observable?

Ans:

Que: What are synchronized method and synchronized statement?

Ans:

// This is synchronized metho
	public synchronized void method(){
		System.out.println();
	}
	
	public void method1(){
		// This is synchronized block inside method
		synchronized(this) {
			System.out.println("Hi");	
		}
		System.out.println("Hello");
	}

 

Que: Can an unreachable object become reachable again? (Yes via Final method)

Ans: Yes unreachable code can be accessed vie final block. When ever garbage collection will occur final block will be executed without fail so object can be reachable in that final block.

Que: What will be the default values of all the elements of an array defined as an instance variable?

Ans: It will depend on type of Array you are defining. If it is Object type it will be null else it will contain default value of that data types. e.g. for boolean it will be false, for int it is 0.

 

Que: What is Overloading?

Ans: Look Here for better understanding of Overloading

Que: What is Overriding?

Ans: Look Here for better understanding of Overriding

Que: Can we Overload Overriden method?

Ans: Yes, Derived class can Overload, overridden method.

Que: Can we Override Main method?

Ans: No, Main method is static method and static method can’t be Overriden. It will be hidden in derieved class. For Rules of Overriding look here

Que: How can we invoke super class version of Overriden method?

Ans: Super keyword can be used for this purpose. super keyword will invoke the overriden method from super class.

Syntax: super.methodName()

Que: What is Super?

Ans: Super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.

Note*:super or this needs to be first statement in method declaration. Hence both can not be used at the same time.

Que: Is there any way we can prevent method from being overriden?

Ans: We can avoid method overriding by using final keyword.

Syntax:

public void final methodName(){}

Que: Can constructor be inherited?

Ans: No, constructor cannot be inherited, though a derived class can call the base class constructor.

Que: What is Casting?

Ans: Process of converting the value of One type to another type.

Que: What is the difference between an argument and a parameter?

Ans: While defining method, variables passed in method are called parameters.

While using those methods, values passed to those variables are called arguments.

Que: What are different types of access modifiers?

Ans: Three type of access modifiers are there

  1. Public
  2. Private
  3. Protected

Que: What is Finally & Finalize?

Ans:
Finally: Key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will get execute whether or not an exception is thrown. There will be only one case when finally block will not get executed & that would be system.exit().
finalize: finalize method will be called just before garbage collection of Object

Que: What is Garbage Collection ? How to call garbage collection explicitly?

Ans: When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
Note*: It is just request to garbage collection. It doesn’t force JVM to garbage collect.

Que: What are Transient and Volatile Modifiers?

Ans:
Transient: Transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

Que: Why wait and Notify is in Object Class and not in Thread

Ans: In Multi Threaded model Java uses locks to implement exclusive access to object & lock is related to object and not Thread. These methods work on the locks of the object i.e. the reason why these methods are in Object class and not in Thread.

Que: What is the use of Final keyword?

Ans: Final is a modifier which can be applied on Class / Method / Variable.

  1. Final class can not be extended.
  2. Final method can not be overridden.
  3. Final variables value can’t be changed once assigned.

Que: Can we have several main method in the same class?

Ans: Yes a class can have several main() method. But main method from the public class in the same file will be accessed while running the app.

Que:Different type of Inner Class?

Ans:

1- Static
2- Method Local
3- Anonymous
4- Other then above these normal inner class

Que: What are wrapper classes and what is use of it?

Ans: In Java everything except primitives are object. These primitives don’t get the benefit of being object. Wrapper classes are created to provide the same to primitives. Integer class is wrapper for int primitive.

Que: What is the difference between Integer and Int?

Ans: Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself.

Integer is wrapper class for Int. Integer is an Object while Int is not

Que: Can we have an inner class inside method?

Ans: Yes, More details can be found here

Que: What is the difference between String and String Buffer?

Ans: String is immutable, value assigned once to String can not be changed while StringBuffer is mutable.

 

Exception

Que: What is Checked and Unchecked Exception?

Ans:
Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller.

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are Unchecked exceptions, compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Que: Diff between error and exception?

Ans:

Que: What are the different way of handling exception?

Ans: Exception can be either handled or can be transferred to handled later.

Interface & Abstract Class FAQ

Que: What is Externalization Interface?

Ans:

Que: What is Marker interface/Empty Interface? How can we create Marker Interface? What is the use of Marker Interface?

Ans: Marker interface don’t have any method to implement. It is just used to mark a class for specific functionality. e.g Serializable is the interface which informs JVM that implementing class should be synchronized. And JVM know how to do that.

Que: What is the difference between Abstract and Interface? When should we use any of these two?

Ans: An abstract class is a class which may have the usual flavors of class members (private, protected, etc.) with some abstract methods. An abstract class can have instance methods with default behavior. A class can extend only one abstract class. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. Methods are implicitly public and variables are implicitly public static Final. Which one to choose depends on the design requirement.

Que: Advantage of using Interface over abstract class except multiple Inheritance?

Ans:

Que: Why Interface methods can’t be static?

Ans:

Que: Modifiers allowed for method inside Interface?

Ans:

  1. public
  2. default
  3. abstract

Que: What is an Interface?

Ans: A Contract which class needs to follow when it is inheriting it.

For Complete functioning of Interface look here

Que: Can we instantiate Interface?

Ans: No

Que: Does Interface have member variable

Ans: Yes they have but these variable will be public , static and final implicitly

Que: Modifiers Allowed for method inside Interface?

Ans: Only Public & abstract modifier is allowed.

Que: Can there be an abstract class with no abstract methods in it?

Ans: Yes, there can be an abstract class without abstract methods.

Que: What is the Difference between abstract class and Interface?

Ans: An abstract class is a class which may have the usual flavors of class members (private, protected, etc.) with some abstract methods. An abstract class can have instance methods with default behavior. A class can extend only one abstract class. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. Methods are implicitly public and variables are implicitly public static Final. Which one to choose depends on the design requirement.

By | 2013-11-14T17:03:25+00:00 November 14th, 2013|Interview Question|4 Comments

About the Author:

4 Comments

  1. Yogi December 6, 2013 at 6:48 am - Reply

    For following question:
    Que: Can we create a final class??

    You said we can not create final class. It is confusing for me because String class is java is immutable means it is final.

    • Vivekanand Gautam December 6, 2013 at 6:18 pm - Reply

      Hi Yogi,

      Thanks for your comment. And i admit my mistake. Question should be “Can you create private class?”.
      And answer should be No.

      Thanks for pointing out this problem i have corrected the same. And yes you are right class can be final. Final is used with a class so that class can not be subclassed, like in case of String. Hope it clarifies your doubt.

      Do let me know in case you have more question.

      Thanks

  2. Rajbeer Singh August 29, 2016 at 10:01 pm - Reply

    Class can be private if it’s Normal inner.
    Normal inner class will be treated like member of the outer class so it can have several Modifiers as opposed to Class.

    final
    abstract
    public
    private
    protected
    strictfp
    Can you please clear this confusion?

    • J Singh September 3, 2016 at 10:00 am - Reply

      Hi Rajbeer,

      Inner class can be of 4 types.
      1- Method Local
      2- Ananymous
      3- Static
      Any other inner class not following in any of these 3 will be treated as normal inner class. And those inner class is like member(same as variable and method) of outer class. Hence it can have given modifiers. I would suggest you to go through below article to have a clear picture of Inner class.

      http://javabeginnerstutorial.com/core-java-tutorial/inner-class/

      Regards

Leave A Comment