Q1. Explain JDK, JRE and JVM?
Q1. Explain JDK, JRE and JVM?
Q1. Explain JDK, JRE and JVM?
public : Public is an access modifier, which is used to specify who can access this method.
Public means that this Method will be accessible by any Class.
static : It is a keyword in java which identifies it is class based i.e it can be accessed without
creating the instance of a Class.
void : It is the return type of the method. Void defines the method which will not return any
value.
main: It is the name of the method which is searched by JVM as a starting point for an
application with a particular signature only. It is the method where the main execution occurs.
String args[] : It is the parameter passed to the main method.
1. Default constructor
2. Parameterized constructor
Q7. What is singleton class and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given time, in one JVM. A
class can be made singleton by making its constructor private.
Array List does not define the increment size. Vector defines the increment size.
Array List can only use Iterator for traversing Except Hashtable, Vector is the only other class
an Array List. which uses both Enumeration and Iterator.
Q10. What are the differences between Heap and Stack Memory?
The major difference between Heap and Stack memory are:
Features Stack Heap
Stack memory is used only by one Heap memory is used by all the parts of
Memory
thread of execution. the application.
Stack memory can’t be accessed by Objects stored in the heap are globally
Access
other threads. accessible.
Exists until the end of execution of Heap memory lives from the start till the
Lifetime
the thread. end of application execution.
In Method Overloading, Methods of the same class shares the same name but each method
must have different number of parameters or parameters having different types and order.
Method Overloading is to “add” or “extend” more to method’s behavior.
It is a compile time polymorphism.
The methods must have different signature.
It may or may not need inheritance in Method Overloading.
Let’s take a look at the example below to understand it better.
class Adder {
1 Static int add(int a, int b)
2 {
3 return a+b;
4 }
5 Static double add( double a, double b)
6 {
7 return a+b;
8 }
9 public static void main(String args[])
10 {
11 System.out.println(Adder.add(11,11));
12 System.out.println(Adder.add(12.3,12.6));
}}
Method Overriding:
In Method Overriding, sub class have the same method with same name and exactly the
same number and type of parameters and same return type as a super class.
Method Overriding is to “Change” existing behavior of method.
It is a run time polymorphism.
The methods must have same signature.
It always requires inheritance in Method Overriding.
Let’s take a look at the example below to understand it better.
class Car {
1 void run(){
2 System.out.println(“car is running”);
3 }
4 Class Audi extends Car{
5 void run()
6 {
7 System.out.prinltn(“Audi is running safely with 100km”);
8 }
9 public static void main( String args[])
10 {
11 Car b=new Audi();
12 b.run();
13 }
}
Q5. Can you override a private or static method in Java?
You cannot override a private or static method in Java. If you create a similar method with same
return type and same method arguments in child class then it will hide the super class method; this
is known as method hiding. Similarly, you cannot override a private method in sub class because it’s
not accessible there. What you can do is create another private method with the same name in the
child class. Let’s take a look at the example below to understand it better.
class Base {
private static void display() {
1
System.out.println("Static or class method from Base");
2
}
3
public void print() {
4
System.out.println("Non-static or instance method from Base");
5
}
6
class Derived extends Base {
7
private static void display() {
8
System.out.println("Static or class method from Derived");
9
}
10
public void print() {
11
System.out.println("Non-static or instance method from Derived");
12
}
13
public class test {
14
public static void main(String args[])
15
{
16
Base obj= new Derived();
17
obj1.display();
18
obj1.print();
19
}
}
Java Servlet is server side technologies to extend the capability of web servers by providing
support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing
our own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle
methods. When implementing a generic service, we can extend the GenericServlet class
provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet()
and doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why we
mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.
Q2. What are the differences between Get and Post methods?
Get Post
Limited amount of data can be sent because data is Large amount of data can be sent because data
sent in header. is sent in body.
Secured because data is not exposed in URL
Not Secured because data is exposed in URL bar.
bar.
Can be bookmarked Cannot be bookmarked
Idempotent Non-Idempotent
It is more efficient and used than Post It is less efficient and used
forward() sends the same request to another sendRedirect() method sends new request always
resource. because it uses the URL bar of the browser.
forward() method works at server side. sendRedirect() method works at client side.
1. Servlet is loaded
2. Servlet is instantiated
3. Servlet is initialized
4. Service the request
5. Servlet is destroyed
Cookies are text data sent by server to the client and it gets saved at the client local machine.
Servlet API provides cookies support through javax.servlet.http.Cookie class that implements
Serializable and Cloneable interfaces.
HttpServletRequest getCookies() method is provided to get the array of Cookies from
request, since there is no point of adding Cookie to request, there are no methods to set or
add cookie to request.
Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in
response header, there are no getter methods for cookie.
Its like local parameter associated with Its like global parameter associated with whole
particular servlet application
getServletConfig() method is used to get the getServletContext() method is used to get the context
config object object.
for example shopping cart of a user is a To get the MIME type of a file or application session
specific to particular user so here we can use related information is stored using servlet context
servlet config object.
1. User Authentication
2. HTML Hidden Field
3. Cookies
4. URL Rewriting
5. Session Management API
Connection
Statement
PreparedStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
CallableStatement etc.
Classes:
DriverManager
Blob
Clob
Types
SQLException etc.
Q4. Explain Bean in Spring and List the different Scopes of Spring bean.
Beans are objects that form the backbone of a Spring application. They are managed by the Spring
IoC container. In other words, a bean is an object that is instantiated, assembled, and managed by
a Spring IoC container.
There are five Scopes defined in Spring beans.
Singleton: Only one instance of the bean will be created for each container. This is the
default scope for the spring beans. While using this scope, make sure spring bean doesn’t
have shared instance variables otherwise it might lead to data inconsistency issues because
it’s not thread-safe.
Prototype: A new instance will be created every time the bean is requested.
Request: This is same as prototype scope, however it’s meant to be used for web
applications. A new instance of the bean will be created for each HTTP request.
Session: A new bean will be created for each HTTP session by the container.
Global-session: This is used to create global session beans for Portlet applications.
Q5. Explain the role of DispatcherServlet and ContextLoaderListener.
DispatcherServlet is basically the front controller in the Spring MVC application as it loads the
spring bean configuration file and initializes all the beans that have been configured. If annotations
are enabled, it also scans the packages to configure any bean annotated with @Component,
@Controller, @Repository or @Service annotations.
Q6. What are the differences between constructor injection and setter injection?
No. Constructor Injection Setter Injection
1) No Partial Injection Partial Injection
2) Desn’t override the setter property Overrides the constructor property if both are defined
3) Creates new instance if any modification occurs Doesn’t create new instance if you change the prope
4) Better for too many properties Better for few properties.
Q9. What are some of the important Spring annotations which you have used?
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very
important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as
response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type
is present.
@Service – for service classes.
@Scope – for configuring scope of the spring bean.
@Configuration, @ComponentScan and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around,
@Pointcut etc.
1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more
cleaner and readable.
2. Hibernate supports inheritance, associations and collections. These features are not present
with JDBC API.
3. Hibernate implicitly provides transaction management, in fact most of the queries can’t be
executed outside transaction. In JDBC API, we need to write code for transaction
management using commit and rollback.
4. JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-
catch block code. Most of the times it’s redundant in every JDBC call and used for transaction
management. Hibernate wraps JDBC exceptions and
throw JDBCException or HibernateException un-checked exception, so we don’t need to
write code to handle it. Hibernate built-in transaction management removes the usage of try-
catch blocks.
5. Hibernate Query Language (HQL) is more object oriented and close to java programming
language. For JDBC, we need to write native sql queries.
6. Hibernate supports caching that is better for performance, JDBC queries are not cached
hence performance is low.
7. Hibernate provide option through which we can create database tables too, for JDBC tables
must exist in the database.
8. Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource
for connection pool. This is very important feature in enterprise application and completely
missing in JDBC API.
The include directive includes the content at The include action includes the content at request
page translation time. time.
The include directive includes the original The include action doesn’t include the original
content of the page so page size increases content rather invokes the include() method of
at runtime. Vendor provided class.
It’s better for static pages. It’s better for dynamic pages.
Q4. What purpose does the keywords final, finally, and finalize fulfill?
Final:
Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final
method can’t be overridden and final variable value can’t be changed. Let’s take a look at the
example below to understand it better.
class FinalVarExample {
1
public static void main( String args[])
2
{
3
final int a=10; // Final variable
4
a=50; //Error as value can't be changed
5
}
6
Finally
Finally is used to place important code, it will be executed whether exception is handled or not. Let’s
take a look at the example below to understand it better.
1 class FinallyExample {
2 public static void main(String args[]){
3 try {
4 int x=100;
5 }
6 catch(Exception e) {
7 System.out.println(e);
8 }
9 finally {
10 System.out.println("finally block is executing");}
11 }}
12 }
Finalize
Finalize is used to perform clean up processing just before object is garbage collected. Let’s take
a look at the example below to understand it better.
1 class FinalizeExample {
2 public void finalize() {
3 System.out.println("Finalize is called");
4 }
5 public static void main(String args[])
6 {
7 FinalizeExample f1=new FinalizeExample();
8 FinalizeExample f2=new FinalizeExample();
9 f1= NULL;
10 f2=NULL;
11 System.gc();
12 }
13 }
1. String getMessage() – This method returns the message String of Throwable and the
message can be provided while creating the exception through it’s constructor.
2. String getLocalizedMessage() – This method is provided so that subclasses can override
it to provide locale specific message to the calling program. Throwable class implementation
of this method simply use getMessage() method to return the exception message.
3. Synchronized Throwable getCause() – This method returns the cause of the exception or
null id the cause is unknown.
4. String toString() – This method returns the information about Throwable in String format,
the returned String contains the name of Throwable class and localized message.
5. void printStackTrace() – This method prints the stack trace information to the standard error
stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument
to write the stack trace information to the file or stream.
Q10. What is a finally block? Is there a case when finally will not execute?
Finally block is a block which always execute a set of statements. It is always associated with a try
block regardless of any exception that occurs or not.
Yes, finally will not be executed if the program exits either by calling System.exit() or by causing a
fatal error that causes the process to abort.
1. String getMessage() – This method returns the message String about the exception . The
message can be provided through its constructor.
2. public StackTraceElement[] getStackTrace() – This method returns an array containing
each element on the stack trace. The element at index 0 represents the top of the call stack
whereas the last element in the array represents the method at the bottom of the call stack.
3. Synchronized Throwable getCause() – This method returns the cause of the exception or
null id as represented by a Throwable object.
4. String toString() – This method returns the information in String format. The returned String
contains the name of Throwable class and localized message.
5. void printStackTrace() – This method prints the stack trace information to the standard error
stream.