i Java

Key Points


References


Key Concepts


Java Questions - edureka

https://www.edureka.co/blog/interview-questions/java-interview-questions/

Q1. Explain JDK, JRE and JVM?

JDK vs JRE vs JVM

JDKJREJVM
It stands for Java Development Kit.It stands for Java Runtime Environment.It stands for Java Virtual Machine.
It is the tool necessary to compile, document and package Java programs.JRE refers to a runtime environment in which Java bytecode can be executed.It is an abstract machine. It is a specification that provides a run-time environment in which Java bytecode can be executed.
It contains JRE + development tools.It’s an implementation of the JVM which physically exists.JVM follows three notations: Specification, Implementation, and Runtime Instance.


Q4. Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which are not objects.


Q5. What are wrapper classes in Java?

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.


Q6. What are constructors in Java?

In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:

  1. Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be created by default in case you no other constructor is defined by the user. Its main purpose is to initialize the instance variables with the default values. Also, it is majorly used for object creation. 
  2. Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.


Class has

static variables

static methods

instance variables

instance methods

a main method


Inner vs Nested Class definitions

When a class is defined within a scope of another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class.


Concurrency - object vs class locking

At the heart of concurrency, there lie the concepts of object locking. Locking happens at instance level as well as class level.

  • Object level locking is mechanism when you want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on given instance of the class. This should always be done to make instance level data thread safe.
  • Class level locking prevents multiple threads to enter in a synchronized block in any of all available instances on runtime. This means if in runtime there are 100 instances of DemoClass, then only one thread will be able to execute demoMethod() in any one of the instances at a time, and all other instances will be locked for other threads. This should always be done to make static data thread safe.


2.4. Compare and Swap [CAS] Algorithm

This question is targeted towards mid-level or senior developers. This requires a deep understanding of other concurrent concepts before answering this question. So It is a good way to test deep knowledge in Java concurrency.

What is optimistic and pessimistic locking?
What is compare and swap algorithm?
What is an atomic operation?
How AtomicInteger and AtomicLong works?


2.5. What is Fork/Join framework?

This is not a new concept but is now used in multiple ways since the release of Java 8. Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple enough that it can be solved without further breakups. It’s like a divide-and-conquer algorithm. One important concept to note in this framework is that ideally no worker thread is idle. They implement a work-stealing algorithm in that idle workers steal the work from those workers who are busy.


2.6. What is ThreadPoolExecutor?

In concurrent Java application, creating a thread is an expensive operation. And if you start creating new thread instance everytime to execute a task, application performance will degrade surely. ThreadPoolExecutor solves this problem.

ThreadPoolExecutor separates the task creation and its execution. With ThreadPoolExecutor, you only have to implement the Runnable objects and send them to the executor. It is responsible for their execution, instantiation, and running with necessary threads.

Read how ThreadPoolExecutor solves various problems and how it is used with BlockingQueue.


2.8. How to write a deadlock and resolve in Java

It can come in form of a puzzle. Better be ready for it. The interviewer may test your concurrency knowledge and your deep understanding on wait() and notify() method calls.

Be ready with one deadlock source-code example in your finger-tips. You will need it.


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

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.


Q10. What are the differences between Heap and Stack Memory in Java?

The major difference between Heap and Stack memory are:

FeaturesStackHeap
MemoryStack memory is used only by one thread of execution.Heap memory is used by all the parts of the application.
AccessStack memory can’t be accessed by other threads.Objects stored in the heap are globally accessible.
Memory ManagementFollows LIFO manner to free memory.Memory management is based on the generation associated with each object.
LifetimeExists until the end of execution of the thread.Heap memory lives from the start till the end of application execution.
UsageStack memory only contains local primitive and reference variables to objects in heap space.

Whenever an object is created, it’s always stored in the Heap space.

Packages

provide namespace support to avoid naming conflicts on classes

can be loaded in separate jars with import statements

Control Flow

if else

for

do while

switch  case

Variables used in a switch statement can only be a string, enum, byte, short, int, or char.

break

continue

Data type coercion - explicit and implicit

parseInt  This method is used to get the primitive data type of a certain String.

Character code sets

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

Swing vs AWT for client UI windows

AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

Q24. What is the difference between this() and super() in Java?

In Java, super() and this(), both are special keywords that are used to call the constructor. 

this()super()
1. this() represents the current instance of a class1. super() represents the current instance of a parent/base class
2. Used to call the default constructor of the same class2. Used to call the default constructor of the parent/base class
3. Used to access methods of the current class3. Used to access methods of the base class
4.  Used for pointing the current class instance4. Used for pointing the superclass instance
5. Must be the first line of a block5. Must be the first line of a block


Q29. What is a classloader in Java?

The Java ClassLoader is a subset of JVM (Java Virtual Machine) that is responsible for loading the class files. Whenever a Java program is executed it is first loaded by the classloader. Java provides three built-in classloaders:

  1. Bootstrap ClassLoader
  2. Extension ClassLoader
  3. System/Application ClassLoader

Q15. What is a marker interface?

A Marker interface can be defined as the interface having no data member and member functions. In simpler terms, an empty interface is called the Marker interface. The most common examples of Marker interface in Java are Serializable, Cloneable etc. The marker interface can be declared as follows.

public interface Serializable{ }

Q16. What is object cloning in Java?

Object cloning in Java is the process of creating an exact copy of an object. It basically means the ability to create an object with a similar state as the original object. To achieve this, Java provides a method clone() to make use of this functionality. This method creates a new instance of the class of the current object and then initializes all its fields with the exact same contents of corresponding fields. To object clone(), the marker interface java.lang.Cloneable must be implemented to avoid any runtime exceptions. One thing you must note is Object clone() is a protected method, thus you need to override it.


Servlets Interview Questions  

Q1. What is a servlet?

  • Java Servlet is server-side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
  • The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
  • All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
  • Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.

Servlet - Java Interview Questions - Edureka

Q2. What are the differences between Get and Post methods?

GetPost
Limited amount of data can be sent because data is sent in header.Large amount of data can be sent because data is sent in body.
 Not Secured because data is exposed in URL bar. Secured because data is not exposed in URL bar.
 Can be bookmarked Cannot be bookmarked
 Idempotent Non-Idempotent
 It is more efficient and used than Post It is less efficient and used

Q3. What is Request Dispatcher?

RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response.

There are two methods defined in this interface:

1.void forward()

2.void include()

ForwardMethod - Java Interview Questions - Edureka

IncludeMethod - Java Interview Questions - Edureka

Q4. What are the differences between forward() method and sendRedirect() methods?



forward() methodSendRedirect() method
forward() sends the same request to another resource.sendRedirect() method sends new request always because it uses the URL bar of the browser.
 forward() method works at server side. sendRedirect() method works at client side.
 forward() method works within the server only.sendRedirect() method works within and outside the server.

Q5. What is the life-cycle of a servlet?

There are 5 stages in the lifecycle of a servlet:LifeCycleServlet - Java Interview Questions - Edureka

  1. Servlet is loaded
  2. Servlet is instantiated
  3. Servlet is initialized
  4. Service the request
  5. Servlet is destroyed

Q6. How does cookies work in Servlets?

  • Cookies are text data sent by server to the client and it gets saved at the client local machine.
  • Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
  • HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
  • Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

Q7. What are the differences between ServletContext vs ServletConfig?

The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.

ServletConfigServletContext
Servlet config object represent single servletIt represent whole web application running on particular JVM and common for all the servlet
Its like local parameter associated with particular servletIts like global parameter associated with whole application
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scopeServletContext has application wide scope so define outside of servlet tag in web.xml file.
getServletConfig() method is used to get the config objectgetServletContext() method is  used to get the context object.
for example shopping cart of a user is a specific to particular user so here we can use servlet configTo get the MIME type of a file or application session related information is stored using servlet context object.


Q8. What are the different methods of session management in servlets?

Session is a conversational state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

Some of the common ways of session management in servlets are:

  1. User Authentication
  2. HTML Hidden Field
  3. Cookies
  4. URL Rewriting
  5. Session Management API


SessionManagement - Java Interview Questions - Edureka

In case you are facing any challenges with these java interview questions, please comment your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for a structured training from edureka! Click below to know more.


JDBC Interview Questions 

1. What is JDBC Driver?

JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:

  1. JDBC-ODBC bridge driver
  2. Native-API driver (partially java driver)
  3. Network Protocol driver (fully java driver)
  4. Thin driver (fully java driver)

2. What are the steps to connect to a database in java?

  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection


3. What are the JDBC API components?

The java.sql package contains interfaces and classes for JDBC API.

Interfaces:

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

Classes:

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

4. What is the role of JDBC DriverManager class?

The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

5. What is JDBC Connection interface?

The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

ConnectionInterface - Java Interview Questions - Edureka

6.  What is the purpose of JDBC ResultSet interface?

The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

7. What is JDBC ResultSetMetaData interface?

The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

8. What is JDBC DatabaseMetaData interface?

The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.

9. What do you mean by batch processing in JDBC?

Batch processing helps you to group related SQL statements into a batch and execute them instead of executing a single query. By using batch processing technique in JDBC, you can execute multiple queries which makes the performance faster.

10. What is the difference between execute, executeQuery, executeUpdate?

Statement execute(String query) is used to execute any SQL query and it returns TRUE if the result is an ResultSet such as running Select queries. The output is FALSE when there is no ResultSet object such as running Insert or Update queries. We can use getResultSet() to get the ResultSet and getUpdateCount() method to retrieve the update count.

Statement executeQuery(String query) is used to execute Select queries and returns the ResultSet. ResultSet returned is never null even if there are no records matching the query. When executing select queries we should use executeQuery method so that if someone tries to execute insert/update statement it will throw java.sql.SQLException with message “executeQuery method can not be used for update”.

Statement executeUpdate(String query) is used to execute Insert/Update/Delete (DML) statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language (DML) statements. For DDL statements, the output is 0.

You should use execute() method only when you are not sure about the type of statement else use executeQuery or executeUpdate method.

Q11. What do you understand by JDBC Statements?

JDBC statements are basically the statements which are used to send SQL commands to the database and retrieve data back from the database. Various methods like execute(), executeUpdate(), executeQuery, etc. are provided by JDBC to interact with the database.

JDBC supports 3 types of statements:

  1. Statement: Used for general purpose access to the database and executes a static SQL query at runtime.
  2. PreparedStatement: Used to provide input parameters to the query during execution.
  3. CallableStatement: Used to access the database stored procedures and helps in accepting runtime parameters.

In case you are facing any challenges with these java interview questions, please comment your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for a structured training from edureka!


Java coding interview questions - javacodegeek

Spring Interview Questions 

Q1. What is Spring?

Wikipedia defines the Spring framework as “an application framework and inversion of control container for the Java platform. The framework’s core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.” Spring is essentially a lightweight, integrated framework that can be used for developing enterprise applications in java.

Q2. Name the different modules of the Spring framework.

Some of the important Spring Framework modules are:

  • Spring Context – for dependency injection.
  • Spring AOP – for aspect oriented programming.
  • Spring DAO – for database operations using DAO pattern
  • Spring JDBC – for JDBC and DataSource support.
  • Spring ORM – for ORM tools support such as Hibernate
  • Spring Web Module – for creating web applications.
  • Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.

SpringFramework - Java Interview Questions - Edureka

Q3. List some of the important annotations in annotation-based Spring configuration.

The important annotations are:

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

Q4. Explain Bean in Spring and List the different Scopes of Spring bean.

Beans are objects that form the backbone of a Spring application. They are managed by the Spring IoC container. In other words, a bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

There are five Scopes defined in Spring beans.

SpringBean - Java Interview Questions - Edureka

  • Singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
  • Prototype: A new instance will be created every time the bean is requested.
  • Request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
  • Session: A new bean will be created for each HTTP session by the container.
  • Global-session: This is used to create global session beans for Portlet applications.

Q5. Explain the role of DispatcherServlet and ContextLoaderListener.

DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring bean configuration file and initializes all the beans that have been configured. If annotations are enabled, it also scans the packages to configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.

DispatcherServlet - Java Interview Questions - Edureka

ContextLoaderListener, on the other hand, is the listener to start up and shut down the WebApplicationContext in Spring root. Some of its important functions includes tying up the lifecycle of Application Context to the lifecycle of the ServletContext and automating the creation of ApplicationContext.

ContextLoader - Java Interview Questions - Edureka

Q6. What are the differences between constructor injection and setter injection?

No.Constructor InjectionSetter Injection
 1) No Partial Injection Partial Injection
 2) Doesn’t override the setter property Overrides the constructor property if both are defined.
 3)Creates a new instance if any modification occursDoesn’t create a new instance if you change the property value
 4)  Better for too many properties Better for a few properties.

Q7. What is autowiring in Spring? What are the autowiring modes?

Autowiring enables the programmer to inject the bean automatically. We don’t need to write explicit injection logic. Let’s see the code to inject bean using dependency injection.

  1. <bean id=“emp” class=“com.javatpoint.Employee” autowire=“byName” />  

The autowiring modes are given below:

No.ModeDescription
 1) no this is the default mode, it means autowiring is not enabled.
 2) byName Injects the bean based on the property name. It uses setter method.
 3) byType Injects the bean based on the property type. It uses setter method.
 4) constructor It injects the bean using constructor

Q8. How to handle exceptions in Spring MVC Framework?

Spring MVC Framework provides the following ways to help us achieving robust exception handling.

Controller Based:

We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.

Global Exception Handler:

Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.

HandlerExceptionResolver implementation: 

For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

Q9. What are some of the important Spring annotations which you have used?

Some of the Spring annotations that I have used in my project are:

@Controller – for controller classes in Spring MVC project.

@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples

@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.

@PathVariable – for mapping dynamic values from the URI to handler method arguments.

@Autowired – for autowiring dependencies in spring beans.

@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.

@Service – for service classes.

@Scope – for configuring the scope of the spring bean.

@Configuration, @ComponentScan and @Bean – for java based configurations.

AspectJ annotations for configuring aspects and advices , @Aspect, @Before, @After, @Around, @Pointcut, etc.

Q10. How to integrate Spring and Hibernate Frameworks?

We can use Spring ORM module to integrate Spring and Hibernate frameworks if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.

Also, Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for hibernate boiler-plate code for transaction management. 

Q11. Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:

  1. Programmatic transaction management: In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.
  2. Declarative transaction management: In this, transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.

In case you are facing any challenges with these java interview questions, please comment your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for structured training from edureka!



Hibernate Interview Questions

1. What is Hibernate Framework?

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa.

Hibernate provides a reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use the Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.

Similarly, hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.

2. What are the important benefits of using Hibernate Framework?

Some of the important benefits of using hibernate framework are:

  1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
  2. Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
  3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism, and association.
  4. Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentation and help is easily available in forums.
  5. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
  6. Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
  7. Hibernate cache helps us in getting better performance.
  8. For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

3. Explain Hibernate architecture.

HibernateArchitecture - Java Interview Questions - Edureka

4. What are the differences between get and load methods?

The differences between get() and load() methods are given below.

No.get()load()
 1) Returns null if object is not found.Throws ObjectNotFoundException if an object is not found.
 2) get() method always hit the database. load() method doesn’t hit the database.
 3) It returns a real object, not a proxy. It returns a proxy object.
 4)It should be used if you are not sure about the existence of instance.It should be used if you are sure that the instance exists.

5. What are the advantages of Hibernate over JDBC?

Some of the important advantages of Hibernate framework over JDBC are:

  1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
  2. Hibernate supports inheritance, associations, and collections. These features are not present with JDBC API.
  3. Hibernate implicitly provides transaction management, in fact, most of the queries can’t be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback. 
  4. JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
  5. Hibernate Query Language (HQL) is more object-oriented and close to Java programming language. For JDBC, we need to write native SQL queries.
  6. Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
  7. Hibernate provides option through which we can create database tables too, for JDBC tables must exist in the database.
  8. Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for the connection pool. This is a very important feature in enterprise application and completely missing in JDBC API.
  9. Hibernate supports JPA annotations, so the code is independent of the implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.


Java Interview Questions: JSP

1. What are the life-cycle methods for a jsp?

MethodsDescription
 public void jspInit()It is invoked only once, same as init method of servlet.
public void _jspService(ServletRequest request,ServletResponse)throws ServletException,IOExceptionIt is invoked at each request, same as service() method of servlet.
 public void jspDestroy()It is invoked only once, same as destroy() method of servlet.

2. What are the JSP implicit objects?

JSP provides 9 implicit objects by default. They are as follows:


VariableType
1) out JspWriter
2) request HttpServletRequest
3) response HttpServletResponse
4) config ServletConfig
5) session HttpSession
6) application ServletContext
7) pageContext PageContext
8) page Object
9) exception Throwable

3. What are the differences between include directive and include action?

include directiveinclude action
The include directive includes the content at page translation time.The include action includes the content at request time.
The include directive includes the original content of the page so page size increases at runtime.The include action doesn’t include the original content rather invokes the include() method of Vendor provided class.
 It’s better for static pages. It’s better for dynamic pages.

4. How to disable caching on back button of the browser?

<%
response.setHeader(“Cache-Control”,”no-store”);
response.setHeader(“Pragma”,”no-cache”);
response.setHeader (“Expires”, “0”);                    //prevents caching at the proxy server
%>   

5. What are the different tags provided in JSTL?

There are 5 type of JSTL tags.

  1. core tags
  2. sql tags
  3. xml tags
  4. internationalization tags
  5. functions tags

6. How to disable session in JSP?

  1. <%@ page session=“false” %>   

7.  How to delete a Cookie in a JSP?

The following code explains how to delete a Cookie in a JSP :


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 );

8. Explain the jspDestroy() method.

jspDestry() method is invoked from javax.servlet.jsp.JspPage interface whenever a JSP page is about to be destroyed. Servlets destroy methods can be easily overridden to perform cleanup, like when closing a database connection.

9.  How is JSP better than Servlet technology?

JSP is a technology on the server’s side to make content generation simple. They are document-centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside an HTML template file. It provides the framework for the development of a Web Application.

10. Why should we not configure JSP standard tags in web.xml?

We don’t need to configure JSP standard tags in web.xml because when container loads the web application and find TLD files, it automatically configures them to be used directly in the application JSP pages. We just need to include it in the JSP page using taglib directive.

11. How will you use JSP EL in order to get the HTTP method name?

Using pageContext JSP EL implicit object you can get the request object reference and make use of the dot operator to retrieve the HTTP method name in the JSP page. The JSP EL code for this purpose will look like ${pageContext.request.method}.

In case you are facing any challenges with these java interview questions, please comment on your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for structured training from edureka!

Exception and Thread Java Interview Questions

Q1. What is the difference between Error and Exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you cannot repair them at runtime. Though error can be caught in the catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving the user feedback for entering proper values etc.

Q2. How can you handle Java exceptions?

There are five keywords used to handle exceptions in Java: 

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

Q3. What are the differences between Checked Exception and Unchecked Exception?

Checked Exception

  • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. 
  • Checked exceptions are checked at compile-time.
  • Example: IOException, SQLException etc.

Unchecked Exception

  • The classes that extend RuntimeException are known as unchecked exceptions. 
  • Unchecked exceptions are not checked at compile-time.
  • Example: ArithmeticException, NullPointerException etc.

Q4. What purpose do the keywords final, finally, and finalize fulfill? 

Final:

Final is used to apply restrictions on class, method, and variable. A final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed. Let’s take a look at the example below to understand it better.


class FinalVarExample {
public static void main( String args[])
{
final int a=10; // Final variable
a=50; //Error as value can't be changed
}


Finally

Finally is used to place important code, it will be executed whether the exception is handled or not. Let’s take a look at the example below to understand it better.

class FinallyExample {
public static void main(String args[]){
try {
int x=100;
}
catch(Exception e) {
System.out.println(e);
}
finally {
System.out.println("finally block is executing");}
}}
}

Finalize

Finalize is used to perform clean up processing just before the object is garbage collected. Let’s take a look at the example below to understand it better.


class FinalizeExample {
public void finalize() {
System.out.println("Finalize is called");
}
public static void main(String args[])
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1= NULL;
f2=NULL;
System.gc();
}
}

 Q5. What are the differences between throw and throws? 

throw keywordthrows keyword
Throw is used to explicitly throw an exception.Throws is used to declare an exception.
Checked exceptions can not be propagated with throw only.Checked exception can be propagated with throws.
Throw is followed by an instance.Throws is followed by class.
Throw is used within the method.Throws is used with the method signature.
You cannot throw multiple exceptionYou can declare multiple exception e.g. public void method()throws IOException,SQLException.

Q6. What is exception hierarchy in java?

The hierarchy is as follows:

Throwable is a parent class of all Exception classes. There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends Exception class whereas errors are further classified into Virtual Machine error and Assertion error.

ExceptionHierarchy - Java Interview Questions - Edureka

Q7. How to create a custom Exception?

To create you own exception extend the Exception class or any of its subclasses.

  • class New1Exception extends Exception { }               // this will create Checked Exception
  • class NewException extends IOException { }             // this will create Checked exception
  • class NewException extends NullPonterExcpetion { }  // this will create UnChecked exception

Q8. What are the important methods of Java Exception Class?

Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable.

  1. String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.
  2. String getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
  3. Synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.
  4. String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.
  5. void printStackTrace() – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as an argument to write the stack trace information to the file or stream.

Q9. What are the differences between processes and threads?

 ProcessThread
DefinitionAn executing instance of a program is called a process.A thread is a subset of the process.
CommunicationProcesses must use inter-process communication to communicate with sibling processes.Threads can directly communicate with other threads of its process.
ControlProcesses can only exercise control over child processes.Threads can exercise considerable control over threads of the same process.
ChangesAny change in the parent process does not affect child processes.Any change in the main thread may affect the behavior of the other threads of the process.
MemoryRun in separate memory spaces.Run in shared memory spaces.
Controlled byProcess is controlled by the operating system.Threads are controlled by programmer in a program.
DependenceProcesses are independent.Threads are dependent.

Q10. What is a finally block? Is there a case when finally will not execute?

Finally block is a block which always executes a set of statements. It is always associated with a try block regardless of any exception that occurs or not. 
Yes, finally will not be executed if the program exits either by calling System.exit() or by causing a fatal error that causes the process to abort.

Q11. What is synchronization?

Synchronization refers to multi-threading. A synchronized block of code can be executed by only one thread at a time. As Java supports execution of multiple threads, two or more threads may access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in sync. Synchronization avoids memory consistency errors caused due to inconsistent view of shared memory. When a method is declared as synchronized the thread holds the monitor for that method’s object. If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor.

Synchronization - Java Interview Questions - Edureka

 Q12. Can we write multiple catch blocks under single try block? 

Yes we can have multiple catch blocks under single try block but the approach should be from specific to general. Let’s understand this with a programmatic example.

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

Q13. What are the important methods of Java Exception Class?

Methods are defined in the base class Throwable. Some of the important methods of Java exception class are stated below. 

  1. String getMessage() – This method returns the message String about the exception. The message can be provided through its constructor.
  2. public StackTraceElement[] getStackTrace() – This method returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack whereas the last element in the array represents the method at the bottom of the call stack.
  3. Synchronized Throwable getCause() – This method returns the cause of the exception or null id as represented by a Throwable object.

  4. String toString() – This method returns the information in String format. The returned String contains the name of Throwable class and localized message.
  5. void printStackTrace() – This method prints the stack trace information to the standard error stream. 

Q14. What is OutOfMemoryError in Java?

OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of memory.

Q15. What is a Thread?

A thread is the smallest piece of programmed instructions which can be executed independently by a scheduler. In Java, all the programs will have at least one thread which is known as the main thread. This main thread is created by the JVM when the program starts its execution. The main thread is used to invoke the main() of the program.

Q16. What are the two ways to create a thread?

In Java, threads can be created in the following two ways:- 

  • By implementing the Runnable interface.
  • By extending the Thread

Q17. What are the different types of garbage collectors in Java?

Garbage collection in Java a program which helps in implicit memory management. Since in Java, using the new keyword you can create objects dynamically, which once created will consume some memory. Once the job is done and there are no more references left to the object, Java using garbage collection destroys the object and relieves the memory occupied by it. Java provides four types of garbage collectors:

  • Serial Garbage Collector
  • Parallel Garbage Collector
  • CMS Garbage Collector
  • G1 Garbage Collector


Difference between Thread sleep and wait

The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.



More Java Questions - self test


4.1. Spring Core Interview Questions

I have tried to collect some top spring core interview questions which you face into your next technical interview e.g.

What is Inversion of Control (IoC) and Dependency Injection (DI)?
Difference between BeanFactory and ApplicationContext?
What is Spring Java-Based Configuration?
Explain Spring Bean lifecycle?
What are different Spring Bean Scopes?
Are Singleton beans thread safe in Spring Framework?
Explain different modes of bean autowiring?
Explain @Qualifier annotation with example?
Difference between constructor injection and setter injection?
Name some of the design patterns used in Spring Framework?

4.2. Spring AOP Interview Questions

Spring AOP (Aspect Oriented Programming) compliments OOPs in the sense that it also provides modularity. In OOPs, key unit is Objects, but in AOP key unit is aspects or cross-cutting concerns such as logging and security. AOP provides the way to dynamically add the cross-cutting concern before, after or around the actual logic using simple pluggable configurations

Go through these most asked AOP interview questions-

Difference between concern and cross-cutting concern?
What are the available AOP implementations?
What are the different advice types in spring AOP?
What is Spring AOP Proxy?
What is Joint point and Point cut?
What is aspect weaving?

4.3. Spring MVC Interview Questions

These Spring MVC interview questions and answers have been written to help you prepare for the interviews and quickly revise the concepts in general. I will strongly suggest you to go deeper into each concept if you have extra time. In general, you should be able to answer these questions-

What is MVC Architecture?
What is DispatcherServlet and ContextLoaderListener?
How to use Java based configuration?
How can we use Spring to create Restful Web Service returning JSON response?
Difference between <context:annotation-config> vs <context:component-scan>?
Difference between @Component, @Controller, @Repository & @Service annotations?
How does Spring MVC provide validation support?
What is Spring MVC Interceptor and how to use it?
How to handle exceptions in Spring MVC Framework?
How to achieve localization in Spring MVC applications?

5. Test Your Knowledge
5.1. Real Java interview questions asked for Oracle Enterprise Manager Project

So far you have been learning all different concepts in Java which can come in front of you in form of interview questions. It’s time to see whether you are prepared or not. Go through some real questions asked from Sreenath Ravva, in his interview with Oracle Corporation.

Can you just start telling about your self and your project?
What is abstraction and encapsulation in java ?
Method Overloading rules?
Widening and narrowing in java?
Can I have only try block in code?
Threads : producer and consumer problem?
Why wait(), notify() and notifyAll() are defined in Object class?
Can we override wait() or notify() methods?
Difference between wait(), sleep() and yield()?
Explain about join() method in thread class?
Have you faced out of memory error? If yes how you fixed ? Tell different scenarios why it comes?
Database connection leakage?
Write a program to swap two numbers with out using third variable?
Write a program to sort an array and remove duplicates?
Write a program on Singleton?
Write a program to merge two arrays?
What is the use of final and finally keywords?
Can I declare class as static or private?
Why you want to change the company?

Java Questions - softwaretestinghelp

https://www.softwaretestinghelp.com/core-java-interview-questions/

What are the features in JAVA?

Ans: Features of Java:

  • Oops concepts
    • Object-oriented
    • Inheritance
    • Encapsulation
    • Polymorphism
    • Abstraction
  • Platform independent: A single program works on different platforms without any modification.
  • High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT converts the bytecode into machine language and then JVM starts the execution.
  • Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which is called main thread. The user can create multiple threads by extending the thread class or by implementing Runnable interface.

Q #6) What is meant by Local variable and Instance variable?

Ans: Local variables are defined in the method and scope of the variables that have existed inside the method itself.

An instance variable is defined inside the class and outside the method and scope of the variables exist throughout the class.

Q #7) What is a Class?

Ans: All Java codes are defined in a class. A Class has variables and methods.

Variables are attributes which define the state of a class.

Methods are the place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy the particular requirement.

Example:

public class Addition{ //Class name declaration
int a = 5; //Variable declaration
int b= 5;
public void add(){ //Method declaration
int c = a+b;
} }

Classes can extend other classes

Classes can implement 1 or more interfaces


Q #9)What are the Oops concepts?

Ans: Oops concepts include:

  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Interface

What other ways can objects work together ???

association

  • composition
  • collaboration

What is encapsulation useful for?

  • provides controlled access to object variables limiting uncontrolled updates
  • accessor methods read and write variables instead

What is polymorphism?

  • multiple versions or types of an object. a group of people are unique instances of person. the request "eat lunch" is implemented differently by everyone but simple to program ( vs using case or if statements for each different lunch chosen )

What is inheritance?

  • Java is single inheritance vs multiple. You can use interfaces to add additional behavior to a class if needed.

What are interfaces?

  • a definition of what a class should ( behavior and state ) without an implementation
  • In Java, a Table interface can be implemented by many different classes
  • Easy way to find solutions is too look for interfaces by name and then find implementors


Methods

  • static methods - accessed on the class
  • instance methods - accessed on the object
  • method access levels
    • public - any other class can access
    • protected - member accessed by any class in package or subclasses in other packages
    • none - package level access
    • private - only classes in the same hierarchy
  • override a method - a subclass redefines a method from a superclass
  • overloaded methods - multiple methods with the same name but different signatures in a class

Final - a variable, a method or a class can all be Final ( not allowed to change )


Lambda Methods

first class objects ( can be defined, assigned to a variable, returned as an argument, passed as a parm )

anonymous methods similar to inner classes


error handling

try - catch - finally blocks

use throws keyword on a method if an error will be propagated ( vs handled )

  • The normal flow of the execution won’t be terminated if exception got handled
  • We can identify the problem by using catch declaration
  • can propagate a more meaningful error than the one thrown in the method


	try{
	//Risky codes are surrounded by this block
	}catch(Exception e){
	//Exceptions are caught in catch block
    e.printStackTrace();
	}

Q #32) What are the types of Exceptions?

Ans: Two types of Exceptions are explained below in detail.

Checked Exception:

These exceptions are checked by the compiler at the time of compilation. Classes that extend Throwable class except Runtime exception and Error are called checked Exception.

Checked Exceptions must either declare the exception using throws keyword (or) surrounded by appropriate try/catch.

E.g. ClassNotFound Exception

Unchecked Exception:

These exceptions are not checked during the compile time by the compiler.  The compiler doesn’t force to handle these exceptions.

It includes:

  • Arithmetic Exception
  • ArrayIndexOutOfBounds Exception

Interfaces

Interfaces define added function for a class to implement

  • All the methods in the interface are internally public abstract void.
  • All the variables in the interface are internally public static final that is constants.
  • Classes can implement the interface and not extends.
  • The class which implements the interface should provide an implementation for all the methods declared in the interface.

Abstract class for subclasses to fully implement any abstract methods - templates for subclasses

Ans: We can create the Abstract class by using “Abstract” keyword before the class name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a concrete class.

Abstract method:

The method which has only the declaration and not the implementation is called the abstract method and it has the keyword called “abstract”. Declarations are the ends with a semicolon.


Array vs ArrayList

Arrays declared with a size;

arrays can be copied etc

array elements addressed by index

def ar1 = { "one", "two", "three" }; 
ar1[1] = 2;


ArrayList is a type of list

growable with add method

ArrayList myList = new ArrayList(); 
myList.add("one");

String, StringBuffer, StringBuilder

String

each string value is stored in the String pool

String s1 = "this is an immutable string";
s1 = "now a new string value";

StringBuffer is an object that has methods to add, append, toString etc

StringBuffer sb = new StringBuffer();
sb.add( "now a new string value");

StringBuilder is a faster implementation of StringBuffer that is not synchronized

String s1 = "this is an immutable string";
s1 = "now a new string value";


HashMap vs HashTable

HashMap

HashMap methods are not synchronized

Iterator used to iterate the values

allows a null key, null values

HashTable

HashTable methods are synchronized, thread-safe

enumerator used to iterate the values

no null keys or values


What is the difference between an IdentityHashMap and a WeakHashMap

https://www.quora.com/What-is-the-difference-between-an-IdentityHashMap-and-a-WeakHashMap-in-Java

The main difference is that IdentityHashMap uses == operator when comparing keys and values, instead of equals method used by WeakHashMap, or any other Map implementation for that matter. That means two keys in IdentityHashMap K1 and K2 are considered equal if and only if K1==K2. For a WeakHashMap or any other Map implementation for that matter it is K1.equals(K2).

IdentityHashMap is not a general purpose Map implementation, it intentionally violates the general contract, which specifies usage of equals method when comparing objects.



HashSet vs TreeSet

HashSet

elements stored in random order

TreeSet

elements maintained in sorted order


Collection Types

collections used to: search, sort, update, insert, delete

Interfaces:

  • Collection
  • List
  • Set
  • Map
  • Sorted Set
  • Sorted Map
  • Queue

Classes:

  • Lists:
  • Array List
  • Vector
  • Linked List

Sets:

  • Hash set
  • Linked Hash Set
  • Tree Set

Maps:

  • Hash Map
  • Hash Table
  • Tree Map
  • Linked Hashed Map

Queue:

  • Priority Queue


Difference between Ordered and Sorted Collections

Ordered:

It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the values from the collection in a specific order.

Sorted:

Sorting mechanism can be applied internally or externally so that the group of objects sorted in a particular collection is based on properties of the objects.


Vector:

It is same as Array List.

  • Vector methods are synchronized.
  • Thread safety.
  • It also implements the Random Access.
  • Thread safety usually causes a performance hit.


Linked List:

  • Elements are doubly linked to one another.
  • Performance is slow than Array list.
  • Good choice for insertion and deletion.
  • Maintains the insertion order and accepts the duplicates.
  • In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.
public class Fruit {
public static void main (String [ ] args){
Linkedlist <String> names = new linkedlist <String> ( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}


Sets and HashSet

Ans: Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not.

Hash Set:

  • Unordered and unsorted.
  • Uses the hash code of the object to insert the values.
  • Use this when the requirement is “no duplicates and don’t care about the order”.

Linked Hash set:

  • An ordered version of the hash set is known as Linked Hash Set.
  • Maintains a doubly-Linked list of all the elements.
  • Use this when the iteration order is required.

Tree Set:

  • It is one of the two sorted collections.
  • Uses “Read-Black” tree structure and guarantees that the elements will be in an ascending order.
  • We can construct a tree set with the constructor by using comparable (or) comparator.


Map Types

Ans: Map cares about unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like set, Map also uses “equals ( )” method to determine whether two keys are same or different.

HashMap:

  • Unordered and unsorted map.
  • Hashmap is a good choice when we don’t care about the order.
  • It allows one null key and multiple null values.
  • Duplicate keys not allowed
Public class Fruit{
Public static void main(String[ ] args){
HashMap<Sting,String> names =new HashMap<String,String>( );
names.put(“key1”,“cherry”);
names.put (“key2”,“banana”);
names.put (“key3”,“apple”);
names.put (“key4”,“kiwi”);
names.put (“key1”,“cherry”);
System.out.println(names);
}
 }


HashTable:

  • Like vector key, methods of the class are synchronized.
  • Thread safety and therefore slows the performance.
  • Doesn’t allow anything that is null.


 Linked Hash Map:

  • Maintains insertion order.
  • Slower than Hash map.
  • Can expect a faster iteration.

TreeMap:

  • Sorted Map.
  • Like Tree set, we can construct a sort order with the constructor.
public class Fruit{
public static void main(String[ ]args){
TreeMap<Sting,String> names =new TreeMap<String,String>( );
names.put(“key1”,“cherry”);
names.put(“key2”,“banana”);
names.put(“key3”,“apple”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
}

Q #30) Explain the Priority Queue.

Ans: Queue Interface

Priority Queue: Linked list class has been enhanced to implement the queue interface. Queues can be handled with a linked list. Purpose of a queue is “Priority-in, Priority-out”.

Hence elements are ordered either naturally or according to the comparator. The elements ordering represents their relative priority.


Q #38) What is a Thread?

Ans: In Java, the flow of a execution is called Thread. Every java program has at least one thread called main thread, the Main thread is created by JVM. The user can define their own threads by extending Thread class (or) by implementing Runnable interface. Threads are executed concurrently.

Example:

public static void main(String[] args){//main thread starts here
);

Q #39) How do you make a thread in Java?

Ans: There are two ways available in order to make a thread.

#1) Extend Thread class:

Extending a Thread class and override the run method. The thread is available in java.lang.thread.

Example:

Public class Addition extends Thread {
public void run () {
} }

The disadvantage of using a thread class is that we cannot extend any other classes because we have already extend the thread class. We can overload the run () method in our class.

#2) Implement Runnable interface:

Another way is implementing the runnable interface. For that we should provide the implementation for run () method which is defined in the interface.

Example:

Public class Addition implements Runnable {
public void run () {
}
}

Q #40) Explain about join () method.

Ans: Join () method is used to join one thread with the end of the currently running thread.

Example:

public static void main (String[] args){
Thread t = new Thread ();
t.start ();
t.join ();}

From the above code, the main thread started the execution. When it reaches the code t.start() then ‘thread t’ starts the own stack for the execution. JVM switches between the main thread and ‘thread t’.

Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task, then only main thread started the execution.

It is a non-static method. Join () method has overloaded version. So we can mention the time duration in join () method also “.s”.

Q #41) What does yield method of the Thread class do?

Ans: A yield () method moves the currently running thread to a  runnable state and allows the other threads for execution. So that equal priority threads have a chance to run. It is a static method. It doesn’t release any lock.

Yield () method moves the thread back to the Runnable state only, and not the thread to sleep (), wait () (or) block.

Example:

public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
Thread.yield();
}  }


Q #42) Explain about wait () method.

Ans: wait () method is used to make the thread to wait in the waiting pool. When a wait () method is executed during a thread execution then immediately the thread gives up the lock on the object and goes to the waiting pool. Wait () method tells the thread to wait for a given amount of time.

Then the thread will wake up after notify () (or) notify all () method is called.

Wait() and the other above-mentioned methods do not give the lock on the object immediately until the currently executing thread completes the synchronized code. It is mostly used in synchronization.

public static void main (String[] args){
Thread t = new Thread ();
t.start ();
Synchronized (t) {
Wait();
}
}


Q #43) Difference between notify() method and notifyAll() method in Java.

Ans: Given below are few differences between notify() method and notifyAll() method

notify()notifyAll()
This method is used to send a signal to wake up a single thread in the waiting pool.This method sends the signal to wake up all the threads in a waiting spool.

Q #44) How to stop a thread in java? Explain about sleep () method in a thread?

Ans: We can stop a thread by using the following thread methods.

  • Sleeping
  • Waiting
  • Blocked

Sleep:

Sleep () method is used to sleep the currently executing thread for the given amount of time. Once the thread is wake up it can move to the runnable state. So sleep () method is used to delay the execution for some period.

It is a static method.

Example:

Thread. Sleep (2000)

So it delays the thread to sleep 2 milliseconds. Sleep () method throws an uninterrupted exception, hence we need to surround the block with try/catch.

public class ExampleThread implements Runnable{
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
} }

Q #45) When to use Runnable interface Vs Thread class in Java?

Ans: If we need our class to extend some other classes other than the thread then we can go with the runnable interface because in java we can extend only one class.

If we are not going to extend any class then we can extend the thread class.

Q #46) Difference between start() and run() method of thread class.

Ans: Start() method creates new thread and the code inside the run () method is executed in the new thread. If we directly called the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method.


Q #47) What is Multi-threading?

Ans: Multiple threads are executed simultaneously. Each thread starts their own stack based on the flow (or) priority of the threads.

Example Program:

public class MultipleThreads implements Runnable
{
public static void main (String[] args){//Main thread starts here
Runnable r = new runnable ();
Thread t=new thread ();
t.start ();//User thread starts here
Addition add=new addition ();
}
public void run(){
go();
}//User thread ends here
} 



Q #48) Explain thread life cycle in Java.

Ans: Thread has the following states:

  • New
  • Runnable
  • Running
  • Non-runnable (Blocked)
  • Terminated
  • New:

In New state, Thread instance has been created but start () method is not yet invoked. Now the thread is not considered alive.

  • Runnable:

The Thread is in runnable state after invocation of the start () method, but before the run () method is invoked. But a thread can also return to the runnable state from waiting/sleeping. In this state the thread is considered alive.

  • Running:

The thread is in running state after it calls the run () method. Now the thread begins the execution.

  • Non-Runnable(Blocked):

The thread is alive but it is not eligible to run. It is not in runnable state but also, it will return to runnable state after some time.

Example: wait, sleep, block.

  • Terminated :

Once the run method is completed then it is terminated. Now the thread is not alive.


Q #49) What is Synchronization?

Ans: Synchronization makes only one thread to access a block of code at a time. If multiple thread accesses the block of code, then there is a chance for inaccurate results at the end. To avoid this issue, we can provide synchronization for the sensitive block of codes.

The synchronized keyword means that a thread needs a key in order to access the synchronized code.

Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can access a synchronized method only if the thread can get the key to the objects lock.

For this, we use “Synchronized” keyword.

Example:


Q #51) What is meant by Serialization?

Ans: Converting a file into a byte stream is known as Serialization. The objects in the file is converted to the bytes for security purposes. For this, we need to implement java.io.Serializable interface. It has no method to define.

Variables that are marked as transient will not be a part of the serialization. So we can skip the serialization for the variables in the file by using a transient keyword.

Q #52) What is the purpose of a transient variable?

Ans: Transient variables are not part of the serialization process. During deserialization, the transient variables values are set to default value. It is not used with static variables.

Example:

transient int numbers;

Q #53) Which methods are used during Serialization and Deserialization process?

Ans: ObjectOutputStream and ObjectInputStream classes are higher level java.io. package. We will use them with lower level classes FileOutputStream and FileInputStream.

ObjectOutputStream.writeObject —->Serialize the object and write the serialized object to a file.

ObjectInputStream.readObject —> Reads the file and deserializes the object.

To be serialized, an object must implement the serializable interface. If superclass implements Serializable, then the subclass will automatically be serializable.

Q #54) What is the purpose of a Volatile Variable?

Ans: Volatile variable values are always read from the main memory and not from thread's cache memory. This is used mainly during synchronization. It is applicable only for variables.

Example:

volatile int number;

Q #55) Difference between Serialization and Deserialization in Java.

Ans: These are the difference between serialization and deserialization in java:

SerializationDeserialization
Serialization is the process which is used to convert the objects into byte streamDeserialization is the opposite process of serialization where we can get the objects back from the byte stream.
An object is serialized by writing it an ObjectOutputStream.

An object is deserialized by reading it from an ObjectInputStream.




Q #56) What is SerialVersionUID?

Ans: Whenever an object is Serialized, the object is stamped with a version ID number for the object class. This ID is called the  SerialVersionUID. This is used during deserialization to verify that the sender and receiver that are compatible with the Serialization.


Other resources




Potential Value Opportunities



Potential Challenges



Candidate Solutions



Step-by-step guide for Example



sample code block

sample code block
 



Recommended Next Steps