Core java interview questions

Page Content

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

Beginners

1: Java is platform independent language. What does it mean? (beg)

 

2: How many methods are there in Object class? (Beg)

There are total 9 methods

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

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

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.

4: Can we create a private class??

No Class can have only public or default access modifier.

5: 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

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

You better look at here for detail answer.

9: What is the difference between Comparable and Comparator interface?

 

10: What is the use of Marker Interfaces when there is no method in the Marker Interface? (Inter)

 

11: What is the difference between ArrayList and LinkedList in terms of performance? (Inter)

12: How(Steps) to Create Immutable Class? (Inter)

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

13: How to implement the Singleton pattern? (Inter)

Single instance per JVM 4 thing needs to follow in order to achieve it.
1- Make the constructor private.
2- Provide a Static method to get singleton object
3- Make a private reference 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 references so avoid that situation need to make the static method as synchronized)
6- Provide the implementation for Clone() method and throw CloneNotSupportedException exception from a 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).

Can we use an enum to create singleton class? (Inter)

Class & Object

14: Why wait and Notify is in Object Class and not in Thread? (Inter)

In Multi-Threaded model Java uses locks to implement exclusive access to object & lock is related to an 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.

15: What is an inline class? (Inter)

16: What is Class

A class is a template for multiple objects with similar features(State & Behavior) and it is a blue print for objects

17: What is Constructor

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

18: What is the difference between Constructor & Method?

Differences are

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

19: What is the use of Class.ForName and how it works. (Inter)

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 represents 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 the class. Note: If Class has a Static block, anonymous block and constructor then the only static block will get executed while executing this code.

20: How to increase JVM Heap size? (Inter)

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

21: Does the class ‘Class’ extends Object?

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

Note: everything in Java except primitives extend Object class.

22: What is compile-time loading and run-time loading? (??)

Inner Class

23: An inner class can not access the method variable in which it is defined but can access if it is final why? (Inter)

Inner classes are class within Class. An inner class instance has the special relationship with Outer class. This special relationship gives inner class access to the member of the outer class as if they are the part of the outer class.
An 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.

24: Different type of Inner classes? (Inter)

Type of Inner Class

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

Variable

25: Why the final instance variable doesn’t get default value? what specialty occurred with final variable??

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

26: Use of intern() method in String object? (Inter)

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.

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

Pass-by value.

Static & this

28: What is static in Java?

Static means class level. A 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.

29: Is there any way to make static method from Superclass to Instance method in the subclass? (Inter)

No, We can only hide the static method from Superclass.

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

31: What is the pros and cons of using synchronization? (Inter)

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

32: Method name which can be used to call(Request) garbage collection? (Inter)

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

33: What is Final?

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

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

34: Can we declare the Main method as private?

Yes, you can declare the main method as private.

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

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

37: Does importing of package also import subpackage?

No.

38: What are the different steps in Serialization? (Inter)

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

The object inside object will be serialized or not si depend on if given object is itself serialized or not.

40: What happens to the static field while serialization? (Inter)

41: What are wrapper classes and what is the use of it? (Inter)

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

42: Execution of finally with respect to return and system exit? (Inter)

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.

43: What are Observer and Observable? (Inter)

 

44: What are the synchronized method and synchronized statement?

// 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");
	}

 

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

Yes, unreachable code can be accessed vie final block. Whenever garbage collection will occur final block will be executed without fail so object can be reachable in that final block.

46: What will be the default values of all the elements of an array defined as an instance variable? (Inter)

It will depend on the 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.

 

46: What is Overloading?

Look Here for the better understanding of Overloading

48: What is Overriding?

Look Here for the better understanding of Overriding

49: Can we Overload Overriden method?

Yes, the Derived class can Overload, overridden method.

50: Can we Override the Main method?

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

51: How can we invoke superclass version of Overriden method?

Super keyword can be used for this purpose. super keyword will invoke the overridden method from superclass.

Syntax: super.methodName()

52: What is Super?

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 cannot be used at the same time.

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

We can avoid method overriding by using final keyword.

Syntax:

public void final methodName(){}

54: Can constructor be inherited?

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

55: What is Casting? (Inter)

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

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

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

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

57: What are different types of access modifiers?

Three type of access modifiers are there

  1. Public
  2. Private
  3. Protected

58: What is Finally & Finalize?

Finally: Keyword 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

59: What is Garbage Collection? How to call garbage collection explicitly? (Inter)

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 requested to garbage collection. It doesn’t force JVM to garbage collect.

60: What are Transient and Volatile Modifiers? (Inter)

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.

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

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.

62: What is the use of Final keyword?

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

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

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

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.

64: Different type of Inner Class?

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

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

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.

66: What is the difference between Integer and Int? (Inter)

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. An integer is an Object while Int is not

67: Can we have an inner class inside method?

Yes, More details can be found here

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

String is immutable, a value assigned once to String cannot be changed while StringBuffer is mutable.

 

Exception

69: What is Checked and Unchecked Exception?

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, a 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.

70: Diff between error and exception?

 

71: What are the different way of handling exception?

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

Interface & Abstract Class FAQ

72: What is Externalization Interface? (Inter)

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

Marker interface doesn’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 knows how to do that.

74: What is the difference between Abstract and Interface? When should we use any of these two? (Inter)

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.

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

76: Why Interface methods can’t be static?

77: Modifiers allowed for the method inside Interface?

  1. public
  2. default
  3. abstract

78: What is an Interface?

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

For the Complete functioning of Interface look here

79: Can we instantiate Interface?

No

80: Does Interface have the member variable

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

81: Modifiers Allowed for method inside Interface?

Only Public & abstract modifier is allowed.

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

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

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

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.

4 Comments Core java interview questions

  1. Yogi

    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.

    Reply
    1. Vivekanand Gautam

      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

      Reply
  2. Rajbeer Singh

    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?

    Reply

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.