8 C
Jaipur
Thursday, January 28, 2021

100 Frequently asked Java Interview Questions and Answers

Must read

Java is becoming the most prominent and widely-used programming language at the moment. So, preparing well for Java interview questions has become essential for every programmer who seeks jobs. In fact, Java is the first secure, class-based, and reliable object-oriented language of the modern world. Java is used in different domains like information technology, banking, financial services, scientific and research community, retail, and the stock market. Various technologies use Java as the important core of their functionalities.

With the increasing usage and popularity, the job opportunity of Java is also increasing. To utilize these lucrative opportunities, you have to face the platform with intelligence and witty answers. To build up the interviewee’s self-confidence, he must have previous knowledge about the question patterns of the job interview and the common  Java interview questions and answers that are usually asked.

Java Interview Questions and Answers


Java can be found all over the web. Whether you are a beginner or an experienced, some commonly asked Java Interview Questions that you are likely to face if trying for the IT world. The following covers the most frequently asked basic Java questions and questions for the experienced, and the answers are provided accordingly to aid for interview preparation.

Java Basic Interview Questions


This section will cover the fundamentals and core concepts of the java programming language. These are the most important Java Interview questions. No matter whether you are attending an interview for an entry-level or mid-level, or top-level java job, you should have a solid understanding of the topics these questions are going to discuss to set yourself apart from others.

Q1. What is Java?


This is a very fundamental java interview question. Here is how to answer it properly: “Java is a user interface design language that is class-based and object-oriented”. The bytecode of Java runs on various operating systems, including Linux, Windows, and macOS. Sun Microsystem developed this high-level programming language.

Java is the programming or software development language that generally, we use for application programming. Windows, mobile applications, and web-based enterprises use java applications. Java architecture does not support unions and structures.  A virtual keyword is not used in this programming language. It uses a single Inheritance.

java programming features

Q2. What makes the Java platform independent?


Java is a  program writing language that can be run on many kinds of operating systems and hardware, and thus it is not dependent on any platform. Java platform is independent as it contains byte codes. The Java compiler transmutes the source code to bytecode. Bytecode is the intermediate language. Any kind of system can be used to operate the byte code.

Any platform is suitable to run Java programs smoothly. Java uses the JVM or Java Virtual Machine, which depends on the operating systems. For different operating systems, different JVM corresponding is used. This is platform dependency, whereas Java operates independently.

Q3: What is an object-oriented program in Java?


When it comes to frequently asked Java interview questions, this question can easily take place in the list. Object-oriented programming is the programming model where the programs are organized around the objects. In the object-oriented program, the object is the real-world entity. It is a programming style that utilizes the objects to function.

The main purpose of the object-oriented program is to bind the data and the functions together. Some concepts of the program-oriented objects are the Class, Inheritance, Polymorphism, Abstraction, Encapsulation, Object, and Message Passing.

Q4: What is considered a Java string pool?


Java String Pool can be interpreted as assembling of Strings which are stored in the heap memory. Java string pool is the storage area. In this area, the strings are kept. String objects are created through the use of a new operator. Many diverse means are used to generate Strings.

The string object is handy for the Java language. In Java, a string is unchallengeable. So the string pool is possible. The string pool does not need any time to create the string. It helps to save space for the Java runtime.

Q5. Explain JDK, JRE, and JVM.


A lot of abbreviations are also asked in the Java interview question. The full meaning of JDK is the Java Development Kit. JDK is a useful tool for packaging Java programs and compiling documents. Java Development Kit contains some development tools. It also contains Java Runtime Environment or JRE. In the Java program, the Java Development Kit is an important technology package.

The full meaning of JRE is the Java Runtime Environment, where the Java bytecodes are carried out. Java Runtime Environment is also named Java RTE. JRE contains the Java Virtual Machine or the JVM, supporting files, and core classes.

Java Virtual Machine, or JVM, is an abstract machine that helps the computer run computer programs. The implementation of JVM is the Java Runtime Environment.

Stack vs. Heap in Java

Q6. Explain the concepts of OOPs


Another question that is asked in the Java interview is about OOPs. The full meaning of OOPs is Object-Oriented programming. This is the programming style. The main ideas of this Object-Oriented Programming are inheritance, abstraction, encapsulation, and polymorphism. To know about the working process of Java, we need to know about these four ideas.

Inheritance: Inheritance helps the programmers to produce new classes. These new classes contain some qualities of the previous classes.

Abstraction: Abstraction is the complex Java programming activity represented through classes, variables, objects, etc.

Encapsulation: Encapsulation is the method of keeping the code and data safe within the classes.

Polymorphism: The concept, Polymorphism, helps Java Programmers to use a single word to mean various things in different contexts.

Q7. Explain Polymorphism and the types of Polymorphism


Types of Polymorphism in Java

Polymorphism is a special and useful concept of Java Programming. This concept enables the Java Programmer to use only one word for getting the meaning of various things in various contexts. This is also called “one interface, many implementations.” The two types of Polymorphism are :

Compile Time Polymorphism–  It is the polymorphism that can be accomplished within compiler time and also termed as Static Polymorphism.

Example: Method Overloading.

Run Time Polymorphism- If the call of an overridden method is accomplished during the runtime, it is called Run Time Polymorphism. Run Time Polymorphism is also called as Dynamic Polymorphism.

You will often find many Java interview questions coming from the fundamentals of Object Oriented Programming method, and this question is surely one of them.

Q8. Explain the Method Overriding in Java


if you search for the best java interview question and answer, then Method Overriding is a must to know. If a method is present both in the parent class and the subclass, a declaration is needed to implement the method in the subclass. This declaration is called Method Overriding. Method overriding is important for the separate and independent implementation of the method in the child class.

The method of the subclass is termed as Method Overriding. This is object-oriented programming. The methods are written in the subclass. The method of the parent method is termed as Method Overridden. Through Method Overriding, the Java program accomplishes the Run Time Polymorphism.

Q9. How does the Inner-Class differ from the Sub-Class?


Candidates must be able to differentiate the classification of Classes in Java interviews. The class which is declared inside the interface is called the Java Inner-Class. The Inner-class is also called the nested class. An Inner-Class can access all the methods of the outer class. Various Inner-Classes can remain within the same class. The inner class possesses its method.

The class which inherits the attributes and methods from the superclasses is called the Java Sub-Class. The Sub-Class is also called the child class. Sub-Class inherits the attributes from the parent class. It can access all the protected and the public methods of its parent class. Sub-Class does not possess its methods.

Constructors in Java

Q10. How are the constructors different from the methods?


The methods are useful for Java programmers and thus asked regularly in Java interviews. These are useful for the representation of the behavior of the object. A method contains various statements that are needed to accomplish some particular tasks. These statements carry the outcomes to the caller. Methods enable us to use the same code again. We do not need to retype the same code again.

New objects need the constructors to start functioning. It does not possess the return type. The class is termed the same as the constructor. A single class consists of various constructors. The sub-class does not contain the constructors. Constructors also possess many classes.

Q11. What is Interface in java?


For taking the best preparation on Java interview questions and answers, then Interface is one of the most important topics where you should give more attention. An interface is the reference type, which contains abstract methods, static methods, constants, default methods, and nested types. The writing of the interface is like the writing of the Java class. All the approaches and means used for the interface are abstract and public and does not comprehend any constructor.

This is the collection of some related methods. An interface is not able to provide the code. It can provide only the signature. The interface is needed to be implemented for accessing the interface method. This implementation class offers the body of the interface method.

Abstract Class in Java

Q12. Define an abstract class in terms of Java.


Java interview questions cover lots under the topic of the class. The class which contains the abstract keyword is called an abstract class. An abstract class contains both abstract and non-abstract methods. The abstract class is not exhibitable and contains static methods and constructors.

An abstract class also contains data members and the main method. The abstract method offers the implementation of the interface. An abstract class falls under a restricted class and to produce new objects. A body is not possessed by the abstract methods that are used in the abstract class.

Q13. Explain StringBuffer and StringBuilder in Java


In the Java interview questions, candidates are often asked to compare two similar but not the same topics in the interview sessions. The peer class, which offers the functionality to the string, is called the StringBuffer. The String Buffer illustrates the writable and the growable character. A StringBuffer contains the characters and the substrings in it. These are inserted in the middle and the end. The StringBuffer grows to provide a place.

A StringBuilder contains the sequence of the characters. A StringBuilder is not threadsafe. The main tasks on a StringBuilder are the insert methods and the append methods. The objects of the StringBuilder are similar to the string objects. A StringBuilder is non-synchronized. It contains the heap memory. It performs very fast.

Q14. Describe the Static Method and Non-Static Method in Java


The Java Static Method belongs to a class. All the instance of a class has access to the Static Method. It is not incorporated with the instance of the class nor to the objects. The static methods can be termed by their class name. It is not able to access non-static data.

The Java methods, which are all non-static, can access The static methods and the static variables. The class object is needed for the non-static method as it varies in the ram. The dynamic binding or runtime is used by the non-static method.

Q15. What is Inheritance in Java? Explain different types of Inheritance?


You can also expect questions that ask you about the explanations and typology. One common query is about Inheritance. The concept to reuse the code as another class adopts one class’s properties is known as Inheritance in Java. The Java Inheritance assists in building up the relationship among the classes. Inheritance occurs between the Super Classes and the Sub Classes.

The Super Class is also known as the Parent Class or the Base Class. The Sub Class is known as the Child Class or the Derived Class. The child class inherits the properties from the Parent Class. This is the principal feature of the Object-Oriented Program.

Hierarchical Inheritance in JavaThere are various types of Inheritance in java. Such as-

Single Inheritance: If a class extends to another class, then it is called Single Inheritance.

Multilevel Inheritance: When the derived class becomes the parent class for the next class, it is called Multilevel Inheritance.

Multiple Inheritance: This type of inheritance concerns any class that inherits from numerous classes.

Hybrid Inheritance: The presence of Single and Multiple Inheritance creates the Hybrid Inheritance. This is the combination of these to Inheritances.

Hierarchical Inheritance: If any Parent Class is inherited by various Child Classes, it is called the Hierarchical Inheritance.

Q16. Explain Get and Post Method in Java


Get Method is a popular and efficient method in sending the data. In the Get method, the data is transmitted in the header. A limited amount of data can be sent through the Get Method. In this method,  the data is apparent in the URL, so it is not completely safe to transform it.

Both the Get Method and the Post Method uses HTTP or HyperText Transfer Protocol to transfer the data. In the Post method, the data is sent in a body. Compared to the Get Method, through the Post Method, many data can be transferred. In the Post Method, the data is not exposed in the URL, so the data are safe.

Q17. Describe package in Java and its advantages


The Java package contains the interfaces, sub-packages, and related classes. The classes and the interfaces are bundled together in the Java package. The directory structures are related to the Java package names. The two types of Java packages are:

  • Build-in package
  • User-defined package

Java, net, io, swing, lang, SQL, util, java, awt, etc., are examples of Build in a Java package. Our created packages are the user-defined packages. Java packages are used to organize the Java classes, sub-packages, and interfaces. It contains some package keywords.

Advantages of Java PackagesTo maintain the Java interfaces and classes, a categorization is needed. Java Packages are used for this classification. Through the categorization, Java packages avoid the clash of names. The Java packages also offer access to protection facilities. Java packages are also useful for controlling the codes.

The Java packages are used for the modularization of the codes. The codes are also reused with the aid of the Java Package. The Java classes also possess some hidden classes. These hidden clauses are only seen within the package. The external classes do not see these. The Java packages maintain the hierarchical orders.

Q18. What is the difference between equals () and == in Java?


The difference between Equals () Method and == in Java is asked regularly in Java interviews. Both of them are used for comparing the objects in Java. Every object of Java possesses a particular location and space. Equals () Method and == are related to this location and space.

Equals () is one kind of method while == is considered as the binary operator. This operator is used to compare the objects and primitives’ memory position and is applied for the default implementation. Whereas, Equals () method analyze the difference between the state of two separate objects. This method also compares the standards of two different objects.

Q19. Describe Java Modifiers and name the type of Access Modifiers that can be found in Java.


Java modifiers are the keywords through which the significance of the variable can be changed. There are two types of modifiers in Java-

Access Modifier: The access modifiers are the keywords that state the approachability of the class, constructor, method, and field. The access level can be changed through the use of the Access Modifier.

Non-Access Modifier: To control the inheritance and capabilities, the Non-Access Modifier is used. This is also used to identify the overriding of the class in the subclass.

The four types of Access Modifiers include:

Private Access Modifier: The access of a Private Access Modifier is limited within the class.

Protected Access Modifiers: The Protected Access Modifier can be accessed within the Package and also outside the package through the use of child class.

Default Access Modifiers: The Default Access Modifier can be accessed only within the Package. It is inaccessible from the exterior.

Public Access Modifiers: The Public Access Modifiers can be accessed from everywhere. It can be accessed within and outside the class and the package.

Q20. What is meant by the final keyword in Java


The keyword which is used as the Non-Accessed Modifier in Java is called the final keyword. This keyword can be used with the class, methods, and variables. The final keyword can be used in various contexts like

final Method: Generally, the methods are overridden by the inherited classes. When the methods are declared as final, then it cannot be overridden anymore.

final Class: In Java, if a class is acknowledged as final, the sub-classes will not extend it anymore. The final Class can extend itself.

final Variable: If the variables are used along with the final keyword, its value will be unchanged.

Association in JavaQ21. What is the Association in terms of Java? Describe the types of associations in java.


The topic of association is most likely to come when you are reading the intermediate level Java interview questions. Association is how two individual objects relate to one another. The relationship between the classes is also described as the “has-a” relationship. It creates a connection through the objects. Every object has its lifecycles. All the objects are independent, and none of the objects belong to any other object. There can be –

  • One one relationship
  • One to many relationships
  • Many to many relationships

The relation between the classes is bi-directional. The association connection reveals how the objects use the functionality of other objects.

Association in Java can be divided into two types-

Aggregation: The Aggregation relation illustrates the “Has-A” relationship. Aggregation Association is the one-way relationship between the classes. The affiliation of these classes is also called a “one-to-one” relationship. In Aggregation Association, the objects are independent. One object does not influence another object.

Composition: The composition Association refers to the “one-to-many” relationship. The objects are not independent here. It is the part-of relationship. In Composition Association, the object influences another object. The objects depend on each other.

Q22. What are Exceptions in Java? What are the keywords used to handle Java Exceptions?


The event that creates problems at the Java program’s runtime is referred to as Exceptions in Java. IOExceptions, ClassNotFoundExceptions, SQLExceptions are some common exceptions in Java. It creates a disturbance in the normal flow of the java programs. To remove this interruption, these exceptions are needed to be handled.

The following keywords are used to handle the runtime errors:

  • finally
  • throw
  • try
  • throws
  • catch

Q23. List Some Build-in Exceptions in Java.


The exception is referred to as the hindrances at the runtime of the Java program. Exceptions interrupt the flow of the program. There are various kinds of Java exceptions. Such as,

  • ClassNotFoundException
  • IOException
  • FileNotFoundException
  • SQLException
  • ArrayIndexOutOfBoundException
  • InturruptedException
  • NoSuchMethodException
  • RunTimeException
  • NullPointerException
  • NumberFormatException
  • NoSuchFieldException
  • StringIndexOutOfBoundsException
  • ArithmaticException
  • ClassNotFoundException

Q24. Describe the Independent Process and the Cooperative Process in Java


At the time of Synchronization, sometimes the processes are independent, and sometimes the processes are influenced by other processes. The process can be categorized into two types:

Independent Process: If the execution of one process does not impact another’s execution, it is called Independent Process.

Cooperative Process: If the execution of one process influences another’s process, it is called Cooperative Process. In Cooperative Process, the execution of one process is impacted by the execution of other processes.

Q25. Describe the features of Java Programming Language


This is the most common Java Interview Question that interviewers like to ask to judge a candidate’s capability. The language of Java programming is very functional and beneficial. This is a very simple language, and it is very easy to learn. The users of Java do not need to worry about safety. Java does not use explicit pointers and is very safe to use. It uses strong memory management.

Java uses the “read-one-write-anywhere” approach. So, we can run the Java programs through every machine. It can be executed everywhere. Java Programing Language is handy because it is a platform-oriented language. Java contains its platform to execute the codes.

Java has a bulk of useful features. Some of them are listed below:

Independent Platform: Java programs can operate on various platforms, and no further alteration is required. The JVM approbates the program to operate on many platforms.

Simplicity: This programming language is user friendly and simple. Java and its codes are easy to learn, read, and write.

Multi-Threading: Multi-threading is the method of executing various threads at one time. Multi-threading is useful for the maximum utilization of the CPU.

Object-Oriented: As an object-oriented coding language, Java possesses features like polymorphism, encapsulation, inheritance, and abstraction.

Q26. What is WORA in Java?


If you are an experienced Java developer, then this type of Java interview questions should be known. The interviewers frequently asked about WORA in the Java interview. The full meaning of WORA is “Write Once, Run Anywhere.” It refers to the capability of the program to run on the various Operating Systems. This is also termed as WORE or “Write Once, Run Everywhere.”

The WORA capable programs are performed in the devices which contain any version of Windows, Android, Linux, Mac OS, HP-UX, Solaris, and NetWare. The devices can be smartphones, a desktop computer, a tablet device, a notebook computer, etc.

Q27. Why does Java not use Pointers?


Pointers are the variables that are used to keep the address of the other variable. C Language uses the pointers, but Java does not use this variable. Pointers are not used in Java for several reasons. Using Pointers is very complex. Simplicity is a prominent feature of Java. So, Java does not use Pointers.

Using the Pointers is not safe. Java offers the reference type. The user feels comfortable dealing with the reference type then using the Pointers. In Java, the JVM automatically accomplishes the distribution of memory. So, there is not any necessity for the Pointers. The pointer performs on the Internet. If Java allows the Pointer, the information can be leaked.

Q28. What are JVM and its importance in Java?


JVM is very significant about Java. In the Java interview, the interviewers frequently asked about the JVM. The full meaning of JVM is Java Virtual Machine. JVM can be described as an abstract machine that offers a runtime environment in which the Java bytecode is executed.

It specifies the performance of Java Virtual Machine. Oracle and many other companies provide their implementation. JVM is considered platform-oriented. It is accessible to many software and hardware companies. Its purpose is to execute other programs.

Q29. Differentiate between Java and C++


This is the most common and frequently asked question in Java Interviews. Both Java and C++ are the programming language but has distinct characters that set them apart. Java is an uncomplicated software design language that is not dependent on any platform. We use Java Programming Language for application programming. It was created as the interpreter to use in the Printing System. Java does not maintenance multiple inheritances. It does not support the operator overloading.

While C++ is a more complicated and higher-level language than JAVA, this programming language is platform-dependent and used for system programming, unlike JAVA. It was designed for application programming and system programming. It supports various inheritances. It also provides operator overloading.

Q30. Differentiate between local and instance variables


Local and instance variables are two types of Java variables. Local variables are those variables that offer local scope only. They are normally used in Java methods, constructors, or blocks. Local variables are not visible. And other materials of your program can’t access them. The best part about having a local variable in your Java code is that other code methods won’t be aware of these local variables.

On the other hand, instrumental variables can be observed from different parts of Java code attached to the objects themselves. Furthermore, Instance variables are defined inside the class, meaning that when a change is made to the variables, it will not influence other instances from that class.

Q31. Mention some differences between Java and other platforms


Here are some major differences between Java and other platforms. Java is a software-only platform that gives the benefit of overly simple data integration. Most of the other platforms, on the other hand, are hardware-based or both software and hardware-based.

Java runs on top of other hardware only platforms; whereas most other platforms can run only the hardware elements.

Java codes are OS independent and can run on any operating system. Hardly any other platforms offer this freedom. Java offers its run-time environment (JRE) and virtual machine (JVM). There is hardly any other programming language that offers this advantage.

Q32. Explain the classloader and its types


ClassLoaders is a Java object. It is a subsystem of a Java virtual machine and is used to load classes. Three classloaders are incorporated in Java.

Bootstrap ClassLoader: Bootstrap Classloader is a superclass of the Extension classloader. It is a machine code that acts upon the JVM instruction. It can load rt.jar file, java. util file, and original Java ClassLoader

Extension ClassLoader: Extension ClassLoader is the child of Bootstrap ClassLoader and parent of System ClassLoader. It can load extensions from the JDK Extension library. Extensions loaded by this classloader are of core java classes.

System ClassLoader: Also known as Application ClassLoader, it is the child classloader of the extension classloader. The system class loader can load files of Java class from the classpath. It is reliable for loading application-level class into a java virtual machine.

Q33. Mention the different access specifiers in Java


Java access specifiers, a.k.a. Visibility specifiers, are the keywords in Java. They are used to determine the accessibility of different Java methods, classes, or variables. Here are four Java access specifiers of Java:

Public Specifiers: Classes, variables, or methods from the same or other packages can be accessed by any classes in Java. The public access specifier gets the highest level of accessibility.

Protected Specifiers: When a method or field is declared protected, it can be accessed by class from the same package or within the same or sub-class of that class only.

Default Specifiers: When there is no access specifier set for any given method, it will naturally set a default specifier. In Default access specifiers, variables, classes, and methods from the same package can be accessed only.

Private Specifiers: Private variables are accessible within the class but not outside the class. Only the inside members are granted permission to reach the variables. Outside members without the control, the inside members cannot access these variables.

Is Java Object-Oriented?Q34. Explain what is meant by wrapper classes in Java.


Wrapper classes do an exciting task of changing primitives into a reference type. We know there are dedicated classes for every primitive data type.

Every primitive data type has a dedicated class for itself. The name “wrapper” was given due to its function of wrapping the primitives into an object that belongs to a particular class. An image is shown below that demonstrates the different primitive types, wrapper class, and constructor argument.

Q35. What elements make up the JDBC API?


This is a common question in Java interviews targeting the more trained interviewee. JDBC API consists of different classes and interfaces. These classes and interfaces are given below –

Classes:

  • Blob
  • Clob
  • DriverManager
  • SQLException
  • Types etc.

Interfaces:

  • Connection
  • CallableStatement
  • DatabaseMetaData
  • PreparedStatement
  • ResultSet
  • ResultSetMetaData
  • Statement etc.

Q36. What are the names of some networks of the Spring framework?


There is various Spring Framework network. A few very important of them are –

  • Spring AOP – Aspect-oriented programming.
  • Spring Context – Dependency injection.
  • Spring Web Module – To create web applications.
  • Spring ORM – ORM tools to support such as Hibernate
  • Spring MVC – Model-View-Controller
  • Spring JDBC – JDBC and DataSource support.
  • Spring DAO –Database operations using DAO pattern

Java Spring Bean Scope

Q37. Elaborate Bean in Spring and Describe the different Scopes of Spring bean list


Spring IoC container manages Beans, which can be told to be the spine of any application based on Spring. In managing, there are tasks like instantiation and assembly. Five scopes are there, which can be defined by Spring beans if broadly differentiated.

Singleton: It is Spring bean’s default scope. Beans are engendered for every container there. As it is not thread-safe, you cannot have shared variables.

Prototype: For every prototype and every bean requested, a new instance will be created.

Request: Although it is similar to Prototype, it has been created especially for web application purposes. For every single HTTP request, a new instance will be created.

Session: For every HTTP session initiated by the container, there will be a session.

Global-session: Global-session creates sessions that are for global beans and applied in Portlet apps.

Q38. How is setter injection in comparison with constructor injection?


Setter Injection Constructor Injection
Just partial injection is possible here. No injection happens in here.
New instances are not needed for changing the property value. New instances are needed for any rectifications or changes.
In the case of both being defined, it overrides the constructor. Setter property is not even touched.
Better in situations where the number of properties is not that high. When there are too many properties, it is better to use constructor injection.


Q39. Describe the process of making an Exception that is customized?


There are different ways to create a custom exception. Here are some easy ways to achieve it.

class New1Exception extends Exception { }

Checked

class NewException extends IOException { }

Checked exception

class NewException extends NullPonterExcpetion { }

Unchecked

Q40. What is considered as a final block? In what circumstance will it fail to work eventually?


It is one kind of block that executes a set of statements, but not individual statements.
Yes, there can be such a case. Finally, the block will not work if System.exit() command is used, or there is a fatal error in the code.

Q41.How to write multiple catch blocks under a single try block?


Multiple catch blocks can be under a single try block if it is run from specific to general. The program below will make it clear.

public class Example {

public static void main(String args[]) {

try {

int a[]= new int[10];

a[10]= 10/0;

}

catch(ArithmeticException e)

{

System.out.println("Arithmetic exception in first catch block");

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Array index out of bounds in second catch block");

}

catch(Exception e)

{

System.out.println("Any exception in third catch block");

}

}

Q42. What is OutOfMemoryError in Java?


Out of Memory Errors in Java

This is a commonly occurring error, so this also appears commonly in Java interview questions and answers. OutofMemoryError is a subclass that falls under java language. This generally happens when JVM runs out of memory to run.

Garbage Collectors in Java

Q43. Compare Checked Exception and Unchecked Exception.


Focus on this one of the widely asked  Java interview questions and answers to be on the safe side while attending any Java job interview for enhancing your chance to make the most out of it.

Checked Exception Unchecked Exception
Checked options extend throwable class except for errors and runtime exception. Unchecked exceptions extend runtime exception.
These are checked during compile-time. Unchecked exceptions remain unchecked during compile-time.
A few examples of the checked option can be – IO Exception, SQL Exception, etc. A few examples of unchecked options can be – Arithmetic Exception, Null Pointer Exception, etc.

Differences between Java throw and throws

Q44. What qualities differentiate throw and throws?


throw keyword throws keyword
It throws exceptions explicitly. An exception is declared by Throws.
You cannot propagate checked exceptions with the throw. It can be done with throws.
Usually followed by throw. Classes follow throws.
Multiple exceptions are not throwable. Multiple exceptions are declarable.

Q45.Describe the exception hierarchy in terms of java.


Checked and unchecked exceptions create the exceptions, and Virtual Machine error and Assertion error create Error to constitute Throwable and then objects. This is the hierarchy of exceptions in Java.

Q46. Explain the dissimilarity between Error and Exception.


Error are symbols of mistakes done in the code. Example – JVM error, out of memory error, etc. Error is not fixable during the compilation time. Exceptions, on the other hand, happens due to wrong input or human error. Example – Filenotfoundexception, Nullpointerexception, etc. This is a basic Java interview question in comparison to experienced.

Q47. What is the code that will remove a Cookie in a JSP?


It is widely asked in Java interview questions and answers. By coding, one can easily delete a cookie in JSP. The code is given below –

Cookie mycook = new Cookie("name1","value1");

response.addCookie(mycook1);

Cookie killmycook = new Cookie("mycook1","value1");

killmycook . set MaxAge ( 0 );

killmycook . set Path ("/");

killmycook . addCookie ( killmycook 1 );

Q48. How is the Hibernate Framework beneficial?


This is a common question asked in a Java interview for experienced. Hibernate Framework in Java can be useful in various ways:

  • Hibernate framework can support JPA and XML annotation, which also makes code execution independent.
  • Boiler-plate code from JDBC manages resources to ease coders focusing on various logics.
  • It offers a strong query language named HQL. HQL is almost like SQL. HQL is 100% object-oriented. This easily understands concepts like association, polymorphism, and inheritance.
  • Being an open-source project, this is a choice that’s more amicable and easier to learn.
  • Java EE frameworks are very much compatible with Hibernate and also very popular.
  • Lazy initialization by proxy objects can be done in this, and the hibernate framework performs queries on a requirement basis.
  • Better performance can be achieved by hibernation cache memory.

Q49. What is Spring? Mention how to deal with Spring MVC Framework.


Spring framework is a container that controls the inversion. It is such a framework which can be used in various Java situation. There are also possible extensions that can be used for making web applications in the Java EE platform. It is very much lightweight, a framework for entire enterprise applications.

Java Database Connectivity: Spring MVC Framework can be dealt with in three ways. They are Controller Based, Global Exception Handler, and Handler Exception Resolver Implementation.

Controller-Based: If you can annotate the existing method with generic Exception Handler annotation, you are handling exception based on the controller.

Global Exception Handler: If you are handling an exception where Spring gives Controller Advice annotation, it is Global Exception Handler.

Handler Exception Resolver implementation: Handler Exception Resolver interface comes from Spring Framework. Coders can use it to compose any global exception handler. It ensures default implementation classes, which is not possible for the methods described before.

Q50. Explain encapsulation in Java?


Encapsulation is considered a potential tool in Java. Interviewers often ask about this question in a Java interview for experienced. With this, one can easily pack his/her data and code together into one single unit. The data is accessible only through the current class. Normally it is kept secret and secluded from the outer world. To encapsulate in one need to,

  • Call the variables as of a private class.
  • Changing the public setter and getter methods will allow observing the values belonging to the variables.

Java object marker interfaceAlthough the interviewers may also ask different types of questions from a wide range of areas, specific topics, such as Java architect, servlet, thread, etc., are more regularly asked. A candidate should focus on those more while preparation. The following questions are suggested for better preparation.

Java Architect Interview Questions


For answering Java Architect Interview Questions correctly, you should have a clear concept of the various processes required to formulate a Java Program. You can expect questions on Byte and Source Code, Java Compilation, JVM, JIT, and Operating System as well.

Q51. What is termed as constructors in Java?


One of the very commonly asked Java architect interview questions is about Java Constructors. A code block is referred to as a constructor. The function of constructors is to start operating the state of an object. The methods are used to show how an object acts. There are two types of constructors-

Default Constructor: A constructor without any argument. A default constructor does not possess any parameter. Every programmer should know this type of Java architect interview questions.

Parameterized Constructor: Argument passable constructor is called Parameterized Constructor. These arguments were created for helping to initialize Java architect interviews. The object is set in motion with the use of the Parameters.

Q52. Differentiate between Hibernate and Java Database Connectivity (JDBC)


In this Java Architect Interview Question, the difference between the Hibernate and the JDBC is frequently asked. Both of these approaches are used to connect between a Java database and a Java application. Hibernate contains the Object Relational Mapping Tool. JDBC does not facilitate its user with the Object Relational Mapping Mechanism.

The JDBC is not scalable like Hibernate. The Hibernate and JDBC programming languages are different from each other. The functionalities of these two programming languages are distinct. The language used for JDBC is a  query that maintains a specific structure. The Hibernate contains the Catching Mechanism, but the JDBC does not provide any caching functionality.

Q53. What is more useful, Hibernate or JDBC?


The interviewers frequently ask this as a Java architect interview question to the interviewee. They may ask the interviewee what he will use between the Hibernate and the JDBC. They ask such questions to examine whether the interviewee knows the minute details about the advanced technologies.

However, Hibernate is more useful than JDBC. It is more flexible than JDBC because it contains HQL features. The programming language of Hibernate is Hibernate Query Language. This is an object-oriented language. If we change the database, the queries will be automatically updated. If we use the JDBC, then we need to update each query separately. The JDBC is hard for the procedure than the Hibernate.

Q54. How does the JDBC DriverManager class function?


All the registered drivers are dealt with in the JDBC DriverManager class. Registering and unregistering can both be done by JDBC DriverManager Class. The factory method of JDBC has the ability to make the instance of Connection as it is wanted. This is a common Java architect interview question and often asked.

Q55. What is meant by the jspDestroy() method?


javax.servlet.jsp.JspPage interface requires the jspDestry() method if a JSP page is needed to be destroyed. This is a useful method to destroy pages in Java and a very common Java architect interview question.

Q56. What sets get and load methods apart?


It is a very common question asked in the Java architect interviews. Few differences between them are given below –

get() load()
get() always returns null if it fails to find the object. load() fetches ObjectNotFoundException if it fails to find the object.
Related to the database. Not related to load().
Always a real object is fetched but not a proxy. Always fetches a proxy object.

Q57. How can Java architects improve applications with database connections and avoid database deadlock?


A java architect should understand and handle issues regarding databases, and thus this question could be asked as one of the Java architect interview questions.

To improve the application with database connection, one can review ORM strategy, if used, and make required changes to tune database cashing. Indexes can be modified with a new structure. Optimizing and rewriting the query would also help in improving the application.

Database deadlock occurs when an excess amount of resources attempts for the locks. A Java architect should know to solve the issue. To avoid the deadlock, a queue of requests should be made to verify each of them, and cursors should be used limitedly so that the tables are not locks. The use of transactions can also help in avoiding issues of database deadlock.

Q58. List some of the essential annotations in the annotation-based Spring configuration.


Interviewees are often asked about this, as it is a popular Java architect interview question. Some important annotations are listed below.

  • @Autowired
  • @PostConstruct
  • @PreDestroy
  • @Qualifier
  • @Required
  • @Resource

Spring Framework for Java Architect Interview Questions

Q59. What are the benefits related to sharding?


Java architect interview questions also include queries about Sharding. Sharding is a way in which sorting tables in a database into machines accordingly. The now separate database are called shards. This method of Sharding improves scalability as it reduces the number of rows in the tables individually. Scaling becomes easier in java application as one just have to add or remove shards to do so.

Q60. How does Spring frameworks aid Java developers?


Spring Framework enterprise applications that are built with java. As a candidate, one is expected to answer this java architect interview question.

The spring framework benefits Java developers in various ways. As Enterprise Java Bean or EJB container is not required, spring is very lightweight. It is used with POJOs and can also be used with a heavy servlet container. This lightweight feature also allows creating enterprise applications with limited core resources.

The efficient and modular architecture of the spring framework allows more choices for classes and packages. It also gives boilerplate code, using components such as templates, which makes development easier.

Java Servlet Interview Questions


When it comes to extending the server’s capabilities, Servlet can play a major role in Java Programming Language. It is used to complete the programming model of Request-Response for hosting dynamic and user-oriented web applications. You should look at the most important Java servelet interview questions to better perform interview sessions.

Q61. Describe Servlet and its types.


Java servlet interview questions are also an important topic to explore in Java interviews. Java servlet is the component of the Java software, which increases the capability of the server. A java servlet can respond to various kinds of petitions.

Types of Servlets for Java servlet interview questions

Generic Servlets: To respond, the client’s request, a Generic Servlet overrides the service() method. This is a protocol-independent Servlet. Two types of arguments are accepted by this service() method-

  • ServletRequest Objects
  • ServletResponse Objects

HTTP Servlet: This is an Abstract class. The Generic Servlet is extended by this. HTTP Servlet does not possess abstract methods. It remains in java.servlet.http.

Q62. Describe the life cycle of a Servlet


Some other Java servlet interview questions include its life-cycle, which can be answered as such. Servlet class is used to respond to network requests. The servlet is needed for the implementation of the web application. From the creation of the destruction, a servlet goes through five stages. The stages are-

  1. Loading
  2. Instantiation
  3. Initialization
  4. Request
  5. Destruction

Packages in Java for servlet interview questions Q63. Differentiate between Forward () Method and SendRedirect () Method in Java.


Forward () Methods are used to deliver similar requests to other sources. The same contents are shifted from one servlet to another servlet with the help of this method. The Forward () Method performs within the server only. Forward () method is the part of Request Dispatcher. Request Dispatcher is the interface of the Servlet.

SendRedirect () Method is used to deliver new requests to the other resources. The sources are JSP, HTML file, or servlet. It works on the client-side. The SendRedirect () Method is functioned to send requests, both within and outside the server, with the  URL bar present in the browser.

This differentiation is also asked in Java servlet interview questions.

Exception Handling in Java servlet interview questionsQ64. Why is  JSP preferred over Servlet technology?


One of the most asked Java servlet interview questions asks about its technology such as JSP.JSP lets you deal with the server-side, which in return, makes the process of generating contents way simpler. On the other hand, Servlet technology deals with the inside codes of websites, which also execute and instantiate Java Classes. An interesting fact is that everything of this happens in the HTML file.

Q65. How many JSP implicit objects are there and name them?


There are 9 JSP implicit objects in the default setup. The list below shows them –

  • Application (Servlet_context)
  • Config (Servlet_Config)
  • Exception (Throwable)
  • Out (Jsp_Writer)
  • Page Object)
  • pageContext (PageContext)
  • Request (HttpServletRequest)
  • Response (HttpServletResponse)
  • Session (HttpSession)

Life-cycle methods for JSP for Java servlet Interview questions

Q66. Mention the life-cycle methods that are related to JSP?


There are 3 different lifecycle methods for a JSP. All of them are described below –

  1. public void jspInit()

– This code is applied for one time only, and the method is the same as the init method of the servlet.

  1. public void _jspService(ServletRequest request,ServletResponse)throws ServletException,IOException

– This code is applied for each request individually, and its method is the same as the service() method of the servlet.

  1. public void jspDestroy()

– This code is also applied only once, just like spending, and the method is very same as the destroy() method of the servlet.

Q67. Describe Request Dispatcher.


The interviewer may ask about request dispatcher as a Java servlet interview question. Request Dispatcher interface is used for communication of servlet of the same context that is inter-servlet where requests are forwarded to resources such as HTML, JSP, or another servlet with the condition that falls under the same application. Request Dispatcher is also used to combine the contents of resources to response. ServletContext getRequestDispatcher(String path) method is used to get this interface with a / and at the start of the path.

2 types of methods used in the interfaces are void forward, which sends requests from one servlet to another, and the other is void include, which includes content received from the resource.

Q68. Compare PrintWriter and ServletOutputStream and explain what happens if we try to get both .in a servlet


Java servlet interview questions may also include this in the questionnaire for selecting the best candidates.

PrintWriter is a class that is character-stream and is used to write information based on a character such as String to the response, and this class is obtained through ServletResponse getWriter().

On the other hand, ServletOutputStream is a class that is byte-stream and is used to write array data to response, and object reference of the class can be attained through the ServletResponse getOutputStream() method.

Q69. Explain what happens if we try to get both PrintWriter and ServletOutputStream in a servlet.


Both PrintWriter and ServletOutputStream instances can not be obtained in the same single servlet. As another method is used for the response, “java.lang.IllegalStateException” with a message will be seen at runtime if one tries to put both in the servlet. You can consider this one of the most frequent Java servlet interview questions.

Q70. What are the functions of the Servlet Container?


Java servlet interview questions can also bring up Servlet containers, which are also called web containers. The servlet container works to manage the resource pool, support for multiple applications, execute garbage collector, hot deployment, perform memory optimizations, provides security configurations, etc. Some functions of the container include:

  • Communication Support: Web client and servlet can have easy communication with the help of servlet container as the server socket is not required to be built to receive or parse request or to generate a response.
  • Lifecycle and Resource Management: The container helps with loading servlets into memory, initializing them also invoking and destroying them as well as resource pooling and management by providing JNDI or a similar utility.
  • Multithreading Support: With the help of the container, time and memory can be saved as the container creates a new thread for each request and gives request and response objects.

Java Thread Interview Questions


Threads are an integral part of the Java programming language. In this modern era, to meet the demand for complex operations and efficient performance, you need to know about java. lang. Thread class. So, Java thread interview questions are also important to judge your capabilities as threads are used to execute parallel tasks and get the CPU’s maximum utilization.

Q71. Define what Java Thread is?


It is one of the basic Java thread interview questions. Java thread is comparatively a very easygoing process. A Java thread refers to a separate way of execution. A multithreaded program is allowed in Java. Multithreading is another form of multitasking. The parts of the multithreaded program can run at the same time. This separate part of the program is called the Thread in Java.

Each Java program contains a thread called the main thread, which is used by JVM. Java Threads are essential for the Java Run-time System. A Java Thread shifts from one state to another state. A Java Thread exists in the following states:

  • New
  • Blocked
  • Terminated
  • Suspended
  • Runnable

Inheritance in Java thread interview questions

Q72.Explain what is meant by Synchronization about Java.


The multithreading process is referred to as synchronization in java. This is the ability to maintain access to various threads. Through the synchronization process, a single thread gets access to shared resources. The Synchronization process is used to avoid consistency problems and to prevent thread interruption.

The synchronization process develops around the monitor or the lock. All the objects contain the lock. If we proclaim any method as synchronized, then it is called the synchronization method. You can expect Java thread interview questions related to synchronization as well.

Q73. What are the types of Synchronization?


The classification is often asked as part of Java thread interview questions. Synchronization is used to control the access of different threads to one resource. It solves the problem of thread interruption. The two types of classification of  Synchronization are:

Process Synchronization: Process Synchronization is the execution of various threads or processes to ensure their particular sequence of actions.

Thread Synchronization: Thread Synchronization is ensuring the fact that one resource is used by one thread. Thread Synchronization happens when multiple threads try to access one resource.

Q74. What are the types of Thread Synchronization?


Java thread interview questions also include this as a topic for candidates. Thread Synchronization is confirming that one resource is used by one thread. When multiple threads try to access one resource, then the Thread Synchronization is used. Thread Synchronization can be categorized into two types:

Mutual Exclusive: When we share our data, our data can be interrupted by other data. Mutual exclusive prevent this interruption. It keeps the thread from interrupting the other threads. Mutual Exclusive performs through the following three ways:

  • Synchronized Method
  • Synchronized Block
  • Static Synchronization

Cooperation: In Java, Cooperation is inter-thread communication.

Q75. What is a Java thread? What are the advantages of a Java thread?


The definition of Java thread is one of the frequently asked Java thread interview questions. Thread is the path in the execution of a program. Every Java program contains a thread, which is the main thread. Every thread has a priority. The higher priority threads are executed before the lower-priority thread. A Java thread has various advantages.

Mentioning the following information may give you an advantage in java interview questions and answers secession. A thread is used to reduce maintenance costs and development time. The thread develops the performances of complex applications. A thread is used in server applications. It improves server applications. It develops the responsiveness of the user interface. It uses multiprocessor systems.

Q76. Describe the usages of a thread


Java thread interview questions can inquire the candidates about the usage of it. A thread is very useful for the application of Java, all of which are threaded. Threads help to operate various processes simultaneously. Different priorities can be set to the threads. The threads which have a high priority are executed fast. The lower-priority threads are executed later.

Through the use of the multithreading process, more than one client can connect to the server simultaneously. It offers concurrent execution and share process with addresses that are alike. Threading also has some challenges. The client can maximize the application up to a certain extent.

Features of Java Threads for interview questionsQ77. What is more useful between The Thread and The Runnable in java?


The usefulness of different threat-related topics is important when you are considering the Java Thread Interview Questions. This is very confusing to choose between the Thread and the Runnable in Java. So, the interviewers frequently ask this question in the Java interview. We cannot extend multiple inheritances because if you extend any Thread Class, you cannot extend another class in Java.

The object-oriented program refers to add new functions, improve and modify behaviors. If we do not want to modify, then we can use the Runnable Interface. It represents the task. The executor or the thread executes the task. The logical separation as Runnable is more useful than the thread. This is very familiar to the Java designers. So they easily accept the Runnable as Task.

Q78. Compare between threads and processes.


Comparison is frequently asked to be dawn between these two as a part of Java thread interview questions.

Thread Process
A subset of the processes can be called a thread. The program has different instances of execution. These are called processes.
Communication can be directly done. Inter-process communication is a must to maintain communication with sibling processes.
Threads exert significant control over other threads that belongs to the same process. Processes exert lever over child processes only.
Any alteration of the main thread impacts the behavior of the others of the same process. Altering the parent process does not change the child processes.
Threads can function in memory spaces that are shared. Processes require separate memory spaces.
Threads are dependent. Processes are independent.

Comparison between threads and blocks for interview questions Q79. Describe what is meant by Thread Priority.


Java thread interview questions can include Thread Priority, which is an int, with variable values ranging from 1-10 as per priority level. Each thread has an individual and specific priority value where the thread with the higher value is preferred during execution before the ones with a lower value. Other than the value, OS-dependent Thread Scheduler is also taken into account.

Q80. How is ThreadLocal used?


You can expect to be asked about the use of ThreadLocals, whose function is to create thread-local variables in Java thread interview questions. Thread-local variables are used to avoid synchronization. The variables are specified to each thread, and can it gets () and set() methods to get the default value or change its value local to Thread. ThreadLocal Instances are open to connecting the state along a thread and are generally in classes of private static fields.

Java Data Structures Interview Questions


Interviewers can ask you Java data structures interview questions to efficiently store and manage data on your computer. Besides, they can also want to know about algorithms and differentiate between primitive and non-primitive data types.

Q81. What is the data structure in Java?


Java data structures interview questions are asked to the candidates. The process of manipulating and organizing the data is called the data structure. This is the method of storing the data on the computer. This is useful for the effective use of the data. Algorithms are used in this java data structure for the manipulation of the data.

To be skilled at Java programs, the programmer needs to learn the relationship between the data structure and the algorithms. They should also know how the Java data structures and the algorithms work together.

Java data structures interview questions

Q82. What is the classification of data structure?


One other Java data structure interview questions are about its classification. The two types of Java data structures are-

Linear Data Structure: All the elements of the Linear Java Data Structure are stationed in chronological order. The elements are arranged in a non-hierarchical way. In the Linear Data Structure, each element follows a predecessor without the first and the last element. The element is also followed by a successor in Java data structures.

Non-Linear Data Structure: Here, the elements disregards any sequential order. The elements of Non-Linear Data Structure are not organized chronologically. The elements are connected with other elements.

Q83. Describe the Storage Structure and the File Structure in Java


This question is often asked after Java data structures interview questions. In a computer, some structures are saved in the main memory. These structures are called the Storage Structure in the Java Structure. The Storage Structure allows the implementation of the data structure. It illustrates the data structure of the computer memory.

The auxiliary structure is called the File Structure. The Storage Structure and the File Structure are separate from each other in the memory space. File Structure illustrates the Storage Structure of the auxiliary memory.

Q84. How does Singly Linked List differ from Doubly Linked List in Java Data Structure?


The distinction between the Singly Linked List and the Doubly Linked List is frequently asked in Java data structures interview questions. The Singly Linked List and the Doubly Linked List are different from each other in their ability to traverse.

The Singly Linked List contains one pointer. In this list, one node is pointed towards the next node. It does not contain any pointer towards the prior node. The Singly Linked List does not allow its users to traverse back, whereas the Doubly Linked List consists of two pointers. It has separate pointers towards the former and the following nodes. It allows its users to negotiate back.

Q85. What operation can be done using different data structures?


This question is often asked as Java data structures interview questions. The data structure can be used to insert new items and delete existing items in collections. The structure makes each data accessible just for once to be processed. The structure also makes it easier to find existing items and sort the data according to the chosen order, numerical, alphanumerical, or other forms.

Java data structures

Q86. What is the Linked list data structure?


A collection of data objects, nodes that are stored without any order are called Linked List. Here, pointers connect each node with its adjacent node. The two fields of a node are the Data field and Link Field.  This question is often asked as Java data structures interview questions as well.

Q87. How is Linked List better than Array?


As Java data structures interview questions, the interviewer can ask the advantages of Link List that Array does not have. During runtime, the size of a linked list can be incremented, which cannot be done in an array. Unlike Array, the link list can be absent from main memory as nodes can be stored in other places and be connected via links in case of limited space.

Memory space limits the element number in the list, whereas an array’s size decides the number of elements in the Array. The dynamic method of storage of List allows it to grow as per demand while the array is stored on the main memory statically where the size must be specified at compile time.

Q88: How can one know about a loop present in the Link list?


Java data structures interview questions can also include tricky questions to judge your knowledge, such as this. A loop can be found using two pointers approach. Simultaneously, one pointer is placed after the processing of 2 nodes the other is placed after each node. If both pointers direct to the same node, the loop must be there as it only happens when a cycle of a linked list happens.

Q89: How is stack data structure different from Queue data structure?


This is one of the Java data structure interview questions that is asked often. The main difference between Stack and Queue is in their order. While Stack is a data structure following LIFO( Last In First Out) order, the Queue data structure follows FIFO((First In First Out) order.

Q90: What makes file structure different from storage structure?


This is another common and easy Java data structure interview question that is asked quite often. The storage structure shows the computer memory’s data structure, whereas the file structure uses auxiliary memory to show the storage structure.

Java Collection Interview Questions


In Java programming language fundamentals, Java collection interview questions can be easily considered one of the most significant pillars. If you attend an interview, you must gain a strong knowledge of collection frameworks to establish yourself as an aspiring Java developer.

Q91. What are the memory areas that are assigned by JVM?


This is one of our most asked Java collection interview questions. There are several types of allocated memory areas by JVM. Here are some:

Class (Method) Area: Class area saves class level structures for per class. Such as the runtime constant pool, method data, code for different methods and fields.

Heap: Heap is the runtime data area of JVM. Here, memory is distributed to the objects.

Stack: Stack is used in Java to reserve frames. Every time methods are mentioned in Java, a new frame is developed. For every thread, there remains a private stack. Stack in Java is also used to store incomplete outputs. Later, these results will be needed to return value for other methods.

Program Counter Register: The program counter (PC) register is used to carry the address of currently available JVM instruction. PC registers are available in non-native methods. In native methods, program counter values are unspecified.

Native Method Stack: Native method stacks are also known as C stacks. Native method stacks hold the native methods in Java applications. However, Java is not used while writing native method stacks.

Q92. What do you mean by Java Collection Framework?


This question is an integral part of the list of most common Java collection interview questions. The object which represents the group of the objects is called the Collection in Java. It offers an architecture for manipulating and storing this group of objects. JDK uses the Collection Framework to reuse the data structure.

JDK 1.2 introduced the Collection Framework. It was developed by Joshua Bloch. It also designed the Collection Framework. It offers various interfaces like Queue, List, Queue, Deque. Java Collection Framework also offers various classes like:

  • LinkedList
  • TreeSet
  • Vector
  • LinkedHashSet
  • PriorityQueue
  • ArrayList

Q93. How is Java Collection Framework beneficial?


Java collection interview questions also include queries about its usefulness. Java Collections are very useful and used in all programming languages. The collection Framework benefits from the facility of interoperability. Through the use of the core collection class, Java collection Framework decreases the development effort.

The collection Framework increases code quality and can be maintained easily.  The collection class performs this with the help of JDK. The collection classes reduce the effort for code maintenance. It also helps us with the facility of reusability.

Q94. What is referred to as the interface in Java?


Regarding java collection interview questions, the interviewers frequently asked about the interface of the Java Collection Framework. Here goes the answer, Java Collection provides various interfaces like List, Set, Map, Queue, Deque. The Set excludes all elements that match with another, and so no element is repeated. It represents the sets. The Map is not able to contain duplicate keywords.

The List includes elements that are alike and the same.  Any element can be accessed from the index of the List. The Collection Interfaces declares the basic methods of the Collections. The Collection Framework is built upon the Collection Interfaces. The Collection Interfaces help to pass the collections of objects.

Now you know at least 50 Java Interview Questions and Answers for your next job interview. Want to better the odds? Read more for more Java Interview Questions and Answers.

Q95. Name some Java Collection framework provided interfaces.


This question is very common and often asked as a part of the java collection interview questions. Java Collection provides various Interfaces like,

  • List Interface
  • Set Interface
  • Map Interface
  • Queue Interface
  • Deque. Interface
  • SortedSet Interface

Description of some basic Interfaces in Java:

List Interface: List Interface refers to a collection of elements. The elements are arranged in sequence in the List Interface. We can add and retrieve elements in order. If we restore the element, it does not influence the sequence of the order.

Set Interface: Set Interface is not able to maintain any order. If we store and restore the element, the order will be affected. It does not allow any elements that match with another.

Map Interface:  The Map Interface adds or restores the elements in the form of a value pair or the key pairs, and this Interface is excluded from Collection Interface

Q96. What is defined as an Iterator?


This question is often asked when it comes to the important Java collection interview questions. Iterator is an interface that gives methods that aid to iterate over any collection. Enumeration is replaced by this interface in Java Collection Framework and, while iteration, it permits omission of elements by the caller from the collection. The iterator design pattern is implemented by a simple and common traversal method through the elements given by the Java collection iterator. “iterator()” method can be used to obtain iterator instance.

Q97. What Collection views does the Map interface provide?


A frequently asked Java collection interview question is about Map Interface, which provides three collection views.

  • Set<K> keySet(): Set view of the keys included in this map is given back. Any changes to the set are also shown on the map, and vice-versa as the set is backed by the map.
  • Collection<V> values(): Collection view of the values included in this map is given back. Any changes to the collection are also shown on the map, and vice-versa as the collection is backed by a map.
  • Set<Map.Entry<K, V>> entrySet(): Set view of the mappings included in this map is given back. Any changes to the set are also shown on the map, and vice-versa as the set is backed by the map.

Q98. What are the different aspects of  Heap Memory and Stack Memory in Java?


Queries about Heap Memory and Stack memory also fall under Java collection interview question.

The objects of the Java program are kept in the Java heap memory. Java Runtime uses the Heap Space of Java. Java Runtime allocates the space to JRE classes and objects. The garbage collections remove the objects without the reference. The objects of heap memory possess global access.

To execute the thread, Java Stack Memory is used. Execution of the thread is the only use of the Stack Memory. Java Stack Memory contains the references of the objects of Heap Memory and the primitive variables. Stack Memory is not globally accessible, rather by a single thread.

Q98. Define Enumset.


As part of the Java collection interview question, one may be asked about EnumSet, which a set used for implementing enum types where all the elements in a set are originated from a specific enum type when created. It is unsynchronized and does not permit null elements. Useful methods such as  copyOf(Collection c), of(E first, E… rest) and complementOf(EnumSet s) are also provided.

Q99: Compare the vector with the Array list in Java.


A vector is a synchronized list interface. It is not good at adding, searching, deleting, and updating as it is synchronized. The insertion order of the vector is not generally used in a non-thread environment.

An array list is unsynchronized, and it is not without unintended interaction or thread-safe. In an array list, several threads are permitted to operate. The performance of the array list is high, as the threads are not required to wait during the performance.

These differences can also be asked if the examiner focuses more on the Java collection interview questions.

Q100. How to distinguish  ArrayList and HashSet in Java?


This is another differentiative question of Java collection interview question. The differences between the Arraylist and HashSet is frequently asked in Java collection interview question. ArrayList refers to the list interface. It permits duplicate values. ArrayList maintains an order based on the index and is backed by the array. It preserves the insertion order. It contains three constructors:

  • ArrayList()
  • ArrayList (Arraylist in Capacity)
  • ArrayList (int collection C)

HashSet refers to the set interface. It does not permit duplicate values. What is a HashSet? It is an object-based collection that does not follow any specific order. It is backed by HashMap. It does not preserve the insertion order.

Wrapping it up!


We hope these 100 Java interview questions, along with their given answers, cover it all and prepare you better, and you have a great interview. We tried our best to make this blog helpful for Java job seekers. If we have missed anything, please comment below. Share it with a friend if you have found it useful. Tell us what kind of interview questions we should cover next!

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article