Java Interview Questions Part 6

Does constructor return any value?

Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an explicit return type with the constructor). More Details.

How to create packages in Java?

If you are using the programming IDEs like Eclipse, NetBeans, MyEclipse, etc. click on file->new->project and eclipse will ask you to enter the name of the package. It will create the project package containing various directories such as src, etc. If you are using an editor like notepad for java programming, use the following steps to create the package.

  • Define a package package_name. Create the class with the name class_name and save this file with your_class_name.java.
  • Now compile the file by running the following command on the terminal.
  1. javac -d . your_class_name.java  

The above command creates the package with the name package_name in the present working directory.

  • Now, run the class file by using the absolute class file name, like following.
  1. java package_name.class_name  

Can I import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or the same class multiple times. Neither compiler nor JVM complains about it. However, the JVM will internally load the class only once no matter how many times you import the same class.

What are the advantages and disadvantages of object cloning?

Advantage of Object Cloning

  • You don't need to write lengthy and repetitive codes. Just use an abstract class with a 4- or 5-line long clone() method.
  • It is the easiest and most efficient way of copying objects, especially if we are applying it to an already developed or an old project. Just define a parent class, implement Cloneable in it, provide the definition of the clone() method and the task will be done.
  • Clone() is the fastest way to copy the array.

Disadvantage of Object Cloning

  • To use the Object.clone() method, we have to change many syntaxes to our code, like implementing a Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling Object.clone(), etc.
  • We have to implement the Cloneable interface while it does not have any methods in it. We have to use it to tell the JVM that we can perform a clone() on our object.
  • Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.
  • Object.clone() does not invoke any constructor, so we do not have any control over object construction.
  • If you want to write a clone method in a child class, then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.
  • Object.clone() supports only shallow copying, but we will need to override it if we need deep cloning.

What is the Collection framework in Java?

Collection Framework is a combination of classes and interface, which is used to store and manipulate the data in the form of objects. It provides various classes such as ArrayList, Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set, etc. for this purpose.

What is the difference between Set and Map?

The differences between the Set and Map are given below.

  • Set contains values only whereas Map contains key and values both.
  • Set contains unique values whereas Map can contain unique Keys with duplicate values.
  • Set holds a single number of null value whereas Map can include a single null key with n number of null values.

What is the difference between Collection and Collections?

The differences between the Collection and Collections are given below.

  • The Collection is an interface whereas Collections is a class.
  • The Collection interface provides the standard functionality of data structure to List, Set, and Queue. However, Collections class is to sort and synchronize the collection elements.
  • The Collection interface provides the methods that can be used for data structure whereas Collections class provides the static methods which can be used for various operation on a collection.

What is the advantage of Properties file?

If you change the value in the properties file, you don't need to recompile the java class. So, it makes the application easy to manage. It is used to store information which is to be changed frequently. Consider the following example.

  1. import java.util.*;  
  2. import java.io.*;  
  3. public class Test {  
  4. public static void main(String[] args)throws Exception{  
  5.     FileReader reader=new FileReader("db.properties");  
  6.       
  7.     Properties p=new Properties();  
  8.     p.load(reader);  
  9.       
  10. 10.     System.out.println(p.getProperty("user"));  
  11. 11.     System.out.println(p.getProperty("password"));  

12. }  

13. }  

Output

system

oracle

What is the difference between ArrayList and Vector?

No.

ArrayList

Vector

1)

ArrayList is not synchronized.

Vector is synchronized.

2)

ArrayList is not a legacy class.

Vector is a legacy class.

3)

ArrayList increases its size by 50% of the array size.

Vector increases its size by

doubling the array size.

4)

ArrayList is not ?thread-safe? as it is not synchronized.

Vector list is ?thread-safe? as

it?s every method is synchronized.

What is the difference between ArrayList and LinkedList?

No.

ArrayList

LinkedList

1)

ArrayList uses a dynamic array.

LinkedList uses a doubly linked list.

2)

ArrayList is not efficient for manipulation because too much is required.

LinkedList is efficient for manipulation.

3)

ArrayList is better to store and fetch data.

LinkedList is better to manipulate data.

4)

ArrayList provides random access.

LinkedList does not provide random access.

5)

ArrayList takes less memory overhead as it stores only object

LinkedList takes more memory overhead,

 as it stores the object as well as the

 address of that object.

What is the difference between List and Set?

The List and Set both extend the collection interface. However, there are some differences between the both which are listed below.

  • The List can contain duplicate elements whereas Set includes unique items.
  • The List is an ordered collection which maintains the insertion order whereas Set is an unordered collection which does not preserve the insertion order.
  • The List interface contains a single legacy class which is Vector class whereas Set interface does not have any legacy class.
  • The List interface can allow n number of null values whereas Set interface only allows a single null value.

What is the difference between HashSet and HashMap?

The differences between the HashSet and HashMap are listed below.

  • HashSet contains only values whereas HashMap includes the entry (key, value). HashSet can be iterated, but HashMap needs to convert into Set to be iterated.
  • HashSet implements Set interface whereas HashMap implements the Map interface
  • HashSet cannot have any duplicate value whereas HashMap can contain duplicate values with unique keys.
  • HashSet contains the only single number of null value whereas HashMap can hold a single null key with n number of null values.

What is the difference between HashMap and Hashtable?

No.

HashMap

Hashtable

1)

HashMap is not synchronized.

Hashtable is synchronized.

2)

HashMap can contain one null key and multiple null values.

Hashtable cannot contain any null key or null value.

3)

HashMap is not ?thread-safe,? so it is useful for non-threaded applications.

Hashtable is thread-safe, and

it can be shared between various threads.

4)

4) HashMap inherits the AbstractMap class

Hashtable inherits the Dictionary class.

What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

What is the difference between Array and ArrayList?

The main differences between the Array and ArrayList are given below.

SN

Array

ArrayList

1

The Array is of fixed size, means we cannot resize the array as per need.

ArrayList is not of the fixed size

we can change the size dynamically.

2

Arrays are of the static type.

ArrayList is of dynamic size.

3

Arrays can store primitive data types as well as objects.

ArrayList cannot store the primitive

data types it can only store the objects.


What is the difference between the length of an Array and size of ArrayList?

The length of an array can be obtained using the property of length whereas ArrayList does not support length property, but we can use size() method to get the number of objects in the list.

Finding the length of the array

  1. Int [] array = new int[4];  
  2. System.out.println("The size of the array is " + array.length);  
  3.           

Finding the size of the ArrayList

  1. ArrayList<String> list=new ArrayList<String>();    
  2. list.add("ankit");    
  3. list.add("nippun");  
  4. System.out.println(list.size());  

What are the main differences between array and collection?

Array and Collection are somewhat similar regarding storing the references of objects and manipulating the data, but they differ in many ways. The main differences between the array and Collection are defined below:

  • Arrays are always of fixed size, i.e., a user can not increase or decrease the length of the array according to their requirement or at runtime, but In Collection, size can be changed dynamically as per need.
  • Arrays can only store homogeneous or similar type objects, but in Collection, heterogeneous objects can be stored.
  • Arrays cannot provide the ?ready-made? methods for user requirements as sorting, searching, etc. but Collection includes readymade methods to use.

How to reverse ArrayList?

To reverse an ArrayList, we can use reverse() method of Collections class. Consider the following example.

  1. import java.util.ArrayList;  
  2. import java.util.Collection;  
  3. import java.util.Collections;  
  4. import java.util.Iterator;  
  5. import java.util.List;  
  6. public class ReverseArrayList {  
  7. public static void main(String[] args) {  
  8.      List list = new ArrayList<>();  
  9.      list.add(10);  
  10. 10.      list.add(50);  
  11. 11.      list.add(30);  
  12. 12.      Iterator i = list.iterator();  
  13. 13.      System.out.println("printing the list....");  
  14. 14.      while(i.hasNext())  
  15. 15.      {  
  16. 16.          System.out.println(i.next());  
  17. 17.      }  
  18. 18.      Iterator i2 = list.iterator();  
  19. 19.      Collections.reverse(list);  
  20. 20.      System.out.println("printing list in reverse order....");  
  21. 21.      while(i2.hasNext())  
  22. 22.      {  
  23. 23.          System.out.println(i2.next());  
  24. 24.      }  
  25. 25.     }  

26. }  

Output

printing the list....

10

50

30

printing list in reverse order....

30

50

10

When to use ArrayList and LinkedList?

LinkedLists are better to use for the update operations whereas ArrayLists are better to use for the search operations.

How to make Java ArrayList Read-Only?

We can obtain java ArrayList Read-only by calling the Collections.unmodifiableCollection() method. When we define an ArrayList as Read-only then we cannot perform any modification in the collection through  add(), remove() or set() method.

What is JDBC?

JDBC is a Java API that is used to connect and execute the query to the database. JDBC API uses JDBC drivers to connect to the database. JDBC API can be used to access tabular data stored into any relational database.

 More details.

What are the steps to connect to the database in java?

The following steps are used in database connectivity.

  • Registering the driver class:

The forName() method of the Class class is used to register the driver class. This method is used to load the driver class dynamically. Consider the following example to register OracleDriver class.

  1. Class.forName("oracle.jdbc.driver.OracleDriver");  
  • Creating connection:

The getConnection() method of DriverManager class is used to establish the connection with the database. The syntax of the getConnection() method is given below.

  1. 1) public static Connection getConnection(String url)throws SQLException  
  2. 2) public static Connection getConnection(String url,String name,String password)  
  3. throws SQLException  

Consider the following example to establish the connection with the Oracle database.

  1. Connection con=DriverManager.getConnection(  
  2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");  
  • Creating the statement:

The createStatement() method of Connection interface is used to create the Statement. The object of the Statement is responsible for executing queries with the database.

  1. public Statement createStatement()throws SQLException  

consider the following example to create the statement object

  1. Statement stmt=con.createStatement();  
  • Executing the queries:

The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method is given below.

  1. public ResultSet executeQuery(String sql)throws SQLException  

Example to execute the query

  1. ResultSet rs=stmt.executeQuery("select * from emp");  
  2. while(rs.next()){  
  3. System.out.println(rs.getInt(1)+" "+rs.getString(2));  
  4. }  

However, to perform the insert and update operations in the database, executeUpdate() method is used which returns the boolean value to indicate the successful completion of the operation.

  • Closing connection:

By closing connection, object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.

Syntax of close() method is given below.

  1. public void close()throws SQLException  

Consider the following example to close the connection.

  1. con.close();  

More details.

What are the JDBC statements?

In JDBC, Statements are used to send SQL commands to the database and receive data from the database. There are various methods provided by JDBC statements such as execute(), executeUpdate(), executeQuery, etc. which helps you to interact with the database.

There is three type of JDBC statements given in the following table.

Statements

Explanation

Statement

Statement is the factory for resultset.

It is used for general purpose access to the database.

It executes a static SQL query at runtime.

PreparedStatement

The PreparedStatement is used when

we need to provide input parameters to the query

at runtime.

CallableStatement

CallableStatement is used when we need to

access the database stored procedures.

 It can also accept runtime parameters.

What are the differences between execute, executeQuery, and executeUpdate?

execute

executeQuery

executeUpdate

The execute method can be used for any SQL statements(Select and Update both).

The executeQuery method can be used only with the select statement.

The executeUpdate

 method can

 be used to

update/delete/insert

operations

 in the database.

The execute method returns a boolean type value where true indicates that the ResultSet s returned which can later be extracted and false indicates that the integer or void value is returned.

The executeQuery() method returns a ResultSet object which contains the data retrieved by the select statement.

The executeUpdate() method returns

 an integer value representing

the number of records affected where

 0 indicates that query returns nothing.


What is the role of the JDBC DriverManager class?

The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver().

What are the differences between stored procedure and functions?

The differences between stored procedures and functions are given below:

Stored Procedure

Function

Is used to perform business logic.

Is used to perform the calculation.

Must not have the return type.

Must have the return type.

May return 0 or more values.

May return only one value.

The procedure supports input and output parameters.

The function supports only input parameter.

Exception handling using try/catch block can be used in stored procedures.

Exception handling using try/catch

can't be used in user-defined functions.

What is the major difference between java.util.Date and java.sql.Date data type?

The major difference between java.util.Date and java.sql.Date is that, java.sql.Date represents date without time information whereas, java.util.Date represents both date and time information.

How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?

By InetAddress.getByName("192.18.97.39").getHostName() where 192.18.97.39 is the IP address. Consider the following example.

  1. import java.io.*;    
  2. import java.net.*;    
  3. public class InetDemo{    
  4. public static void main(String[] args){    
  5. try{    
  6. InetAddress ip=InetAddress.getByName("195.201.10.8");    
  7.   
  8. System.out.println("Host Name: "+ip.getHostName());    
  9. }catch(Exception e){System.out.println(e);}    

10. }    

11. }    

  1. 12.       

What is the life-cycle of a servlet?

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

What is difference between Get and Post method?

Get

Post

1) 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.

2) Not Secured because data is exposed in URL bar.

Secured because data is not exposed in URL bar.

3) Can be bookmarked

Cannot be bookmarked

4) Idempotent

Non-Idempotent

5) It is more efficient and used than Post

It is less efficient and used

more details...

Who is responsible to create the object of servlet?

The web container or servlet container.

When servlet object is created?

At the time of first request.

What are Cookies?

A cookie is a small piece of information that is persisted between the 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.

more details...

What are the differences between Statement and PreparedStatement interface?

Statement

PreparedStatement

The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet; i.e., it provides the factory method to get the object of ResultSet.

The PreparedStatement interface is

a subinterface of Statement.

 It is used to execute the parameterized

query.

In the case of Statement, the query is compiled each time we run the program.

In the case of PreparedStatement,

 the query is compiled only once.

The Statement is mainly used in the case when we need to run the static query at runtime.

PreparedStatement is used when

we need to provide input parameters

to the query at runtime.

More details.

What are the benefits of PreparedStatement over Statement?

The benefits of using PreparedStatement over Statement interface is given below.

  • The PreparedStatement performs faster as compare to Statement because the Statement needs to be compiled everytime we run the code whereas the PreparedStatement compiled once and then execute only on runtime.
  • PreparedStatement can execute Parameterized query whereas Statement can only run static queries.
  • The query used in PreparedStatement is appeared to be similar every time. Therefore, the database can reuse the previous access plan whereas, Statement inline the parameters into the String, therefore, the query doesn't appear to be same everytime which prevents cache reusage.

How can we execute stored procedures using CallableStatement?

Following are the steps to create and execute stored procedures. Here, we are creating a table user420 by using a stored procedure and inserting values into it.

  • Create the procedure in the database.

To call the stored procedure, you need to create it in the database. Here, we are assuming that the stored procedure looks like this.

  1. create or replace procedure "INSERTR"  
  2. (id IN NUMBER,  
  3. name IN VARCHAR2)  
  4. is  
  5. begin  
  6. insert into user420 values(id,name);  
  7. end;  
  8. /     

The table structure is given below:

  1. create table user420(id number(10), name varchar2(200));  
  • Establish a network connection.
  1. Class.forName("oracle.jdbc.driver.OracleDriver");  
  2. Connection con=DriverManager.getConnection(  
  3. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  • Create the Object of CallableStatement.
  1. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");  
  • Provide the values and execute the query by using the following syntax.
  1. stmt.setInt(1,1011);  
  2. stmt.setString(2,"Amit");  
  3. stmt.execute();  
  • Check the database; the values will be found there. However, the complete code will look like the following.
  1. import java.sql.*;  
  2. public class Proc {  
  3. public static void main(String[] args) throws Exception{  
  4.   
  5. Class.forName("oracle.jdbc.driver.OracleDriver");  
  6. Connection con=DriverManager.getConnection(  
  7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  8.   
  9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");  

10. stmt.setInt(1,1011);  

11. stmt.setString(2,"Amit");  

12. stmt.execute();  

  1. 13.   

14. System.out.println("success");  

15. }  

16. }  

Which interface is responsible for transaction management in JDBC?

The Connection interface provides methods for transaction management such as commit(), rollback() etc.

More details.

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: The JDBC-ODBC bridge driver uses the ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of the thin driver. It is easy to use and can be easily connected to any database.
  2. Native-API driver (partially java 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. Its performance is better than JDBC-ODBC bridge driver. However, the native driver must be installed on each client machine.
  3. Network Protocol driver (fully java driver): The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is entirely written in Java. There is no requirement of the client-side library because of the application server that can perform many tasks like auditing, load balancing, logging, etc.
  4. Thin driver (fully java driver): The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as the thin driver. It is entirely written in Java language. Its performance is better than all other drivers however these drivers depend upon the database.

More details.

What does the 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. By default, ResultSet object can move in the forward direction only and is not updatable. However, we can make this object to move the forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int, int) method.

More details.

What are the different types of ResultSet?

ResultSet is categorized by the direction of the reading head and sensitivity or insensitivity of the result provided by it. There are three general types of ResultSet.

Type

Description

ResultSet.TYPE_Forward_ONLY

The cursor can move in the forward direction only.

ResultSet.TYPE_SCROLL_INSENSITIVE

The cursor can move in both the direction (forward and backward).

 The ResultSet is not sensitive to the changes made

 by the others to the database.

ResultSet.TYPE_SCROLL_SENSITIVE

The cursor can move in both the direction.

The ResultSet is sensitive to the changes made by the

others to the database.

What does the 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. Consider the following example.

  1. import java.sql.*;  
  2. class Dbmd{  
  3. public static void main(String args[]){  
  4. try{  
  5. Class.forName("oracle.jdbc.driver.OracleDriver");  
  6.   
  7. Connection con=DriverManager.getConnection(  
  8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  9. DatabaseMetaData dbmd=con.getMetaData();  
  10. 10.   

11. System.out.println("Driver Name: "+dbmd.getDriverName());  

12. System.out.println("Driver Version: "+dbmd.getDriverVersion());  

13. System.out.println("UserName: "+dbmd.getUserName());  

14. System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());  

15. System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());  

  1. 16.   

17. con.close();  

18. }catch(Exception e){ System.out.println(e);}  

19. }  

20. }  

Output

Driver Name: Oracle JDBC Driver

Driver Version: 10.2.0.1.0XE

Database Product Name: Oracle

Database Product Version: Oracle Database 10g Express Edition Release 10.2.0.1.0 -Production

More details.

What does the JDBC ResultSetMetaData interface?

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

More details.

猜你喜欢

转载自www.cnblogs.com/codingyangmao/p/12765983.html