Top 100 Frequently asked Java Questions

 

This section will cover most popular and frequently asked java questions.

 

 

1. What is Java ?

Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on  a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

2. List the platforms supported by Java Programming ?

Java runs on  numerous of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux  like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.

3. List atlest five features of Java ?

Some features of Java are Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded.

4. What are tokens? Name the 5 types of tokens available in Java with an example each.

 The smallest individual unit in a program is known as a token. The five types of tokens are- :

a) Keywords:- public, static, void, import etc. (Java’s own terms)

b) Identifiers:- (variables) alphabets, digits, under score, dollar sign etc.

c) Literals:- (Constants) integer literals, floating literals, boolean literals, character literals, string literal, the null literal.

d) Punctuators (separators):- () {} [] ; , e) Operators = + – < >

5. Why Java is called Arcitectural Neutral ?

It’s compiler generates an architecture-neutral object file format, which makes the compiled code to be executable on  many processors, with the presence of Java runtime system.

6. Why Java is enabled for High Performance ?

Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that converts Java bytecode, which is a program that contains instructions that must be interpreted into instructions that can be sent directly to the processor.

7. Why Java is called dynamic ?

Java is designed to change to an evolving environment. Java programs can carry huge amount of run-time information that can be used to verify and resolve accesses to objects on  run-time.

8.What is JVM(Java Vitual Machince) and how it reflects on  the surroundings of Java’s platform independent feature?

When Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine JVM on  whichever platform it is being run.

9. List Java IDE’s ?

Netbeans, Eclipse, etc.

10. What type of variables a class can consist of ?

A class can consists of Local variable, instance variables and class variables.

11. What do you mean by Local Variable ?

Variables that defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.

12. What do yo mean by Instance Variable ?

Instance variables are variables that are defined within a class but outside any method. These variables are instantiated when the class is loaded.

13. What do you mean by Class Variable ?

These are variables that are declared with in a class, outside any method, with the static keyword.

14. What do you mean by Singleton class ?

Singleton class control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.

15. What do you understand by static methods and static variables ?

They are methods and variables shared by all the objects in a class. Their static nature is a character of the class and not the object itself. 

16. What do you understand by the word Object-Oriented Paradigm ?

When your programming paradigm is dependent on objects containing data with methods defined within the class to which they belong, it is referred to as Object Oriented Paradigm. 

17. Difference between Object Oriented and Object-Based language ?

Object Oriented languages such as Java and C++ follow all the concepts of an Object Oriented Program and do not have inbuilt objects. 
Object-Based languages like JavaScript do not follow all OOPs concepts-such as inheritance-and do have I built objects. 

18. What is method signature ? What are the things it consist of ?

Method signature is used by the compiler to differentiate the methods. Method signature consist of three things.

a) Method name

b) Number of arguments

c) Types of arguments

19. What is the use of Constructor? 

Constructor is used  to initialize the state of any object. When you create a new object using a new keyword, a default constructor is invoked. This must have a name similar to the class name. 

20. What is the use of ‘this’ keyword ?

You can use ‘this’ to refer to a current object, invoke the current class method or class constructor. You can also pass it on as an argument into your methods or constructors. 

21. What do you understand by the term aggeration ?

It is a type of weak relation you can create between two classes, where one contain references to another class contained within it. 

22. What is the purpose of composition ?

You can use composition to hold the reference of one class within another class, and in this case, the contained object cannot exist without the class containing it. It is a type of aggregation. 

23. What do you understand by the term annotation ?

Annotation is a tag you use to symbolize metadata that represents your class, interface, and fields among others. 
They are used by the compiler and the JVM and don’t directly influence the operations. 

24. What do you understand by the term enumeration ?

Enumeration is an interface you can use to access original data structure from which the enumeration is obtained. 

25. What is the function of Synchronized Block ?

Synchronized block scope is smaller than method, you can use it to lock an object for each shared resource.

26. List advantaged of using Java ?

Java is a high-level object-oriented programming language used for developing games, device systems, and applications. 
It is secure, fast, reliable, portable and platform independent. 

27. Explain the statement – public static void main Stringargs[]

public − it is the access specifier.
static − it allows main to be called without instantiating a particular instance of a class.
void − it affirns the compiler that no  value is returned by main.
main − this method is called at the beginning of a Java program.
String args[ ] − args parameter is an instance array of class String

28. Write a note on Declaration and Initialization.

Variables can be declared and initialized in one statement:
Example:
int numDimes = 4;
double length = 52.3;
char courseSection = ‘J’;
boolean done = true;
String lastName = “Reid-Miller”;
int count = 3 + 2;

29. Can you declare an array without assigning the size of an array ?

No we cannot declare an array without assigning size.
If we declare an array without size, it will throw compile time error
Example: marks = new int []; //COMPILER ERROR

30. What is the default value of Array ?

Any new Array is always initialized with a default value as follows:
For byte, short, int, long – default value is zero (0).
For float, double – default value is 0.0.
For Boolean – default value is false.
For object – default value is null.

31. Can we declare array size as a negative number ?

No. We cannot declare the negative integer as an array size.
If we declare, there will be no compile-time error.
However, we will get NegativeArraySizeException at run time.

32. How to find the duplicate in an array ?

String str = "HI RAJU I AM FINE RAJU"; // String with a duplicate word.
String[] words = str.split(" "); // Splitting and converting to Array .
for(int i = 0; i < words.length; i++){ //iterating array inside for loop.
for(int j = i+1; j < words.length; j++){ //iterating same array inside another for loop
if (words[i].equals(words[j])){
// Using equal method i am verifying which word is repeating .
System.out.println( words[i]); // here it will print duplicate .
}
}
}

33. How to get largest and smallest number in an array ?

We use two variables to store largest and smallest number.

First, we initialize largest with Integer.MIN_VALUE and

Next, we initialize smallest with Integer.MAX_VALUE.

In each iteration of the for loop, we will compare present number with largest and smallest number, and we will update

If a number is larger than largest, then it cannot be smaller than smallest. That is it is not required check if the first condition is true,

We will use the if-else control construct, where else part will only execute if the first condition is false.

import java.util.Arrays;
public class MaximumMinimumArrayExample{
public static void largestAndSmallest(int[] numbers) {
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
for (int number : numbers) {
if (number > largest) {
largest = number;
}
else if (number < smallest) {
smallest = number;
}
 }
System.out.println("Largest is : " + largest);
System.out.println("Smallest is : " + smallest);
 }
 }

34.What is the logic to reverse the array

Declare a String Array String[] s = new String[]{“My”,”Leg”,”is”,”cut”};

Iterate it using for loop get all elements in reverse order means end point to start point.

Class Demo
{
public static void main(String[] args)
{
String[] s = new String[]{"My","Leg","is","injured"};
for(int i=s.length-1; i>=0; i--)
{
System.out.println("reverse "+s[i]);
}
}
}

35. Write a program to insert an element  in the specific position in the array.

Insert an element in 3rd position of the array (index->2, value->5)

Iterate the given array in reverse order using for loop.

Now insert given position and value after for loop.

class Demo
{
public static void main(String[] args)
{
int myArr[] = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 };
int largest = myArr[0];
int secondLargest = myArr[0];
System.out.println("The given array is:" );
for (int i = 0; i < myArr.length; i++) {
System.out.print(myArr[i]+"\t");
}
for (int i = 0; i < myArr.length; i++) {
if (myArr[i] > largest) {
secondLargest = largest;
largest = myArr[i];
} else if (myArr[i] > secondLargest) {secondLargest = myArr[i];
}
}
System.out.println("\nSecond largest number is:" + secondLargest);
}
}

36. Can we call String class methods using string literals ?

Yes, we can call String class methods using string literals. Here are some examples,

“KODNEST”.charAt(0)

“KODNEST”.compareTo(“KODNEST”)

“KODNEST”.indexOf(‘O’)

37. What is constructor chaining and how can it be achieved in Java ?

Constructor chaining is the process of calling one constructor from another constructor with respect to current object.
Constructor chaining can be done in two ways:
1.Within same class: It can be done using this() keyword for constructors in same class.
2.From base class: by using super() keyword to call constructor from the base class.
Constructor chaining occurs through inheritance. A sub class constructor’s task is to call super class’s constructor first. This ensures that creation of sub class’s object starts with the initialization of the data members of the super class. There could be any numbers of classes in inheritance chain. Every constructor calls up the chain till class at the top is reached.

38. What are the steps required to execute a query in JDBC ?

  1. First we need to create an instance of a JDBC driver or load JDBC drivers .
  2.   we should open a connection or we should establish the connection
  3.   We should create a statement object and this object will help us to execute the query.
  4. We should Execute query
  5. We should Display the result
  6. We should Close the resources

39. What Class.forName() method will do ?

Class.forName()  loads the class dynamically and it returns the object of type class.
Example:we can use Class.forName() to load the driver class in JDBC
As shown below Class.forName(“oracle.jdbc.driver.OracleDriver”);

40. What are the different types of Statements available in JDBC ?

There are three types of statement:
1. Statement: it’s a commonly used for getting data from database useful when we are using static SQL statement at runtime. it will not accept any parameter.
Example:
                Statement   stmt = conn.createStatement( );      
2. PreparedStatement: when we are using same SQL statement multiple times it is useful and it will accept parameter at runtime.
                String SQL = “Update stock SET limit =? WHERE stock Type = ?”;
                Example:
                PreparedStatement  pstmt = conn.prepareStatement(SQL);
3. Callable Statement: when we want to access stored procedures then callable statement are useful and they also accept runtime parameter. It is called like this
CallableStatement cs = con.prepareCall(“{call SHOW_SUPPLIERS}”); 

41. What is the difference between execute, executeQuery and executeUpdate ?

Execute() – Executes the any kind of SQL statement.it returns boolean
executeQuery() – This is used generally for reading the content of the Database.The output will be in the form of ResultSet. Generally SELECT statement is used.
executeUpdate() – This is generally used for altering the databases. Generally , INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements(DML Statements) The output will be in the form of int which denotes the number of rows affected by the query.

42. What is transaction ?

A transaction is atomic unit of Work. Which means a transaction is a collection of several tasks and if task fails then the effect will be rolled back to the previous state. In simple terms a transaction commits only when all the tasks specified in it executes successfully.

43. Prepared Statements are faster. Why ?

Prepared statement execution is faster than direct execution because the statement is compiled only once. Prepared statements & JDBC driver are connected with each other during execution, and there are no connection overheads.

44. What is cold backup and hot backup ?

Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is ‘online backup’) is a backup taken of each tablespace while the database is running and is being accessed by the users.

45. Write an Example Snippet to Connect Java Application with mysql database.

import java.sql.*;
class MysqlCon
{
     public static void main(String args[])
{
     try
     {
     Class.forName("com.mysql.jdbc.Driver");
     Connection con=DriverManager.getConnection(
     "jdbc:mysql://localhost:3306/Employees","root","root");
      Statement stmt=con.createStatement();
      ResultSet rs=stmt.executeQuery("select * from emp");
      while(rs.next())
      System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
      con.close();
      }
     catch(Exception e)
      {
      System.out.println(e);
       }
}
}

46. Difference between RowSet vs ResultSet in JDBC ?

In a ResultSet handle connection to a DB, we cannot make Result as a serialized object.
Because of above issue, we cannot pass  Resultset across the network.
RowSet extends the ResultSet interface, so it holds all methods from ResultSet. RowSet is serialized.
So, we can pass Rowset from one class to another class because it has no connection with the database.

47. Why Java does not support pointer ?

In Java there are references instead of pointers. These references point to objects in memory. But there is no direct access to these memory locations. JVM is free to move the objects within VM memory.
The  absence  of  pointers  helps  Java  in  managing  memory  and garbage collection effectively. Also it provides developers with convenience of not getting worried about memory allocation and de- allocation.

48. Difference between method overloading and method overriding in Java ?

1.   Method overloading is static polymorphism. Method overriding is runtime polymorphism.
2.     Method overloading occurs within the same class. Method overriding happens in two classes with hierarchy relationship.
3.     Parameters  must  be  different  in  method  overloading.
Parameters must be same in method overriding.
4.     Method overloading is a compile time concept. Method overriding is a runtime concept.

49. Difference between abstract class and interface in Java ?

1.     An abstract  class  can have  implemented  methods  with body (non-abstract methods). Interface has only abstract methods. From Java 8 onwards, interface can have static/default methods in implemented form.
2.     An abstract class can have instance member variables. An interface cannot have instance variables. It can only have constants.
3.     An abstract class can have a constructor. Interface cannot have  constructor.  It  has  to  be  implemented  by  another class.
4.     A class can extend only one abstract class. A class can implement more than one interface.

50. What is package in Java ?

A package is used to encapsulate a group of classes, interfaces and sub-packages. Often, it is a hierarchical structure of storing information. It is easier to organize the related classes and sub- packages in this manner.
A Package also provides access protection for classes and interfaces. A package also helps in removing naming collision.

51. Can you import same class or package twice in your class ?

If we  import same  package  multiple  times  in a  class, compiler includes  it only once.  So  neither  JVM nor  Compiler  gives  any error/warning on including a package multiple times.
If you have two classes with same name, then you may get name collision on importing the class erroneously. JVM internally loads the class only one time.

52. What is serialization ?

Serialization is a process converting an object into a byte array. This byte array represents the class, version and internal state of the object. JVM can use this byte array to transmit/read the object over a network.

53. Why do we make a data member transient ?

Member variables of an object are marked transient to indicate that they should not be serialized.
During   serialization   process   the   transient   variables   are   not considered part of the persistent state of an object.

54. Explain Garbage Collection process in Java ?

Java  has  an  automated  process  called  Garbage  Collector  for Memory Management.  It is  a  daemon in JVM that monitors  the memory usage and performs memory cleanup. Once JVM is low on memory,  GC  process   finds   the  unused  objects   that  are  not referenced by other objects. These unused objects are cleaned up by Garbage Collector daemon in JVM.

55. Why do we use finalize() method in Java ?

Java  has  finalize()  method  to  perform any cleanup  before Garbage  Collection.  This  method  is  in  Object  class,  and  it  is invoked by JVM internally. Developers are free to implement this method for any custom cleanup in case of Garbage Collection.
If an Object is not Garbage Collected, then this method may not be called. This method is never invoked more than once by JVM.

56. Difference between Checked and Unchecked ?

Checked Exceptions extend Throwable class, but they do not extend RuntimeException or Error classes. UncheckedException extend RuntimeException class.

Checked   Exceptions   are   checked   at   compile   time   in  Java. Unchecked Exceptions happen at Runtime, so they are not checked at compile time. IOException, SQLException etc. are examples of Checked Exceptions. NullPointerException, ArithmeticException etc. are examples of Unchecked Exceptions.

57. How many ways are there to convert a List to a set ?

There are two ways to convert a List to a Set in Java.

Option 1: Use HashSet

Set<Integer> mySet = new HashSet<Integer>(myList);

In this case we put a list into a HashSet. Internally hashCode()
method is used to identify duplicate elements.

Option 2: Use TreeSet

In this case we use our own comparator to find duplicate objects.

Set<Integer> mySet = new TreeSet<Integer>(myComparator);
mySet.addAll(myList);

58. Difference between a List and Set collection in Java ?

1.     Order: List collection is an ordered sequence of elements.
A Set  is  just  a  distinct  collection  of  elements  that  is unordered.

2.     Positional Access: When we use a List, we can specify where exactly we want to insert an element. In a Set there is no order, so we can insert element anywhere without worrying about order.

3.     Duplicate: In a List we can store duplicate elements. A Set can hold only unique elements.

59. Difference between HashSet and TreeSet collection in Java ?

1.     Ordering: In a HashSet elements are stored in a random order.  In  a  TreeSet,  elements  are  stored  according  to natural ordering.

2.     Null Value Element: We can store null value object in a HashSet. A TreeSet does not allow to add a null value object.

3.     Performance:  HashSet  performs  basic  operations  like add(), remove(), contains(), size() etc in a constant size time. A TreeSet performs these operations at the order of log(n) time.

4.     Speed: A HashSet is better than a TreeSet in performance for most of operations like add(), remove(), contains(), size() etc .

5.     Internal Structure: a HashMap in Java internally backs a
HashSet. A NavigableMap backs a TreeSet internally.

6.     Features:   A   TreeSet has more features compared to a HashSet. It has methods like pollFirst(), pollLast(), first(), last(), ceiling(), lower() etc.

7.     Element Comparison: A HashSet uses equals() method for comparison.  A  TreeSet  uses  compareTo()  method  for
comparison to maintain ordering of elements.

60. Difference between ArrayList and a LinkedList data structure?

1.     Data  Structure:  An  ArrayList  is  an  indexed  based dynamic array. A LinkedList is a Doubly Linked List data structure.

2.     Insertion:  It  is  easier  to  insert  new  elements  in  a LinkedList, since there is no need to resize an array. Insertion in ArrayList is O(n), since it may require resizing of array and copying its contents to new array.

3.     Remove elements: LinkedList has better performance in removal of elements than ArrayList.

4.   Memory Usage: LinkedList uses more memory than ArrayList, since it has to maintain links for next and previous nodes as well.

5.     Access:  LinkedList  is  slower  in accessing an element, since we have to traverse the list one by one to access the right location.

61. Difference between array and arraylist ?

1.     Size: Array in Java is fixed in size. We cannot change the size of array after creating it. ArrayList is dynamic in size. When we add elements to an ArrayList, its capacity increases automatically.

2.     Performance: In Java Array and ArrayList give different performance for different operations.

3.     add()  or get():  Adding an element to  or  retrieving an element  from an array or  ArrayList  object  has  similar performance. These are constant time operations.

4.     resize(): Automatic resize of ArrayList slows down the performance. ArrayList is internally backed by an Array. In resize() a temporary array is used to copy elements from old array to new array.

5.     Primitives: Array can contain both primitive data types as well  as objects. But ArrayList cannot contain primitive data types. It contains only objects.

6.     Iterator: In an ArrayList we use an Iterator   object to traverse  the  elements.  We  use  for  loop  for  iterating elements in an array.

7.     Type  Safety:    Java  helps  in  ensuring  Type  Safety  of elements in an ArrayList by using Generics. An Array can contain objects of same type of class. If we try to store a different data type object in an Array then it throws ArrayStoreException.

8.     Length:  Size of ArrayList can be obtained by using size() method. Every array object has length variable that is same as the length/size of the array.

9.     Adding  elements:  In  an  ArrayList  we  can  use  add() method to add objects. In an Array assignment operator is used for adding elements.

10.     Multi-dimension: An Array can be multi-dimensional. An
ArrayList is always of single dimension.

62. What do you understand by word thread in Java ?

A thread in Java is a lightweight process that runs within another process or thread. It is an independent path of execution in an application. JVM gives each thread its own method-call stack.

When we start JVM, Java starts one thread.  This thread calls the main method of the class passed in argument to java call.

63. Can we call run()run method instead of start() on a thread in Java ?

Yes. We can call run() method of a thread. But it does not work as a separate thread. It will just work as a normal object in main thread and there will not be context switching between the threads.

64. Explain Deadlock situation ?

A Deadlock is a situation in which two or more threads are waiting on each other to release a resource. Each thread is waiting for a resource that is held by the other waiting thread.

At times there is a circular wait when more than two threads are waiting on each other ’s resources.

65. Explain different states of thread in Java ?

Following are the different states of a Thread in Java:

1.     New: In the New state the thread has not yet.

2.     Runnable: A thread executing in the JVM is in Runnable state.

3.     Blocked:  A  thread  waiting  for  a  monitor  lock  is  in
Blocked state.

4.     Waiting: A thread waiting indefinitely for another thread to perform a particular action is in Waiting state.

5.     Timed_waiting:  A thread  waiting for  another  thread  to perform an action for up to a specified waiting time is in Timed_waiting state.

6.     Terminated:  A thread  that has  exited  is  in Terminated state.

66. Which is a right data type to represent Money (like Dollar/Pound) in Java ?

To represent money you need decimal points in the numbers like
$1.99.

BigDecimal  class  provides  good  methods  to  represent  Money. Using BigDecimal, we can do the calculation with decimal points and correct rounding. But using BigDecimal is a little bit high on memory usage.

We can also use double with predefined precision. But calculation on double can give erroneous results.

67. What will the output for 9*0.1 == 0.9 ? true or false ?

The  answer  is  false  because  floating point numbers  can not be represented exactly in Java, so 9*0.1 is not same as 0.9.

68. How Http works ?

HTTP stands for Hypertext Transfer Protocol. The following below steps explains about working:

Clients opens connection.

Clients sends HTTP request.

Server sends HTTP response.

Client closes connection.

69. What is servlet ?

A servlet is a java program that runs within a web server and serves the client request .Because it serves the client the name is  servlet. Servlets can receive and respond to requests from web clients working on HTTP protocol.

70. What is CGI ?

Common Gateway Interface(CGI) was the most commonly used for server side scripting before the evolution of the java servlet technology. With traditional CGI, a new process is started for each HTTP request eating up more of the CPU cycles thus degrading the performance of the system.

71. What are the advantages of servlet over CGI ?

1.When a CGI script is called, a new process is created for each and every client request. But for servlets, each request is handled by a separate thread. Hence, servlet is more efficient because process creation takes more time compared to thread creation.

2.For each new CGI requests, CGI script is copied into memory. But with servlets, there is only one copy across requests and is shared among threads. iii.In CGI multiple process serves concurrent requests. But in  servlets, only single Process serves  concurrent request.

72. Explain briefly the doGet and doPost methods in HTTPServlet ?

protected void doGet(HTTPServletRequest req, HTTPServletResponse res)
Above method is called by the container to allow a servlet to handle a GET request. It will be called when a URL is requested or the form method is GET.

protected  void doPost(HTTPServletRequest req, HTTPServletResponse res) It is called by the container to allow a servlet to handle a POST request. It will be called when the form method is POST.

73. What is a servlet context ?

It refers to the context in which the servlet runs. It is a gateway between the web container and the servlets. There will be only one instance of servlet context per web application shared by all the servlets in the application. It is used for storing values which can be shared across all the servlets in the web application.

<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<context-param>
 <param-name>URL</param-name>
 <param-value>jdbc:mysql:@//localhost:3306/Employees</param-value>
</context-param>
<context-param>
<param-name>USER</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>PASSWORD</param-name>
<param-value>root</param-value>
</context-param>
</web-app>

74. Explain briefly Lifecycle methods of Jsp ?

A JSP has following lifecycle methods:

1.     jspInit(): This method is invoked when the JSP is called for the first time. We can do initial setup for servicing a request in this method.

2.     _jspService(): This method is used to serve every request of the JSP.

3.     jspDestroy(): Once we remove a JSP from the container, we call this method. It is used for cleanup of resources like Database connections etc.

75. List down advantages of JSP in web architecture ?

1.     Performance: JSP provides very good performance due to their design of using same code to service multiple requests.

2.     Fast:  Since  JSP is  pre-compiled,  server  can serve  the pages very fast.

3.     Extendable: JSP is based on Java Servlets. This helps in extending JSP architecture  with other  Java  technologies like JDBC, JMS, JNDI etc.

4.     Design: It is easier to design user interface with JSP, since it is very close to HTML. UI designers can create a JSP with mock data and developers can later provide implementation of dynamic data.

76. List down different types of directive tags in JSP ?

1.     Page: This directive is used for page related attributes. It can be put anywhere in the JSP page. But by convention we put it on the top of the page.

E.g.

<%@ page attribute="value" %>

2.     Taglib: We can create custom tags in JSP and use these by taglib directive in a JSP page.

E.g.

<%@ taglib uri=“abc.html” prefix=“tag_prefix” >

3.     Include: We use include directive to read a file and merge its content with the JSP page. This is done during compilation stage.

<%@ include file="relative url" >

77. Explian briefly about directive in JSP ?

JSP directive is a mechanism to pass message to JSP container. JSP directive does not produce an output to the page. But it communicates with JSP container.

E.g. <%@include ..%> directive is  used for telling JSP container to include the content of another file during translation of JSP.

There  can  be  zero  or  more  attributes  in  a  directive  to  pass additional information to JSP container.

Some of the important directives  in JSP are:  page, include and taglib.

78. What is RMI ?

The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and distributed garbage collection. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object.

79. What are the layers of RMI Architecture ?

Stub and Skeleton layer:- This layer lies just beneath the view of the developer. This layer is responsible for intercepting method calls made by the client to the interface and redirect these calls to a remote RMI Service.

Remote Reference Layer:- The second layer of the RMI architecture deals with the interpretation of references made from the client to the server’s remote objects. This layer interprets and manages references made from clients to the remote service objects. The connection is a one-to-one (unicast) link.

Transport layer: This layer is responsible for connecting the two JVM participating in the service. This layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

80. What is Hibernate ?

Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration files in XML format. After java objects mapping to database tables, database is used and handled using Java objects without writing complex database queries.

81. What is ORM ?

ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.

82. What is POJO and what are they used for ?

POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.

83. Difference between session.save() and session.saveOrUpdare() in hibernate ?

Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.

84. What are the advantages of using hibernate over JDBC ?

Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.

85. What are the ways to identify objects in hibernate ?

Object identification can be done in following three ways:
1. Using Object Identity: Using == operator.
2. Using Object Equality: Using equals() method.
3. Using database identity: Relational database objects can be identified if they represent same row.

86. Mention the use of session.lock() in hibernate ?

session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.

87. How to invoke stored procedures in hibernate ?

It can be invoked using code below:

<sql-query name="getCollege" callable="true">
<return alias="gc" class="College">
<return-property name="clg_id" column="CGD_ID" />
<return-property name="c_name" column="CGD_NAME" />
<return-property name="clg_id" column="CGD_ID" />
{ ? = call selectStudents() }
</return>
</sql-query>

88. What is transcation management in hibernate and how it works ?

Transaction management is the process of managing a set of statements or commands. In hibernate; transaction management is done by transaction interface as shown in below code:

Session s = null;
Transaction tr = null;
try {
s = sessionFactory.openSession();
tr = s.beginTransaction();
doTheAction(s);
tr.commit();
} catch (RuntimeException exc) {
tr.rollback();
} finally {
s.close();
}

89. Explain the procedure to map java objects with database tables ?

To map java objects with database tables, we need to have Java beans properties names same as column names of a database table. Then mapping is provided in hbm.xml file as given below:

<hibernate-mapping>
<class name="College" table"tbl_college">
<property column="collegename" length="250" name="collegeName"
not-null="true" type="java.lang.String" />
name="collegeDiscipline" not-null="true" type-"java.lang.String" />
</class>
</hibernate-mapping>

90. What is Spring ?

Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

91. How to enable transcations in Spring and what are the benefits of it?

There are two distinct ways to configure Transactions – with annotations or by using Aspect Oriented Programming (AOP) – each with their advantages.

The benefits of using Spring Transactions, according to the official docs, are:

Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO
Support declarative transaction management
Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA
Integrate very well with Spring’s various data access abstractions.

92. Explain briefly about Spring Framework ?

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications – on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the “plumbing” of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

93. List down some important Spring Modules ?

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

94. What is Spring DAO support ?

The Data Access Object (DAO) support in Spring makes it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies easily. It also allows you to code without worrying about catching exceptions that are specific to each of these technology.

95. Describe Spring Security ?

Spring security framework focuses on providing both authentication and authorization in java applications. It also takes care of most of the common security vulnerabilities such as CSRF attack.

It’s very beneficial and easy to use Spring security in web applications, through the use of annotations such as @EnableWebSecurity. You should go through following posts to learn how to use Spring Security framework.

Spring Security in Servlet Web Application
Spring MVC and Spring Security Integration Example

96. Describe Spring MVC framework ?

Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects.

97. What is Controller in Spring MVC framework ?

Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

98. Difference between Bean Factory and Application Context ?

BeanFactory is an interface representing a container that provides and manages bean instances. The default implementation instantiates beans lazily when getBean() is called.

ApplicationContext is an interface representing a container holding all information, metadata, and beans in the application. It also extends the BeanFactory interface but the default implementation instantiates beans eagerly when the application starts. This behavior can be overridden for individual beans.

99. How to mark the scope of a bean ?

To set Spring Bean’s scope, we can use @Scope annotation or “scope” attribute in XML configuration files. There are five supported scopes:

singleton
prototype
request
session
global-session

100. What is DispatcherServlet ?

The DispatcherServlet is the core of Spring Web MVC framework. It handles all the HTTP requests and responses. The DispatcherServlet receives the entry of handler mapping from the configuration file and forwards the request to the controller. The controller then returns an object of Model And View. The DispatcherServlet checks the entry of view resolver in the configuration file and calls the specified view component.

 

Responses

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

New Report

Close