Build Winning Teams with iMocha

Company News, Diversity & Inclusion, iMocha Engineering Product Updates Remote Hiring Skills Assessment

All Posts
14 November, 2018

 java_interview_question

Java is used by approximately 10 million developers globally to create apps for the 15 billion Java-enabled devices. It's also utilized to bring cutting-edge technology like Big Data to everyday devices like mobile phones and DVR boxes. 

And hence today, Java is used everywhere! Thus, to help you ace your interview process like a pro, I'll take you over some of the most significant Java Interview Questions and Answers that will help you stand out during the Java knowledge test. I have compiled a list of top Java interview questions which are classified into 5 sections, namely:

Basic Java  Interview Questions

Java OOPs Interview Questions

JDBC Interview Questions

Hibernate Interview Questions

Java Exception and Thread Interview Questions

Basic Java Interview Questions

Q1) Is the Java platform independent?

Yes. Java is a platform-independent language. We can write java code on one platform and run it on another platform. For e.g. we can write and compile the code on windows and can run the generated bytecode on Linux or any other supported platform. This is one of the main features of java.

Q2) What all memory areas are allocated by JVM?

Classloader, Class area, Heap, Stack, Program Counter Register, and Native Method Stack

Q3) Java vs. C ++?

Here are the few differences between Java and C++:

  • Platform dependency – C++ is platform dependent while java is platform-independent
  • No goto support – Java doesn’t support the goto statement while C++ does.
  • Multiple inheritances – C++ supports multiple inheritances while java does not.
  • Multithreading – C++ does not have in-build thread support, on the other hand, java supports multithreading
  • Virtual keyword – C++ has the virtual keyword, it determines if a member function of a class can be overridden in its child class. In Java, there is no concept of the virtual keyword.

Q4) Explain public static void main(String args[])

Here the public is an access modifier, which means that this method is accessible by any class.

  • static – static keyword tells that this method can be accessed without creating the instance of the class. Refer: Static keyword in java
  • void – this main method returns no value.
  • main – It is the name of the method.

String args[] – The args is an array of String types. This contains the command-line arguments that we can pass while running the program.

Q5) What is Javac?

The javac is a compiler that compiles the source code of your program and generates bytecode. In simple words, javac produces the java byte code from the source code written *.java file. JVM executes the bytecode to run the program.

Q6) What is the class?

A class is a blueprint or template or prototype from which you can create the object of that class. A class has a set of properties and methods that are common to its objects.

Q7) What is the base class of all classes?

java.lang.Object is the base class (superclass) of all classes in java.

Q8) What is a wrapper class in Java?

A wrapper class converts the primitive data type such as int, byte, char, boolean, etc. to the objects of their respective classes such as Integer, Byte, Character, Boolean, etc. 

Q9) What is a path and classPath in Java?

Path specifies the location of .exe files. Classpath specifies the location of bytecode (.class files).

Q10) Different Data types in Java.

byte – 8 bit

short – 16 bit

char – 16 bit Unicode

int – 32 bit (whole number)

float – 32 bit (real number)

long – 64 bit (Single precision)

double – 64 bit (double precision)

Q11) What is Unicode?

Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages.

Q12) What are Literals?

Any constant value that is assigned to a variable is called literal in Java. For example –

// Here 101 is a literal

int num = 101

Q13) Dynamic Initialization?

Dynamic initialization is a process in which the initialization value of a variable isn’t known at compile-time. It’s computed at runtime to initialize the variable.

Q14) What is Typecasting in Java?

When we assign a value of one data type to the different data type then these two data types may not be compatible and needs a conversion. If the data types are compatible (for example assigning int value to long) then java does the automatic conversion and does not require casting. However, if the data types are not compatible then they need to be cast for conversion.

For example:

//here in the brackets we have mentioned long keyword, this is casting

double num = 10001.99;

long num2 = (long)num;

Q15) What is an Array?

An array is a collection (group) of a fixed number of items. The array is a homogeneous data structure which means we can store multiple values of the same type in an array but it can’t contain multiple values of different types. For example, an array of int types can only hold integer values.

Q16) What is the BREAK statement in java?

The break statement is used to break the flow sequence in Java.

The break statement is generally used with a switch case data structure to come out of the statement once a case is executed.

It can be used to come out of the loop in Java.

Q17) Arrays can be defined in different ways. Write them down.

int arr[];

int[] arr;

Java OOPs Interview Questions

Q18) Four main principles of OOPS Concepts?

  • Inheritance
  • Polymorphism
  • Data Encapsulation
  • Abstraction

Q19) What is inheritance?

The process by which one class acquires the properties and functionalities of another class is called inheritance. Inheritance brings reusability of code in a java application. Refer: Guide to Inheritance in Java.

Q20) Does Java support Multiple Inheritance?

When a class extends more than one class then it is called multiple inheritances. Java doesn’t support multiple inheritances whereas C++ supports it, this is one of the differences between java and C++. 

Q21) What is Polymorphism and what are the types of it?

Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: static polymorphism and dynamic polymorphism. 

Q22) What is method overriding in Java?

When a subclass (child class) overrides the method of the superclass(parent class) then it is called overriding. To override a method, the signature of the method in the child class must match with the method signature in the parent class. 

Q23) Can we override a static method?

No, we cannot override a static method in Java.

Q24) What is method overloading?

When a class has more than one method with the same name but different numbers, sequences, or types of arguments then it is known as method overloading. 

Q25) Does Java support operator overloading?

Operator overloading is not supported in Java.

CTA6 - hire better

Q26) Can we overload a method by just changing the return type and without changing the signature of the method?

No, We cannot do this. To overload a method, the method signature must be different, return type doesn’t play any role in method overloading.

Q27) Is it possible to overload the main() method of a class?

Yes, we can overload the main() method in Java.

Q28) What is the difference between method overloading and method overriding?

No.

Method Overloading

Method Overriding

1)

Method overloading is used to increase the readability of the program.

Method overriding is used to provide the specific implementation of the method that is already provided by its superclass.

2)

Method overloading is performed within a class.

Method overriding occurs in two classes that have IS-A (inheritance) relationship.

3)

In the case of method overloading, the parameters must be different.

In the case of method overriding, the parameter must be the same.

4)

Method overloading is an example of compile-time polymorphism.

Method overriding is an example of run time polymorphism.

5)

In java, method overloading can't be performed by changing the return type of the method only. The return type can be the same or different in method overloading. But you must have to change the parameter.

The return type must be the same or covariant in method overriding.

 

Q29) What is static and dynamic binding in Java?

Binding refers to the linking of the method calls to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding. 


Q30) What is Encapsulation?

Wrapping the data and code together is known as encapsulation. 


Q31) What is an abstract class in Java?

An abstract class is a class that can’t be instantiated (we cannot create the object of abstract class), we can only extend such classes. It provides the generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. We can achieve partial abstraction using abstract classes, to achieve full abstraction we use interfaces.


Q32) What is Interface in java?

An interface is used for achieving full abstraction. A class implements an interface, thereby inheriting the abstract methods of the interface. 


Q33) What is the difference between abstract class and interface?


1) Abstract classes can have abstract and non-abstract methods. An interface can only have abstract methods.

2) An abstract class can have static methods but an interface cannot have static methods.

3) abstract class can have constructors but an interface cannot have constructors.


Q34) Name the access modifiers that can be applied to the inner classes?


Public, Private, Abstract, Final, Protected.


Q35) What is a constructor in Java?


Constructor is used for creating an instance of a class, they are invoked when an instance of the class gets created. The constructor name and class name should be the same and it doesn’t have a return type. 

Also Read: How iMocha’s Online Java Programming Tests can Help You Save $1200 Per Hire?


Q36) Can we inherit the constructors?

No, we cannot inherit constructors.


Q37) Can we mark constructors final?

No, Constructor cannot be declared final.


Q38) What are default and parameterized constructors?


Default: Constructors with no arguments are known as default constructors, when you don’t declare any constructor in a class, the compiler creates a default one automatically.


Parameterized: Constructors with arguments are known as parameterized constructors.


Q39) Can a constructor call another constructor?


Yes. A constructor can call another constructor of the same class using this keyword. 

For e.g. this() calls the default constructor.

Note: this() must be the first statement in the calling constructor.


Q40) Can a constructor call the constructor of the parent class?


Yes. In fact, it happens by default. A child class constructor always calls the parent class constructor. However, we can still call it using the super keyword. For e.g. super() can be used for calling the superclass default constructor.


Note: super() must be the first statement in a constructor.


Q41)What is THIS keyword used for?


This keyword is a reference to the current object.


Q42) Can THIS keyword be assigned a null value?

No, this keyword cannot have null values assigned to it.


Q43) Explain ways to pass the arguments in Java?


In java, arguments can be passed as call by value – Java only supports the call by value, there is no concept of call by reference in Java.


Q44) What is a static variable in java?


Static variables are also known as class-level variables. A static variable is the same for all the objects of that particular class in which it is declared.


Q45) What is a static block?


A static block gets executed at the time of class loading. They are used for initializing static variables.


Q46) What is a static method?


Static methods can be called directly without creating the instance (Object) of the class. A static method can access all the static variables of a class directly but it cannot access non-static variables without creating an instance of the class.


Q47) Explain super keyword in Java?


super keyword references to the parent class. There are several uses of super keyword:


It can be used to call the superclass(Parent class) constructor.

It can be used to access a method of the superclass that has been hidden by subclass (Calling parent class version, In case of method overriding).

To call the constructor of the parent class.


Q48) Use of final keyword in Java?

  • Final methods – These methods cannot be overridden by any other method.
  • Final variable – Constants, the value of this variable can’t be changed, it’s fixed.
  • Final class – Such classes cannot be inherited by other classes. These type of classes will be used when application required security or someone don’t want that particular class. Final Keyword in Java.

Q49) What is an Object class?

This is a special class defined by java; all other classes are subclasses of the object class. Object class is the superclass of all other classes. Object class has the following methods


objectClone () – to create a new object that is the same as the object being cloned.

boolean equals(Object obj) – determines whether one object is equal to another.

finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalized method to dispose of system resources or to perform other cleanups.

toString () – Returns a string representation of the object.


Q50) What are Packages in Java?

A Package can be defined as a grouping of related types (classes, interfaces, enumerations, and annotations). Refer: Package in Java.

CTA -3

Q51)What is the difference between import java.util.Date and java.util.* ?

The star form (java.util.* ) includes all the classes of that package and that may increase the compilation time – especially if you import several packages. However, it doesn’t have any effect on run-time performance.


Q52) What is static import?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static, to be used in Java code without specifying the class in which the field has been defined. This feature was introduced into the language in version 5.0.


Q53) Garbage collection in java?

Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically, when no references to an object exist for a long time. This whole process is called garbage collection. The whole purpose of Garbage collection is efficient memory management.


Q54) Use of finalize() method in java?

finalize() method is used to free the allocated resource.


Q55) How many times does the garbage collector call the finalize() method for an object?

The garbage collector calls the finalize() method only once for an object.


Q56) What are two different ways to call a garbage collector?

System.gc() OR Runtime.getRuntime().gc().


Q57) Can the Garbage Collection be forced by any means?

No, it’s not possible. you cannot force a garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.

Exception handling Interview Questions


Q58) What is an exception?

Exceptions are abnormal conditions that arise during the execution of the program. It may occur due to wrong user input or wrong logic written by the programmer.


Q59) Exceptions are defined in which java package? OR which package has definitions for all the exception classes?

Java.lang.Exception

This package contains definitions for Exceptions.


Q60) What are the types of exceptions?

There are two types of exceptions: checked and unchecked exceptions.

Checked exceptions: These exceptions must be handled by the programmer otherwise the program would throw a compilation error.

Unchecked exceptions: It is up to the programmer to write the code in such a way as to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.


Q61) What is the difference between Error and Exception?

Error: Mostly a system issue. It always occurs at run time and must be resolved in order to proceed further.

Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.


Q62) What is throw keyword in exception handling?

The throw keyword is used for throwing a user-defined or pre-defined exception.


Q63) What is the throws keyword?

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.


Q64) Difference between throw and throws in Java

Read the difference here: Java – throw vs throws.


Q65) Can static block throw exception?

Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.


Q66) What is a final block?

Finally block is a block of code that always executes, whether an exception occurs or not. Finally, block follows try block or try-catch block.


Q67) ClassNotFoundException vs NoClassDefFoundError?

1) ClassNotFoundException occurs when the loader could not find the required class in the classpath.

2) NoClassDefFoundError occurs when a class is loaded in the classpath, but one or more of the classes which are required by another class, are removed or failed to load by the compiler.


Q68) Can we have a try block without catch or finally block?

No, we cannot have a try block without catch or finally block. We must have either one of them or both.


Q69) Can we have multiple catch blocks following a single try block?

Yes, we can have multiple catch blocks in order to handle more than one exception.


Q70) Is it possible to have the final block without a catch block?

Yes, we can have a try block followed by a final block without even using catch blocks in between.


Q71) When does not a final block does not get executed?

The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.


Q72) Can we handle more than one exception in a single catch block?

Yes, we can do that using an if-else statement but it is not considered a good practice. We should have one catch block for one exception.


Q73) What is a Java Bean?

A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components. 

CTA7 - generic

JDBC Interview Questions


Q74) What exactly is JDBC?


JDBC is a Java API for connecting to a database and running queries on it. To connect to a database, the JDBC API utilizes JDBC drivers. The JDBC API can be used to retrieve tabular data from any relational database.


Q75) What are JDBC statements and how do I use them?


Statements are used in JDBC to deliver SQL commands to the database and to receive data from it. JDBC statements give a number of methods for interacting with the database, including execute(), executeUpdate(), executeQuery, and so on.

There are three types of JDBC statements given in the following table.

Statements

Explanation

Statement

The statement is the factory for the resultset. It is used for general-purpose access to the database. It executes a static SQL query at runtime.

PreparedStatement

The PreparedStatement is used when we need to provide input parameters to the query at runtime.

CallableStatement

CallableStatement is used when we need to access the database stored procedures. It can also accept runtime parameters.


Q76) What is the return type of the method Class.forName()?


The java.lang object is returned by the Class.forName() method.


Class Object. 


Q77) In JDBC PreparedStatement, how can we set a null value?


We can set the null value to an index using the PreparedStatement interface's setNull() function. The method's syntax is listed below.


void setNull(int parameterIndex, int sqlType) throws SQLException


Q78) What advantages does PreparedStatement have over Statement?


The advantages of the PreparedStatement interface over the Statement interface are listed below.

The PreparedStatement is faster than the Statement because the Statement must be compiled each time the code is run, but the PreparedStatement just needs to be compiled once and then executed at runtime.

The statement can only run static queries, but PreparedStatement can run parameterized queries.


Q79) What are the various ResultSet types?


The direction of the reading head and the sensitivity or insensitivity of the result delivered by ResultSet are used to categorize it. A ResultSet can be one of three different types.



Type

Description

ResultSet.TYPE_Forward_ONLY

The cursor can move in the forward direction only.

ResultSet.TYPE_SCROLL_INSENSITIVE

The cursor can move in both the direction (forward and backward). The ResultSet is not sensitive to the changes made by the others to the database.

ResultSet.TYPE_SCROLL_SENSITIVE

The cursor can move in both the direction. The ResultSet is sensitive to the changes made by the others to the database.



Q80) What does the JDBC DriverManager class do?


The DriverManager class serves as a user-to-driver interface. It maintains track of the available drivers and manages the process of connecting a database to the proper driver. The DriverManager class keeps track of which Driver classes have registered themselves by using the DriverManager.registerDriver function ().

Hibernate Interview Questions


Q81) In Hibernate, what is ORM?


Object Relational Mapping is what Hibernate ORM stands for. This is a pattern for transforming data from a relational database to an object that may be utilized in object-oriented programming structures. This technology also makes data retrieval, production, and manipulation much easier.


Q82) What are some of the most significant Hibernate framework interfaces?


The following are the Hibernate core interfaces:

  • Configuration
  • SessionFactory
  • Session
  • Criteria
  • Query
  • Transaction

Q83) In Hibernate, what is a session?


A session is an object that keeps the database and Java object application connected. Persist(), load(), get(), update(), delete(), and other methods in Session can be used to store, retrieve, alter, or delete data from a database. Query, Criteria, and Transaction objects can also be returned via factory methods.


Q84) What are your thoughts on the claim that "a session is a thread-safe object"?

No, Session is not a thread-safe object, which implies that it can be accessed by several threads at the same time.


Q85) Could you explain hibernate's sluggish loading?

Lazy loading is mostly used to improve application performance by assisting in the on-demand loading of child objects.


It's worth noting that this feature has been enabled by default since Hibernate 3. This means that child objects will not be loaded until the parent object has been loaded.


Q86) In Hibernate, how do you make an immutable class?


The following is an example of how to create an immutable class in Hibernate. If we use the XML style of configuration, we can markmutable=false to make a class immutable. True is the default value, indicating that the class was not created by default.


Immutable classes in Hibernate can also be generated with annotations by utilizing the @Immutable annotation.

Q87) In Hibernate, what is the criterion API?


Hibernate's Criteria API allows programmers to create dynamic criteria queries on the persistence database. For constructing dynamic queries, Criteria API is a more powerful and flexible alternative to HQL (Hibernate Query Language) queries.


This API allows you to create criterion query objects programmatically. The org.hibernate. Criteria interface is used for these purposes.  The createCriteria() method of the Hibernate framework's Session interface takes the persistent object's class or entity name as parameters and returns a persistent object instance after the criterion query is run.


Q88) What are many-to-many relationships?


The term "many-to-many association" refers to the existence of many relationships between instances of two items. Consider the case of several students enrolled in different courses and vice versa.


Q89) What does hibernate's session.lock() function do?


To reattach a disconnected object to the session, use the session.lock() method. Because of the session.lock() function does not verify for data synchronization between the database and the object in the persistence context, reattachment may result in data loss.


Q90) What is hibernate caching, and how does it work?


Hibernate caching is a technique for enhancing application performance by pooling objects in the cache and executing queries faster. Hibernate caching is very effective when retrieving data that is used several times. We can access the data from the cache instead of going to the database. As a result, the application's throughput time is lowered.


Q91) When is the hibernate session's merge() method useful?

Existing values can be updated using the Merge() technique. This function is unique in that it produces a copy from the entity object and returns it once the existing values have been modified. This result object is saved in the persistent context, where it is monitored for changes. The object that was used in the first place isn't tracked.


Q92) One-to-One and Many-to-One associations can be used to map collections. What are your thoughts?

False; only One-to-Many and Many-to-Many relationships allow collection mapping.


Q93) Is it possible to make the Entity class final?


No, we shouldn't make the entity class final since hibernate employs proxy classes and objects to load data slowly and only contacts the database when absolutely necessary. The entity bean is extended to achieve this. If an entity class (or bean) is declared final, it cannot be extended, and hence lazy loading is not possible.


Q94) Describe your favorite features of the Hibernate framework.

ORM Tool, Hibernate provides a powerful query language (HQL)

Q95) How can you differentiate Entity Beans and Hibernate.

Entity beans are containers, classes, descriptors. Hibernate is a tool that instantly persists the object tree to a class.

Q96) How does inheritance work in Hibernate? What are the various strategies available to implement it?

Three types of Inheritance: 

  • Table Per Hierarchy
  • Table Per Concrete class
  • Table Per Subclass

Q97) How does Locking work in Hibernate? What are the various locking mechanisms available?

Locking mechanisms are optimistic and pessimistic. 

Q98) What is lazy loading in Hibernate?

This mechanism on entities and their associations by implementing a proxy of classes.

Q99) What are the various fetching strategies available in Hibernate?

Join fetching and Select fetching

Q100) What are the various fetching strategies available in Hibernate?

Join-Fetching and Select Fetchings are the fetchings available in Hibernate. 

Q101) What are the difference between getting () and load() methods in Hibernate?

getting() and load() which are used for fetching data for the assigned identifier. Get() method return null,load() method throws error of object not found type of exception.

Conclusion

With this, we have come to the end of the Java interview questions blog. I hope these Java interview questions and answers will help you conduct and face interviews. In case you have attended any Java interviews in the recent past, do share those interview questions with us at support@imocha.io we’ll answer them.  

If you wish to explore your Java skills, try iMocha's Java programming skills test.CTA5
Neha Jadhav
Neha Jadhav
Neha Jadhav is our in-house expert with over two years of experience in multifaceted roles requiring Customer Service, Quality Assurance, and Data Analytics. She is passionate about gaming, and loves to catch up on everything technical in her free time.

Topics: Tech Recruitment

Related Posts

How iMocha Sets Coding Problems for Skills Assessments

iMocha has the world's largest skills assessment library, with over 2500 questions across various domains. 

Hiring Rust Developers in 2022

According to the Stack Overflow Developer Survey 2021, which polled nearly 80,000 developers, Rust is the most popular programming language for the sixth time in a row. Facebook has joined the Rust Foundation, the organization that is driving the Rust programming language, along with Amazon Web Services, Google, Huawei, Microsoft, and Mozilla to foster the development of Rust and make it a mainstream language of choice for systems programming and far beyond. 

Hire Vue.js Developers: The iMocha Guide to Spot-top candidates

Vue.js is a progressive JavaScript framework that is an approachable, performant and versatile framework for building web user interfaces and single-page applications. Commonly referred to as Vue, it was developed by Evan You and its first version were released in 2014.