JAVA INTERVIEW QUESTIONS WITH ANSWERS

  • By
  • June 2, 2022
  • JAVA

JAVA INTERVIEW QUESTIONS WITH ANSWERS –

Q 1. What is an Iterator?

A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one

Cursors or iterators are mainly used to fetch the elements of any collection. 

There are following three types of cursors we have in Collection Framework:

1.Iterator

2.ListIterator

3.Enumeration

1.Iterator Cursors(universal cursors) of Collection Framework in Java

By using this cursor we can access the elements of a collection in the forward direction only.

This cursor can be applied to any type of  Collection –

An Iterator is an interface in java that’s why we cannot create an object directly by using a new keyword.  But we can use iterator() method to create an object of it

Creation of Iterator –

Syntax : Iterator it = collection_obj.iterator();

In above syntax, the iterator() method internally creates and returns an object of a class that implements the Iterator Interface directly.

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

 

2.ListIterator Cursors of Collection Framework in Java

By using this cursor we can  access the elements of Collection in both forward and backward directions. 

This cursor can be applied only for only those classes(ArrayList,LinkedList,Stack,Vector) who implements List interface

A ListIterator is an interface in java that’s why we cannot create an object directly by using a new keyword.  But we can use listIterator() method to create an object of it.

Creation of ListIterator

Syntax : ListIterator it = l.listIterator();

In above syntax, the listIterator() method internally creates and returns an object of a class that implements the Iterator Interface directly.

 

3.Enumeration Cursors of Collection Framework in Java

By using this cursor we can access the elements of a collection in the forward direction only.

This is a legacy cursor(Legacy classes and interfaces are the classes and interfaces that formed the collections framework in the earlier versions of Java and have now been restructured) and can be applied only for legacy classes like Stack, Vector

An Enumeration  is an interface in java that’s why we cannot create an object directly by using a new keyword.  But we can use elements()  method to create an object of it

 Creation of Enumeration –

Syntax : 

Enumeration e = v.elements();

In above syntax, the elements() method internally creates and returns an object of a class that implements the Iterator Interface directly.

Q 2. What Collection Framework in Java?

we can defined  group of objects in one single unit called as collection means collection represents group of objects together form one single unit. The Collection in Java is a framework is nothing but an architecture having some interfaces, classes and methods which store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on data such as searching, sorting, insertion, manipulation, and deletion.

The Java Collection framework provides many interfaces (Set, List, Map) and classes (ArrayList, Vector, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, SortedMap, TreeMap).

 

 Q 3.What do you understand about Thread Priority?

Priority is nothing but a number which is assigned to the thread at a time of thread creation and according to that priority number threads get executed. Whenever we create a thread in the program , it always inherits priority from its parent thread. Each thread is assigned with a priority between1 to 10. 

The thread whose priority is higher get a higher chance to get executed as compared to other threads. But if multiple threads have the same priority then the thread scheduler can select any random thread based on their arrival time and execution time. To find the priority of a thread thread scheduler uses  Preemptive Priority Scheduling Algorithm.

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

 

Q 4. What is Thread Scheduler and Time Slicing?

A thread scheduler in java is the part of the JVM that responsible for scheduling the execution of a thread, means thread deicides that which thread should run and which should wait based on their priority, arrival time and execution time

The thread scheduler always chooses to get executed only if that thread is in the RUNNABLE state.

But there is no guarantee which thread will be chosen by the thread scheduler  if you have multiple threads in RUNNABLE state.

There are a number of factors or criteria which are used to select a thread.

 

1.Priority

Priority is nothing but a number which is assigned to the thread at a time of thread creation and according to that priority number threads get executed. Whenever we create a thread in the program , it always inherits priority from its parent thread. Each thread is assigned with a priority between1 to 10. The thread whose priority is higher get a higher chance to get executed as compared to other threads.

But if multiple threads have the same priority then the thread scheduler can select any random thread based on their arrival time and execution time. 

 

2.Arrival time

The thread scheduling process is also depends on the arrival time of the thread. If two or more threads have the same priority then the thread scheduler checks the arrival time of threads.

 

3.Time slice

Time slicing is nothing but the process  of allocating execution time to the thread is called time slicing.

 

Q 5. Which is more preferred – Synchronized block or Synchronized method ?

Synchronized block is a more preferred over Synchronized method it doesn’t lock the Object whereas  synchronized methods does lock the Object. If there are multiple synchronization blocks present in our class, even though they are not related to each other, it will stop them from execution and put them in NON RUNNABLE  state to get the lock on an Object.

 

Q 6. How to create a daemon thread in Java?

By using setDaemon() method you can mark the user thread as a daemon thread.  setDaemon(boolean b) accepts boolean value true or false as a parameter. If we provide true i.e setDaemon(true) then it converts thread to the daemon thread.

 

Q 7. What happens when an exception is thrown by the main method?

When an exception is thrown by the main() method, JVM terminates the program and prints the exception message and stack trace in the system console.

 

Q 8. How to get the database server details in a Java program?

By using the interface DatabaseMetaData we can get the details of the database with which we are currently working. This Databasemetadata interface has some methods which helps us to get database information.

//Program

import java.sql.Connection;

import java.sql.DatabaseMetaData;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

 

public class Databasemetadata {

 

public static void main(String args123[]) throws SQLException,ClassNotFoundException {

// TODO Auto-generated method stub

 

Class.forName(“com.mysql.jdbc.Driver”);

Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/tv”,”root”,”12345pnn&”);

DatabaseMetaData dbmd = con.getMetaData();

System.out.println(“Driver name : “+dbmd.getDriverName());

System.out.println(“Driver version : “+dbmd.getDriverVersion());

System.out.println(“User name : “+dbmd.getUserName());

System.out.println(“Database product name : “+dbmd.getDatabaseProductName());

System.out.println(“product version : “+dbmd.getDatabaseProductVersion());

con.close();

}

 

}

Q 9. What is JDBC PreparedStatement?

Prepared Statement in Java is one of the ways to execute SQL queries using JDBC API. 

In Java we have three types of interfaces: Statement, Prepared Statement and Callable Statement for executing queries. 

In this , Statement is used for executing general-purpose queries, Prepared Statement is used for executing a parametric query, and Callable Statement is used for executing Stored Procedures.

The Prepared Statement interface is a sub interface of Statement and  is used to execute parameterized queries in the database.

“?” is nothing but a placeholder in java.

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

 

Benefits of Java Prepared Statement –

  1. PreparedStatement allows you to write dynamic queries.
  1. PreparedStatement is faster than Statement interface  in Java because, in prepared statements the queries are pre compiled so the compiler does not need to compile the query every time so it saves the compilation time of the program.
  2. PreparedStatement queries are more readable and secure(because they are used to prevent SQL injection attacks). PS prevents sql injection attack because ,in which query and data both gets submitted on the server in different requests. e.g of parameterized query:

 

  String sql=”insert into emp values(?,?,?)”; 

here,we are passing parameter (?) for the values. Its value will be set by calling the setter methods of the PreparedStatement interface. 

Methods:

    i.prepareStatement()      

 

   i.public void setInt(int paramIndex, int value)

     It sets the integer type of value to the given parameter index of ‘?’.

 

   ii.public void setString(int paramIndex, String value)

       It sets the String type of value to the given parameter index of ‘?’.

 

   iii.public void setFloat(int paramIndex, float value)

      It sets the float type of value to the given parameter index of ‘?’.

 

   iv.public void setDouble(int paramIndex, double value)

     It sets the double type of value to the given parameter index of ‘?’.

 

   v.public int executeUpdate()

  It  executes the query. It is used to perform create, drop, insert, update, delete etc operations  on the database..

 

   vi.public ResultSet executeQuery()

    executes the select query. It returns an instance of ResultSet.

 

   vii..public boolean execute(): 

        It is used to execute queries that may return a result of multiple queries.

 

Q 10. What is the difference between Java platform and other platforms?

What is a Platform?

Platform is the combination of Operating system and processor of our machine There are two types of Platform

     1.Software based platform

     2.Hardware based platform

 

Differences between Java platform and other platforms are given below::

Java is  only a software-based platform while others can be hardware or software based platforms.

Java supports the features of WORA (Write once run anywhere),which means it is platform independent, but many other platforms do not provide such feature.

Java provides  both a compiled as well as interpreted environment whereas other platforms provide either compiled or interpreted.

 

Q 11. Explain the “write once and run anywhere” principle of java ?

When we compile our .java file which contains source code, that .java file goes to  the Java Compiler there it  compiles a java program (.java file) and converts it into class files (.class) which contains a  bytecodes , which is the intermediatery language between source code and machine code . These bytecodes are platform independent, so with the help of JVM (Java virtual machine), the java program can run on multiple different platforms. The JVM (Java virtual machine) is platform dependent i.e its implementation differs from platform to platform (like windows, linux etc.), but these JVMs can execute the same java bytecode that is called ‘write once and run anywhere’ principle of java So, this means Java can be written on any system, then  compiled into a standard bytecode and be expected to run on any device which consists of JVM.

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

 

Q 12. Can we save the file with Empty .java  in java?

Yes we can save because the java compiler doesn’t consider it as a saved file name or not except our class as a  public specified we can save any name or empty but  but class must not be public, it means that it must be default. If the class is public then errors will occur.

 

Author:-

Pooja Nandode-Bhavsar

SevenMentor Pvt Ltd

Call the Trainer and Book your free demo Class for now!!!
call icon

© Copyright 202! | Sevenmentor Pvt Ltd.

 

 

 

Submit Comment

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

*
*