Blogs  

37 Advanced Java Interview Questions for Freshers

When preparing for an interview, knowledge of Advanced Java is essential for standing out in today’s competitive IT landscape. Advanced Java goes beyond the basics and delves into enterprise-level development, server-side applications, frameworks like Spring and Hibernate, and more.

In this blog, we'll explore some of the most frequently asked Advanced Java interview questions and their answers to help you confidently approach your next interview.

  1. What is a DataSource in JDBC?

    A Data Source object enables JDBC applications to obtain a DBMS connection from a connection pool. Each Data Source object binds to the JNDI tree and points to a connection pool or MultiPool. Applications look up the Data Source on the JNDI tree and then request a connection from the Data Source.

  2. How many ways can you update a result set?

    The following ways to update a result set

    • updateRow()

    • deleteRow()

    • refreshRow()

    • cancelRowUpdates()

    • insertRow()

  3. How to set the attribute Concurrency in ResultSet?

    CONCUR_READ_ONLY – It is only for reading.
    CONCUR_UPDATABLE − It is for both read and updated.

  4. What are the methods available in HttpServlet class?

    • public void service(ServletRequest req,ServletResponse res)

    • protected void service(HttpServletRequest req, HttpServletResponse res)

    • protected void doGet(HttpServletRequest req, HttpServletResponse res)

    • protected void doPost(HttpServletRequest req, HttpServletResponse res)

    • protected void doHead(HttpServletRequest req, HttpServletResponse res)

    • protected void doOptions(HttpServletRequest req, HttpServletResponse res)

    • protected void doPut(HttpServletRequest req, HttpServletResponse res)

    • protected void doTrace(HttpServletRequest req, HttpServletResponse res)

    • protected void doDelete(HttpServletRequest req, HttpServletResponse res)

    • protected long getLastModified(HttpServletRequest req)

  5. What is HTTPFilter?

    Filters typically run on multithreaded servers,so be aware that a filter must handle concurrentrequests and be careful to synchronize access to shared resources.Shared resources include in-memory data such asinstance or class variables and external objectssuch as files, database connections, and networkconnections.

  6. How servlet filter configuration in web.xml?

    Syntax:
    <filter> 
    <filter-name>...</filter-name> 
    <filter-class>...</filter-class> 
    </filter>



    7.What are the uses of filter in servlet?

    Data compression
    Encryption and decryption
    Input validation.
    Recording all incoming requests
    Logs the IP addresses of the computers from which the requests originate
    Conversion.

  7. What are the methods available in filter interfeace in servlet?

    public void init(FilterConfig config)   
    public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)
    public void destroy()

  8. What is the difference between war file and jar file?

    JAR files are used for packaging and distributing standalone Java applications or libraries, where as WAR files are used for packaging and distributing web applications.

  9. How to create war file?

    It needs jar tool of JDK
    Go inside the project directory of your project (outside the WEB-INF), then write the following command
    jar -cvf projectname.war * 
    Here, -c is used to create file, -v to generate the verbose output and -f to specify the arhive file name.
    The * (asterisk) symbol signifies that all the files of this directory.



  10. What is ServletInputStream?

    ServletInputStream is a class which provides to read binary data as image from the request object.
    The getInputStream() method of ServletRequest interface returns the instance of ServletInputStream.
    it is having only one method called as
    int readLine(byte[] b, int off, int len)
    Example:
    ServletInputStream input =request.getInputStream();

  11. What is ServletOutputStream?

    ServletOutputStream is a class used  to write binary data  into the response.
    The getOutputStream() method of ServletResponse interface returns the instance of ServletOutputStream class.
    Example:
    ServletOutputStream out=response.getOutputStream();

  12. What are the methods available in ServletOutputStream class?

    • void print(long l)

    • void print(boolean b)

    • void print(int i)

    • void print(char c)

    • void print(String s)

    • void print(float f)

    • void println(long l)

    • void println

    • void print(double d)

    • void println(boolean b)

    • void println(double d)

    • void println(int i)

    • void println(float f)

    • void println(String s)

    • void println(char c)

  13. Explain SingleThreadModel interface?

    SinglrThreadModel is used to handle single request at a time. If the programmer wants single request at a time must be implementing this interface. It is a marker interface so does not have any methods.
    It is recommended to use other means to resolve these thread safety issues such as synchronized block etc.
    Sample Program:

    public class TestServlet extends HttpServlet implements SingleThreadModel {
       
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html"); 
            PrintWriter out = resp.getWriter(); 
            out.print("Welcome to "); 
            try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();} 
            out.print("Nareh I Technologies"); 
            out.close(); 
        }
    }
    
  14. What are the methods available in ServletContext Interface?

    • public String getInitParameter(String name)

    • public Enumeration getInitParameterNames()

    • public Enumeration getInitParameterNames()

    • public void removeAttribute(String name)

    • public void setAttribute(String name,Object object)

    • public Object getAttribute(String name)

  15. How to get the object of ServletContext interface?

    getServletContext() method used to returns the object of ServletContext.
    Syntax:
    public ServletContext getServletContext() 
    Example:
    ServletContext serv=getServletContext();

  16. What are Techniques of Session Tracking?

    The following techniques are used for session tracking

    • Hidden Form Field

    • URL Rewriting

    • Cookies

    • HttpSession

  17. Explain JDBCURL connection for oracle expression addition using connection class object?

    JDBC URL of Oracle connection is jdbc:oracle:thin:@localhost:1521:xe
    where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name.

  18. How to establish connection using connection class Object?

    For establish the connection by using connection class object of oracle expression addition is
    Connection con = DriverManager.getConnection(url,user,password)
    The URL is connection which of database URL example oracle and MYSQL.
    UserName: username of oracle database.
    Password: Password of oracle database related to username

  19. Explain JDBCURL connection for MYSQL expression addition using connection class object?

    The url for MYSQL JDBC connection using connection class object is jdbc:mysql://localhost:3306/test
    where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and test is the database name.

  20. What are the different types of drivers in jdbc?

    Type 1: JDBC-ODBC bridge.
    Type 2: Native-API driver(partial Java driver).
    Type 3: Network Protocol driver(pure Java driver for database middleware).
    Type 4: Thin driver(pure Java driver for direct-to-database).
    Type 5: highly-functional drivers with superior performance.

  21. What is “oracle.jdbc.driver.OracleDriver”?

    This is driver class for oracle database and by using Class.ForName to load the oracle driver first
    For class.ForName
    Class.forName("oracle.jdbc.driver.OracleDriver");

  22. What is “com.mysql.jdbc.Driver”?

    This is driver class for MYSQL database by using Class.ForName to load the MYSQL driver first.
    Class.ForName(“com.mysql.jdbc.Driver”);

  23. Which data types are used for storing the image and file in the database table?

    BLOB: it is a data type is used to store the image in the database. We can also store videos and audio by using the BLOB data type. It stores the binary type of data.
    CLOB: it is a data type is used to store the file in the database. It stores the character type of data.

  24. What is stored procedure? What are the parameter types in stored procedure?

    Stored procedure is a group of SQL queries that are executed as a single logical unit to perform a specific task. Name of the procedure should be unique since each procedure is represented by its name.
    For example, operations on an employee database like obtaining information about an employee could be coded as stored procedures that will be executed by an application.

  25. What is the difference between oracle.jdbc.driver.OracleDriver and oracle.jdbc.OracleDriver?

    For Oracle 9i onwards you should use oracle.jdbc.OracleDriver rather than oracle.jdbc.driver.OracleDriver as Oracle have stated that oracle.jdbc.driver.OracleDriver is deprecated and support for this driver class will be discontinued in the next major release.

  26. What is JDBC-ODBC bridge driver?

    JDBC bridge is used to access ODBC drivers installed on each client machine and it converts JDBC method calls into the ODBC function calls. This driver does not support from java 8 or later.

  27. What is Native API driver?

    The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.

  28. What is Network Protocol driver?

    The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol and inotherwords it is three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server. It is fully written in java.

    Advantage is No client-side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.

  29. What is thin driver?

    The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language and it is called as pure java-based driver. For this you don't need to install special software on the client or server.

  30. What is ResultSetMetaData interface in jdbc?

    ResultSetMetaData interface provides methods to get metadata from the ResultSet object and count the number of columns, column name, column type etc by using getMetaData() method of ResultSet.
    Syntax:
    public ResultSetMetaData getMetaData()throws SQLException

  31. What are the commonly used methods in ResultSetMetaData?

    • public int getColumnCount()throws SQLException

    • public String getColumnName(int index)throws SQLException

    • public String getColumnTypeName(int index)throws SQLException

    • public String getTableName(int index)throws SQLException

  32. Explain DatabaseMetaData interface?

    DatabaseMetaData is used for database driver name,product version, name of total number of tables, name of total number of views etc.By using getMetaData() method of Connection interface returns the object of DatabaseMetaData.
    Syntax:
    public DatabaseMetaData getMetaData()throws SQLException 

  33. What are the commonly used methods in DatabaseMetaData?

    • public String getDriverName()throws SQLException

    • public String getDriverVersion()throws SQLException

    • public String getUserName()throws SQLException

    • public String getDatabaseProductName()throws SQLException

    • public String getDatabaseProductVersion()throws SQLException

    • public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)throws SQLException

  34. Explain ACID properties of Transaction management in JDBC?

    ACID stands for Atomicity, Consistency, isolation and durability.
    Atomicity means either all successful or none.
    Consistency ensures bringing the database from one consistent state to another consistent state.
    Isolation ensures that transaction is isolated from other transaction.
    Durability means once a transaction has been committed, it will remain so, even in the event of errors, power loss etc.

  35. What is BatchProcessing in JDBC?

    Instead of executing a single query, we can execute a batch (group) of queries and when one statement sends multiple statements of SQL at once to the database, the communication overhead is reduced significantly, as one is not communicating with the database frequently, which in turn results to fast performance.The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.

  36. What are the steps for batch processing in JDBC?

    The following steps used to create batch processing in JDBC

    • Load the driver class

    • Create Connection

    • Create Statement

    • Add query in the batch

    • Execute Batch

    • Close Connection

Boost Your Skills with Naresh IT's Advanced Java Online Training

If you’re aiming to master the intricacies of Advanced Java and be interview-ready, Naresh IT offers the perfect platform. Our comprehensive Advanced Java Online Training provides:

  • Live instructor-led classes by industry experts.
  • Hands-on practical experience with real-time projects.
  • Complete course material covering servlets, JSP, JDBC, Spring, and Hibernate.
  • 24/7 support for clearing doubts and assisting with assignments.
  • Job-oriented training focused on interview preparation and placement assistance.

At Naresh IT, we not only teach you Advanced Java but also help you sharpen your problem-solving skills with interview-focused training sessions.

Stay tuned for the rest of the blog where we dive into more interview questions for all technologies

Ready to upskill? Enroll in Naresh IT's Advanced Java Online Training today and take your career to the next level!

----------------------------------------------------------------------------------------------------

For More Details About Full Stack Courses : Visit Here
Register For Free Demo on UpComing Batches : Click Here

Top 40 Advanced Java Interview Questions & Answers

When preparing for an interview, knowledge of Advanced Java is essential for standing out in today’s competitive IT landscape. Advanced Java goes beyond the basics and delves into enterprise-level development, server-side applications, frameworks like Spring and Hibernate, and more.

In this blog, we'll explore some of the most frequently asked Advanced Java interview questions and their answers to help you confidently approach your next interview.

  1. What is JDBC?

    JDBC stands for Java Database Connectivity which is used to manipulate and connect for database.

  2. What is servlet?

    Servlet is a taking the request from client and giving the response to the client in other words Servlet is program that run on a Web or Application server and act as a middle layer between a request coming from a Web browser(Client) or other HTTP client and databases or applications on the HTTP server.

  3. What is JSP?

    JSP stands for Java Server Pages and JSP contains both HTML and JSP tags. In JSP tags we use java code like scriptlet tag.
    JSP is a server side programming technology is used to develop web applications and to create dynamic web content.

  4. What is the life cycle of servlet?

    In servlet lifecycle contains three stages
    Init(): This is used to initialize servelet by calling init() method
    Service(): This is used to process the client request
    Destroy(): This is used to terminate servlet request

  5. What are the steps to create JDBC connection?

    The following steps to create a JDBC connection
    i.    Import the packages
    ii.    Register the drivers
    iii.    Establish a connection
    iv.    Create a statement
    v.    Execute the query
    vi.    Retrieve results
    vii.    Close the connections

  6. When destroy() method of servlet gets called?

    The destroy() method is called only once at the end of the life cycle of a servlet.

  7. What are the different types of statements in JDBC?

    Statement, preparedstatement and callable statement are the statements in JDBC
    Statement: it is used to access data from database for static SQL statement at runtime and This statement cannot accept parameters.
    Prepared statement: it is used to access data from database dynamically and by using parameters to execute SQL Query at runtime
    Callable statement: Callable Statements are accepts database stored procedures and if you want access data from database in the form of Stored procedure. It accept input parameters of SQL Query.

  8. What is the difference between execute(), executeQuery() and executeUpdate()?

    execute():  The return type of execute is Boolean if true a resultSet object will be retired otherwise  it returns false. This method is used to execute both select and update SQL queries.
    Syntax:
    Boolean execute(String SQL) 

    executeQuery(): the return type of executeQuery() is ResultSet and it is used only on select statement of SQL query.
    Syntax:
    ResultSet executeQuery(String SQL)

    executeUpdate(): The return type of executeUpdate() is integer, if it return 0 indicates nothing to execute SQL Query. This method is used for update,delete and insert Sql Queries.
    Syntax:
    Int executeUpdate(String SQL)

  9. What is the difference between ServletConfig and ServletContext?

    ServletConfig is used for sharing init parameters specific to a servlet while ServletContext interface is for sharing init parameters within any Servlet within a web application.
    ServleteConfig object represents unique object per/single servlet and ServletContext complete web application running on JVM with unique object.
    getServletConfig() method is used to get the config Object and getServletContext() method is used to get context object.



  10. How to create statement interface in JDBC?

    The following procedure to create statement interface in JDBC by using createStatement() method
    Statement stmtement = null;
    try {
      stmtement = conn.createStatement( );
      . . .
    }
    catch (SQLException e) {
      . . .
    }
    finally {
      . . .// without close connection
    }
    
  11. How to create prepared statement interface in JDBC?

    The following procedure to create preparedStatement interface in JDBC by using prepareStatement(SQL) method.

    PreparedStatement pstmt = null;
    try {
      String SQL = ""; //SQL Query
      pstmt = conn.prepareStatement(SQL);
      . . .
    }
    catch (SQLException e) {
      . . .
    }
    finally {
      . . . // without close connection
    }


  12. Can you create a Deadlock condition on a servlet?

    Yes, Deadlock situation can be created on a servlet by calling doPost() method inside doGet() method, or by calling a doGet() method inside doPost() method will successfully create a deadlock situation.
    Sample Example:
    public class TestServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
    response.getWriter().append("Served at: ").append(request.getContextPath());
    }
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }
    
    }


  13. How to create callable statement interface in JDBC?

    The following procedure to create Callable Statement interface in JDBC by using prepareCall(SQL) method.

    Connection con  = null;
    CallableStatement callstmt = null;
    try {
      String SQL = "{call getEmpName (?, ?)}";
      callstmt = con.prepareCall (SQL);
      . . .
    }
    catch (SQLException e) {
      . . .
    }
    finally {
      . . .// without close connection
    }


  14. What is the difference between sendredirect and requestdispatcher?

    Send Redirect request process is taken care by web container and transfers the request using a browser, each request is processed as a new request. RequestDispatcher request process is taken care by web container, each request is processed without the client being informed.
    Using sendRedirect() it doesn't include any resources but using requestDispatcher() it includes the resources.
    SendRedirect is client-side process and    Request Dispatcher is server-side process.

  15. How to delete cookie using Serlvet?

    The following steps to delete cookie using servlet
    i.    Read existing cookie and store it in cookie object
    ii.    Set cookie as zero using setMaxAge() method to delete exist cookie
    iii.    Add this cookie back into response header
    Example:
    Cookie cookie=new Cookie("user","");
    cookie.setMaxAge(0);
    response.addCookie(cookie);//adding cookie in the response

  16. How to create cookie using Serlvet?

    The following steps to create cookie using servlet
    i.    Create cookie object
    ii.    Add cookie in response by using addCookie(CookieObject)
    Example:
    Cookie cookie=new Cookie("user","NareshIT");//create cookie object  by using key and value
    response.addCookie(cookie);//add cookie in the response

  17. What is URL Rewriting?

    URL rewriting means to add some specific data on the end of URL(Unifom resourse locator) to identify the session in other words it is a automatic process to alter a program for manipulating the  parameters in URL.

    For example user web browser sends request ‘nareshit.in/all-courses’ so the url is manipulated automatically by server add some data like ‘nareshit.in/all-courses;sessionid=123’ here sessionid=123 is identifier.

  18. How to read from data in Servlet?

    Data From User Interface like JSP to servlet handles automatically based on situation
    The following three methods are using servlet read from JSP data
    getParameter(): by using request.getParameter() method to read one from UI
    getParameterValue(): when call this method like request.getParameterValue() it reads multiple values like booking ticket selection.
    getPrameterNames() : when call this method it access list all parameters in current request

  19. What is Cookie?

    A cookie is a piece of information that is present between multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

  20. What are the annotations used in Servlet 3?

    The following 3 important annotations are used in the servlets.
    @WebServlet : for servlet class.
    @WebListener : for listener class.
    @WebFilter : for filter class.

  21. What is the use of RequestDispatcher Interface?

    RequestDispatcher interface handle the request from client and dispatches to their resources such as servlet,JSP,HTML. It hides the information to client browser for security and it contains two methods like forward and include.
    Syntax:
    public void forward(ServletRequest request, ServletResponse response)
    Forwards request from one servlet to another resource like servlet, JSP, HTML etc.
    public void include(ServletRequest request, ServletResponse response)
    Includes the content of the resource such as a servlet, JSP, and HTML in the response.



  22. Why do we use sendredirect() method?

    The sendredirect() method is client-side infomation. It is used to redirect the response to another resource like Servlet, JSP, HTML. It does not hide the infomration from URL.
    Syntax:
    void send Redirect(URL);
    response.sendRedirect(URL);

  23. What are the differences between ResultSet and RowSet?

    RowSet Object can be serialized but ResultSet Object cannot be serialized.
    RowSet either Connected or disconnected from the database but ResultSet always connected to database.
    RowSet using the RowSetProvider.newFactory().createJdb cRowSet() method. and ResultSet using the executeQuery() method.
    Result Set Object is a JavaBean object but Result Set object is not a JavaBean object.

  24. What are the methods used in lifecycle of JSP?

    There are three methods used in lifecycle of JSP.
    i.    public void jspInit()
    ii.    public void _jspService(ServletRequest request,ServletResponse)throws ServletException,IOException
    iii.    public void jspDestroy()

  25. How to disable session in JSP?

    The following tag is used to disable session in JSP
    <%@ page session="false" %> 

  26. What is MVC?

    MVC stands for Model View Controller and this architecture follows View is User Interface that is presentation layer and Controller is Business logic layer and Model is Data access layer to access the data from database.
    It follows View to Controller to Model to Database.

  27. What is the use of <jsp:include> tag?

    This tag includes the response from a servlet or JSP page during the request processing phase.

  28. What is <welcome-file-list> tag?

    <welcome-file-list> is a property which defines list of welcome-files in web.xml
    If you did not define file name while loading the project in the browser or run on server, the tag <welcome-file-list> is used to define the files that invoked automatically by the server.
    By default server looks for welcome file as below
    index.html
    index.htm
    index.jsp
    Example:
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.jsp</welcome-file>
        <welcome-file>default.htm</welcome-file>
      </welcome-file-list>


  29. What is the use of <servlet-mapping> tag?

    <servlet-mapping> is used to associates a URL pattern to a servlet instance. <servlet-mapping> contains two elements like <servlet-name> and <url-pattern> It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to.
    Example:
    <servlet-mapping>
    <servlet-name>Name-of-servlet</servlet-name>
    <url-pattern>/*</url-pattern>
    </servlet-mapping>


  30. What is <session-config>?

    <session-config> is an element available in web.xml file. It contains some models like session-timeout, cookie configuration and tracking mode. Session-config is used to define timeout from the server and as well as configure cookie either http as true for provide security. For tracking mode is Cookie or URL which tracks the information.
    Example:
    <session-config>
            <session-timeout>90</session-timeout>
            <cookie-config>
                <http-only>true</http-only>
                <secure>true</secure>
            </cookie-config>
            <tracking-mode>COOKIE</tracking-mode>
        </session-config>




  31. What is session time out inweb.xml of jsp?

    To set a session-timeout that never expires is not desirable because you would be reliable on the user to push the logout-button every time he's finished to prevent your server of too much load (depending on the amount of users and the hardware). Additionaly there are some security issues you might run into you would rather avoid.

    The reason why the session gets invalidated while the server is still working on a task is because there is no communication between client-side (users browser) and server-side through e.g. a http-request. Therefore the server can't know about the users state, thinks he's idling and invalidates the session after the time set in your web.xml.

  32. What is the use of <class-name> tag in web.xml?

    You specify the serlvet class name i.e fully quailified java class name and it is mapped to url-pattern by using servlet-name element. This makes it easier to use in the web application, in your html etc. for example com.test.NareshIT here NareshIT is a servlet class and it is fully qualified class name with path.
    <servlet-class>com.test.NareshIT</servlet-class>

  33. What is custom tag in jsp?

    Custom tags are known as user defined tags. A tag handler is associated with each tag to implement the operations so, it separates the business logic from JSP and helps avoid the use of scriptlet tags.
    Syntax:

    without body
    <prefix : suffix attribute = “value”/>
    with body
    <prefix : suffix attribute = “value”>body</prefix : suffix>
    We need to follow some steps to create custom tag.
    Create the Tag handler class and perform action at the start or at the end of the tag.
    Create the Tag Library Descriptor (TLD) file and define tags
    Create the JSP file that uses the Custom tag defined in the TLD file

  34. What is the difference between doGet() and doPost()?

    doGet() method is designed to get response context from web resource by sending limited amount of input data, this response contains response header, response body where as doPot() method is designed to send unlimited amount of data along with the request to web resource.
    In doGet() parameters are not encrypted where as in doPost() method parameetrs are encrypted
    doGet() is not suitable for file upload operation but doPost() is suitable for multiple part from data.

  35. Can you disable the caching on the back button of a particular browser?

    Yes, The Caching process can be disabled on the back button of the browser.
    The following tag is used for disable caching
    <% response.setHeader("Cache-Control","no-store"); response.setHeader("Pragma","no-cache"); response.setHeader ("Expires", "0"); %>

  36. What are the methods available in session object?

    The following methods are available in session object
    • public Object getAttribute(String name)

    • public Enumeration getAttributeNames()

    • public long getCreationTime()

    • public String getId()

    • public long getLastAccessedTime()

    • public int getMaxInactiveInterval()

    • public void invalidate()

    • public boolean isNew()

    • public void removeAttribute(String name)

    • public void setAttribute(String name, Object value)

    • public void setMaxInactiveInterval(int interval)

  37. What is the role of Class.forName while loading drivers?

    Class.forName creates an instance of JDBC driver and register with DriverManager. forName() is found in java.lang.Class class is used to get the instance of this Class with the specified class name.
    Syntax:
    public static Class<T> forName(String className) throws ClassNotFoundException
    Sample Program:
    public class InterviewTest {
        public static void main(String[] args) throws ClassNotFoundException{
            Class strcls = Class.forName("java.lang.String");
            System.out.print(strcls.toString());
        }
    }


  38. Why “No suitable driver” error occurs?

    No suitable driver” occurs when we are calling DriverManager.getConnection method,
    Unable to load exact JDBC drivers before calling the getConnection method.It may be
    invalid or wrong JDBC URL.
    In other words This error occurs if JDBC is not able to find a suitable driver for the URL
    format passed to the getConnection() method and  if incorrect driver class name or more
    typically the JDBC database URL passed is not properly constructed or incorrect permission
    to access the driver jar files.

  39. What are the exceptions in JDBC?

    The following exceptions in JDBC
    • batchUpdate Exception

    • Data Truncation

    • SQL Exception

    • SQL Warning
  40. Give steps to connect to the DB using JDBC?

    DriverManager and DataSourse are the two types of connections to connecting database using JDBC

    DriverManager:
    It will load the driver class with the help of class.forName(driver class) and Class.forName().
    Post Loading it will pass the control to DriverManager.
    DriverManager.getConnection() will create the connection to access the database.

    DataSource:
    For DataSource, no need to use DriverManager with the help of JNDI.  It will lookup the DataSource from Naming service server. DataSource.getConnection() method will return Connection object to the DB.

Boost Your Skills with Naresh IT's Advanced Java Online Training

If you’re aiming to master the intricacies of Advanced Java and be interview-ready, Naresh IT offers the perfect platform. Our comprehensive Advanced Java Online Training provides:

  • Live instructor-led classes by industry experts.
  • Hands-on practical experience with real-time projects.
  • Complete course material covering servlets, JSP, JDBC, Spring, and Hibernate.
  • 24/7 support for clearing doubts and assisting with assignments.
  • Job-oriented training focused on interview preparation and placement assistance.

At Naresh IT, we not only teach you Advanced Java but also help you sharpen your problem-solving skills with interview-focused training sessions.

Stay tuned for the rest of the blog where we dive into more interview questions for all technologies

Ready to upskill? Enroll in Naresh IT's Advanced Java Online Training today and take your career to the next level!

----------------------------------------------------------------------------------------------------

For More Details About Full Stack Courses : Visit Here
Register For Free Demo on UpComing Batches : Click Here

40 Most Asked Core Java Interview Questions You Must Prepare in 2024

Java happens to be one of the most powerful yet flexible programming languages, known for its involvement in data processing, application development and large-scale systems generally. It gives developers solid frameworks and tools that enable them to do complex computations and create sophisticated management models that are useful in data management and analysis.

Why Choose Java?

  • Industry Leader: For a long time, Java has been a dependable software development language that many organizations utilize to create applications that can scale up or down as required (Berger, 2019). Its durability as well as versatility makes it the preferred option for enterprise level development.
  • Vast Open Source Ecosystem: There exists an extensive range of open source libraries associated with Java which makes it flexible enough to meet different project requirements with ease when selecting the most appropriate tools.
  • Competitive Advantage: Today’s developers and engineers want faster information processing, extraction of valuable insights, and huge datasets modeling in this rapidly changing tech world (Mohammed et al., 2017). The performance and scalability that Java has, becomes another reason why it can be used to tackle these issues challenging developers today.
  • Broad Versatility: Java provides support for several libraries and frameworks rendering it ideal for different functions ranging from data handling to full-fledged application development. By familiarizing yourself with these libraries, you will speed up your development work and make it more reliable.
  1. Can class have private and protected as access modifier?

No, class does not have private and protected as access modifier, class can be default and public.
Example:

private class NIT{ //error
}
protected class NIT1 // error
{   
}
  1.  What is the difference between Abstraction and Encapsulation?

Abstraction is the method of hiding the unwanted information. Whereas encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside.
In abstraction, implementation complexities are hidden using abstract classes and interfaces. While in encapsulation, the data is hidden using methods of getters and setters.

  1. Why final and abstract cannot be used at a time?

If we declare class as abstract it must be extended by another class but if we declare final class it cannot be extended by other class.
Example:

final class NIT{
   
}
class NIT1 extends NIT // error because final class cannot be extended
{   
}
  1. What is Object Cloning?

Object cloning means exact copy of Object by using Cloneable interface must be implemented by class and if you not implemented it throws cloneNotSupportedException
Example:

public class InterviewTest implements Cloneable {
    int id;
    String name;
    public InterviewTest(int id, String name) {
        this.id=id;
        this.name = name;
    }
   
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
       
    public static void main(String[] args) {
        InterviewTest nit = new InterviewTest(1,"NIT");
        System.out.println(nit.id+" "+nit.name);
        try {
            InterviewTest nit1 = (InterviewTest)nit.clone(); // Object cloning
            System.out.println(nit1.id+" "+nit1.name);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
  1. Define Wrapper Classes in Java?

Wrapper class is a mechanism which contains primitive data types of class and it converts to primitive data type to object and object to primitive data type by using Autoboxing and unboxing technique.
For example Primitive data type ‘char’ and wrapper class is ‘Character’
Example 1: Autoboxing

public class InterviewTest {
    public static void main(String[] args) {
        int id = 25;
        short sh = 10;
        byte by = 15;
        char letter ='N';
        boolean tr = true;
        float fdes = 5.25F;
        double ddes = 6.27D;
        long lon = 43L;
       
        //Autoboxing
        Integer i = id;
        Short s = sh;
        Byte b = by;
        Character c = letter;
        Boolean bol = tr;
        Float f = fdes;
        Double d = ddes;
        Long l = lon;
        //print object values
        System.out.println("Integer: "+i);
        System.out.println("Short: "+s);
        System.out.println("Byte: "+b);
        System.out.println("Charater: "+c);
        System.out.println("Boolean: "+bol);
        System.out.println("Float: " +f);
        System.out.println("Double: "+d);
        System.out.println("Long: "+l);
    }
}


Example 2: Unboxong

public class InterviewTest {
    public static void main(String[] args) {
        Integer i = 25;
        Short s = 10;
        Byte b = 15;
        Character c = 'N';
        Boolean bol = true;
        Float f = 5.25F;
        Double d = 6.27D;
        Long l = 43L;
       
        //Unboxing
        int id = i;
        short sh = s;
        byte by = b;
        char letter =c;
        boolean tr = bol;
        float fdes = f;
        double ddes = d;
        long lon = l;
       
        //print primitive values
        System.out.println("int: "+id);
        System.out.println("short: "+sh);
        System.out.println("byte: "+by);
        System.out.println("char: "+letter);
        System.out.println("boolean: "+tr);
        System.out.println("float: " +fdes);
        System.out.println("double: "+ddes);
        System.out.println("long: "+lon);
    }
}
  1. Can you implement pointers in a Java Program?

No, Pointers are not available in java so, we cannot implement pointers.

  1. Define System.out.println()?

System. out. println() that prints any argument you pass and adds a new line after it. println() is responsible for printing the argument and printing a new line. System.out refers to the standard output stream.
System: this is a final class and it is found at java.lang package.
Out: it is static and public modifier field of System class and it is instance of PrintStream.
Println(): it is an instance of PrintStream class and it prints output and printing new line

  1. How to create an object in Java?

Java is Object Oriented programming language so, without creating an object we cannot execute the program.
In java we provide fives ways to create an object
1.    Using new keyword
2.    Using newInstance method of class
3.    Using newInstance method of Constructor
4.    Using clone()
5.    Using Deserilization
We use Class.forName(String className) method it returns new instance of class object

  1. How to access class data members and methods in Java?

Class data members and methods into another class by using object in java but we have Instance data members and static data members and similar to methods
Example:

class NIT {
    int id = 5;
    public void test()
    {
        System.out.println("NareshIT");
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit = new NIT();
        System.out.println(nit.id);
        nit.test();
    }
}

  1. Can we declare a static variable inside a method?

No we cannot declare a static variable inside a method and only final method is allowed.
Example:

class NIT {
    public void test()
    {
        final int t = 10;
        static String name = "Naresh"; // error
    }
}
  1. What is the difference between a static and a non-static inner class?

Nested or inner static class doesn’t need a reference of Outer class but a non static nested class or Inner class requires Outer class reference.
Example:

class NIT {
    //non static
    class Test
    {
        public void print() {
            System.out.println("NON - Static inner or nested class");
        }
    }
    //static
    static class Program
    {
        void print() {
            System.out.println("Static inner or nested class");
        }
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit = new NIT();
        NIT.Test test = nit.new Test(); // for non static inner class
        test.print();
        NIT.Program prog = new NIT.Program(); // for static inner class
        prog.print();
    }
}
  1. What is the difference between a constructor and a method?

Constructor
Constructor does not have return type and it is used to initialize the object.
Default constructor is available
Method
Method has return type if you declare void it does not return any value and we access by using object.
We don’t have default method

  1. What is the difference between java.util.Date and java.sql.Date?

Both dates are storing date and time information but java.sql.Date is used to communication of java applications with the database but java.util.Date get time and date from the system.
Sometimes we need to convert sql date into util date and vice versa based on date formate

  1. What are the inner class?

We have two types of inner classes one is static inner class and non static inner class
Inner class is defined as class provides another class inside that class or group of classes in one place it is more reliable to maintain.
Example:

class NIT {
    //static inner class
    static class Staticclass
    {
       
    }
    //Non static inner class
    class NonStatic
    {
       
    }
}
  1. What is the anonymous class?

Anonymous class is nothing but without a class name of inner class which is only create single object and a anonymous class must be defined inside another class
Anonymous class may have to create in two ways like class and interface.
Syntax:

Class Outerclass
{
    //define anonymous class
    object = new  Type(parameterlist) // parameter list is optional
{
    body
};
}


Example:

class NIT {
   
    public void test() {
        System.out.println("This is Normal class");
    }
}
public class InterviewTest {
    public void testAnonymous()
    {
        NIT nit = new  NIT() // Anonymous class
        {
            @Override
            public void test() {
                System.out.println("This is Anonymous class");
            }
        };
        nit.test(); // must be class inner class method by using object
    }
    public static void main(String[] args) {
        InterviewTest inter = new InterviewTest();
        inter.testAnonymous();
       
    }
}
  1. What is the difference between thread and process?

process takes more time to create or terminate when compared to thread because thread communication is more efficient and thread have segment of process
We have multi programs holds multiple process but each process have multiple threads.
Process involved in system calls but thread is created by API’s

  1. What is Daemon thread?

In java Daemon thread is service provider thread it provides service to the user threads and the life of the Daemon thread depends on user crated threads.
Daemon thread contains two methods setDaemon(Boolean status) and isDaemon(), if user thread converts to Daemon thread use setDaemon(true) method and if current thread to check Daemon thread or not use isDaemon() method.
Example:

public class InterviewTest extends Thread{
    @Override
        public void run() {
            if(Thread.currentThread().isDaemon())// check if the thread is Daemon or not
                System.out.println("Thread is Daemon");
            else
                System.out.println("User thread");
        }
    public static void main(String[] args) {
        InterviewTest inter = new InterviewTest();// create new thread
        InterviewTest inter1 = new InterviewTest();
        InterviewTest inter2 = new InterviewTest();
       
        inter.setDaemon(true); // first thread i.e user thread convert into Daemon
       
        inter.start();
        inter1.start();
        inter2.start();
    }
}
  1. What is the difference between user thread and Deamon thread?

A user thread can keep running by the JVM running but a daemon thread cannot keep running by the JVM.
User threads are created by application but Deamon threads are created by JVM and user threads are foreground threads ant Deamon threads are background threads
User threads are high priority and Deamon threads are low priority

  1. How can we create daemon threads?

By using setDeamon(Boolean status) method is used to create deamon threads or convert user threads into daemon thread
Example:
Test test = new Test() // user thread
Test.setDeamon(true) // create deamon thread

  1. What is the difference between notify() and notifyAll() methods?

In cache memory a group of threads are waiting for notification in the form of object, if you want notifies into one thread by using notify() method and if you want to notifies all the threads by using notifyAll() method.
According to performance notify() is better performance compares to notifyAll() method
According to risk notify() has more risk compared to notifyAll() because if any thread is missing another does not take request.

  1. What is thread pool?

Thread pool is nothing but to manage collection of threads and it provides multiple tasks to increase the performance and reduce the per task invocation overhead.

  1. What is the difference between Thread and Thread pool?

Thread pool having reuse threads because it has multiple threads but Thread class contains only one thread. We have checking process in Thread pool and no checking process in Thread.

  1. What is the lifecycle of Thread?

We have various stages in lifecycle of Thread.

    • New/ Start
    • Runnable
    • Running
    • Blocked
    • Waiting
    • Terminated
  1. What is the difference between Runnable and Callable interface?

Callable interface is checked exception so it returns value otherwise it throws exception but Runnable interface is unchecked exception so it does not return any value.
Callable interface is call() method but Runnable interface have run() method
Syntax of Runnable interface

public interface Runnable
{
  public abstract void run();
}
Syntax of callable interface
public interface Callable<E>
{
  E call() throws exception ;
}


Example for callable interface

public class InterviewTest implements Callable<String>{
    @Override
    public String call() throws Exception {
        return "Welcome to NareshIT";
    }
    public static void main(String[] args) throws Exception {
        ExecutorService service  = Executors.newFixedThreadPool(3);
        InterviewTest test = new InterviewTest();
        Future<String> thread = service.submit(test);
        System.out.println(thread.get().toString());
        //test.call();
    }
}


Example for Runnable interface

public class InterviewTest implements Runnable{
   
    @Override
        public void run() {
            System.out.println("Runnable Thread");
        }
    public static void main(String[] args) throws Exception {
        InterviewTest test = new  InterviewTest();
        Thread thread = new Thread(test);
        thread.start();
    }
}
  1. How can we handle deadlock?

There are four ways to Handling the deadlock situation
1.    Prevention
2.    Avoidance
3.    Detection and Recovery
4.    Ignorance

  1. What is the purpose of join() method?

In java join() method found in java.lang.Thread class which permits one thread to wait until the other thread to finish its execution. If more than one thread invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to mention the waiting period.
There are three overloaded join() methods
Join() : current thread stops and goes into wait state
Syntax:
public final void join() throws InterruptedException
Join(long mls) : this method is used to current thread is goes to wait state upto specified time that is in milliseconds.
Syntax:
public final synchronized void join(long mls) throws InterruptedException, where mls is in milliseconds
Join(long mls, int nanos) : this method is used to current thread is goes to wait state upto specified time that is in milliseconds plus nano seconds.
Syntax:
public final synchronized void join(long mls, int nanos) throws InterruptedException, where mls is in milliseconds.
Example:

public class InterviewTest{
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread();
        thread.start();
        System.out.println(thread.isAlive());
        thread.join();
        System.out.println(thread.isAlive());
    }
}
  1. What is Thread Scheduler?

Thread Scheduler means the JVM thread using preemptive and priority based scheduling algorithm.
All Java Threads have a priority and the thread with the height priority is scheduled to run by JVM.
In case of two threads have the same priority it follows FIFO order.

  1. What is the use of super keyword?

The super keyword is used for refers to superclass (parent) objects and It is used to call superclass methods, and to access the superclass constructor.
Example:

class NIT {
    int a = 10;
    public NIT() {
        System.out.println("Super class");
    }
   
    public void test() {
        System.out.println("test method");
    }
}
class NIT1 extends NIT
{
    //super keyword implicitly by constructor
    public NIT1() {
        super();
        System.out.println("Child class");
    }
    //super keyword explicitly by constructor
    /*
    * public NIT1() { System.out.println("Child class"); }
    */
   
    // method
    public void process() {
        super.test(); //call parent class method
        System.out.println(super.a); // call parent class variable
    }
}
public class InterviewTest{
    public static void main(String[] args) throws Exception {
        NIT1 nit = new NIT1();
        nit.process();
    }
}
  1. Can Static method be overridden?

NO, static method is not overridden in java because static method of parent class is hidden  in child class but static overloaded methods are possible but different parameters
Example:

class NIT {
    // static method of base class
    public static void test() {
        System.out.println("Base class static test method");
    }
    // Non-static method of base class
    public void display() {
        System.out.println("Base class of display non static method");
    }
}
public class InterviewTest {
    public static void main(String[] args) throws Exception {
        NIT nit = new NIT1();
        nit.test();
        nit.display();
    }
}
  1. What is classLoader?

ClassLoader in java is located at JRE(Java Runtime Environment) and it is dynamically loads java class into JVM(Java Virtual Machine). Java classes aren’t loaded into memory all at once, but when required by an application and ClassLoader loads class dynamically into memory.
By using getClassLoader() method to know classLoader loads the class or not and if any class is not available it return NoClassDefFoundError or ClassNotFoundException.
There are three types of classLoaders.

    • Bootstrap ClassLoader
    • System ClassLoader
    • Extender ClassLoader

  1. What is exception handling?

Exception handling in java is a process to handle the runtime errors by using throw and throws keywords or try, catch and finally keywords.
Java.lang.Throwable is a parent class of Java Exception
There are Checked and UnChecked exceptions in java.

  1. What is the difference between Exception and error in java?

Error is a result from system resources but all errors are comes at run time and unchecked so we cannot handle errors. Exceptions are checked or unchecked exception but we handle Exception at compile time or runtime.

  1. What is the difference between throw and throws in java?

In Java throw keyword is used to throw an exception explicitly in the code, inside the function or the block of code.
In Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code.
Example 1: for throw keyword

public class InterviewTest {
    void test(int num)
    {
        if(num<0)
        {
            throw new ArithmeticException("number must be positive");
            //System.out.println("number must be positive");
        }
        else
        {
            System.out.println(num);
        }
    }
    public static void main(String[] args) throws Exception {
        InterviewTest nit = new InterviewTest();
        nit.test(-5);
    }
}


Example 2: for throws keyword

public class InterviewTest {
   
    int test(int q, int r) throws ArithmeticException
    {
        int div = q/r;
        return div;
    }
    public static void main(String[] args) throws Exception {
        InterviewTest nit = new InterviewTest();
        nit.test(5, 0);
       
        /*
        * try { System.out.println(nit.test(5, 0)); } catch (ArithmeticException e) {
        * System.out.println("Number cannot be divisible by zero"); }
        */
    }
}
  1. What is the difference between checked and unchecked exceptions?

Checked exceptions are compile time exceptions like IOException and SQLException but unchecked exceptions are runtime exceptions like ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

  1. How can we handle checked exception?

Checked exceptions are compile time exceptions and these exceptions are handle by using try and catch method or by using throws keyword.
Example: throws Checked Exception at compile time

public class InterviewTest {
    public static void main(String[] args) throws Exception {
        FileInputStream file = new FileInputStream("D:/input.txr"); // throws FileNotFoundException
    }
}


Example: handle checked exception

public class InterviewTest {
    public static void main(String[] args) throws Exception {
        try {
            FileInputStream file = new FileInputStream("D:/input.txr"); // FileNotFoundException
        } catch (FileNotFoundException e) {
            System.out.println("This file not found");
        }
       
    }
}
  1. What is runtimeException?

Runtime exception is a unchecked exception. Runtime exceptions are might be throw during the execution process it might not be catch.

public class InterviewTest {
    public static void main(String[] args) throws Exception {
        String name = null;
        System.out.println(name.length());// NullPointerException
    }
}
  1. What is Custom exception?

Custom Exception is nothing but user defined exceptions or own exception derived from exception class.

  1. What is the difference between final, finally, and finalize keywords?

In java final is a keyword used to restrict the modification of a variable, method, or class. finally keyword is a block used to ensure that a section of code is always executed, even if an exception is thrown. finalize is a method used to perform cleanup processing on an object before it is garbage collected.

  1. What is the difference between ClassNotFoundException and NoClassDefFoundError?

ClassNotFoundException is thrown when looking up a class that is not found classpath or using an invalid name to look up a class that not found on the runtime classpath. NoClassDefFoundError occurs when a compiled class references another class that isn't on the runtime classpath.

  1. What is the use of printStackTrace() in exception handling of java?

It is used to print exception or error in console with other details like class name along with where exception occured and it if found at java.lang.Throwble class to handle exception or error.
It used to understand easy handle the exception
Syntax:
public void printStackTrace()
Example:

public class InterviewTest {
    public static void main(String[] args)  {
        try
        {
            String name = null;
            name.length();
        }catch (Throwable e) {
            e.printStackTrace();
        }
    }
}


Execution:
NullPointerException : Cannot invoke "String.length()" because "name" is null.

Scope @ NareshIT:

The Core Java Online Training program at NareshIT is a comprehensive hands-on learning experience through which the student gets exposed to front-end, middleware and back-end technologies. These phase-end projects are designed to provide practical solutions to real world problems so that the students are equipped with up-to-date skills that meet industry requirements.


Industry experts teach the program and its content is based on current market trends. You will learn about end-to-end application development that not only makes robust but also feature-laden applications.

At the end of this course, you will be awarded an industry recognized completion certificate that serves as testimony to your knowledge in Core Java development thus increasing your chances of employment.