Java Interview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

How does cookies work in Servlets?

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

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

- Registering the driver class - Creating connection - Creating statement - Executing queries - Closing connection

List some advantages to CSS3 animations over script-based animation?

1. Easy to use and anybody can create them without the knowledge of JavaScript. 2. Executes well even under reasonable system load. As simple animations perform poorly in JavaScript, the rendering engine uses the frame-skipping techniques to allow smooth flow of animation. 3. Allows the browser to control the animation sequence, optimize performance and efficiency by reducing the update frequency of animations executing in tabs that aren't currently visible.

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 are different states of an entity bean?

1. Transient: When an object is never persisted or associated with any session, it's in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). 2. Persistent: When an object is associated with a unique session, it's in persistent state. Any instance returned by a get() or load() method is persistent. 3. Detached: When an object is previously persistent but not associated with any session, it's in detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

What are the different tags provided in JSTL?

1. core tags 2. sql tags 3. xml tags 4. internationalization tags 5. functions tags

What are the JSP implicit objects?

1. out -- JspWriter 2. request -- HttpServletRequest 3. response -- HttpServletResponse 4. config -- ServletConfig 5. session -- HttpSession 6. application -- ServletContext 7. pageContext -- PageContext 8. page -- Object 9. exception -- Throwable

How can you handle Java exceptions?

1. try 2. catch 3. finally 4. throw 5. throws

How to disable caching on back button of the browser?

<% response.setHeader("Cache-Control","no-store"); response.setHeader("Pragma","no-cache"); response.setHeader ("Expires", "0"); //prevents caching at the proxy server %>

What do you mean by GROUP BY Clause?

A GROUP BY clause can be used in select statement where it will collect data across multiple records and group the results by one or more columns.

What are joins in SQL?

A JOIN clause is used to combine rows from two or more tables, based on a related column between them. It is used to merge two tables or retrieve data from there. There are 4 joins in SQL namely: Inner Join Right Join Left Join Full Join

What is the difference between session and cookie ?

A cookie is a bit of information that the Web server sends to the browser. The browser stores the cookies for each Web server in a local file. In a future request, the browser, along with the request, sends all stored cookies for that specific Web server.The differences between session and a cookie are the following: The session should work, regardless of the settings on the client browser. The client may have chosen to disable cookies. However, the sessions still work, as the client has no ability to disable them in the server side. The session and cookies also differ in the amount of information the can store. The HTTP session is capable of storing any Java object, while a cookie can only store String objects.

Can you access non static variable in static context ?

A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.

What is the difference between abstract classes and interfaces?

Abstract Classes: An abstract class can provide complete, default code and/or just the details that have to be overridden. In case of abstract class, a class may extend only one abstract class. An abstract class can have non-abstract methods. An abstract class can have instance variables. An abstract class can have any visibility: public, private, protected. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly An abstract class can contain constructors Abstract classes are fast Interfaces: An interface cannot provide any code at all,just the signature. A Class may implement several interfaces. All methods of an Interface are abstract. An Interface cannot have instance variables An Interface visibility must be public (or) none. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method An Interface cannot contain constructors Interfaces are slow as it requires extra indirection to find corresponding method in the actual class

What is the difference between Abstraction and Encapsulation?

Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of an object. On the other hand, encapsulation focuses on the implementation of an object's behavior. Encapsulation is usually achieved by hiding information about the internal state of an object and thus, can be seen as a strategy used in order to provide abstraction.

What is the use of Aggregate functions in Oracle?

Aggregate function is a function where values of multiple rows or records are joined together to get a single value output. Common aggregate functions are - Average Count Sum

What do you mean by aggregation?

Aggregation is a specialized form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Example: (Department and teacher) A single teacher can not belongs to multiple departments, but if we delete the department, teacher object will not destroy.

What is the difference between an Applet and a Servlet ?

An Applet is a client side java program that runs within a Web browser on the client machine. On the other hand, a servlet is a server side component that runs on the web server.An applet can use the user interface classes, while a servlet does not have a user interface. Instead, a servlet waits for client's HTTP requests and generates a response in every request.

What is an Index?

An index refers to a performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and hence it will be faster to retrieve data.

What is the difference between Array list and vector?

Array List: Array List is not synchronized. Array List is fast as it's non-synchronized. If an element is inserted into the Array List, it increases its Array size by 50%. Array List does not define the increment size. Array List can only use Iterator for traversing an Array List. Vector: Vector is synchronized. Vector is slow as it is thread safe. Vector defaults to doubling size of its array. Vector defines the increment size. Except Hashtable, Vector is the only other class which uses both Enumeration and Iterator.

What is hibernate caching? Explain Hibernate first level cache?

As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application. Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely. Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.

What is autowiring in Spring?

Autowiring enables the programmer to inject the bean automatically. We don't need to write explicit injection logic.

What is the main difference between 'BETWEEN' and 'IN' condition operators?

BETWEEN operator is used to display rows based on a range of values in a row whereas the IN condition operator is used to check for values contained in a specific set of values.

Explain Bean in Spring

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.

What is the difference between CHAR and VARCHAR2 datatype in SQL?

Both Char and Varchar2 are used for characters datatype but varchar2 is used for character strings of variable length whereas Char is used for strings of fixed length.

What is composition in Java?

Composition is again specialized form of Aggregation and we can call this as a "death" relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Example: (House and rooms) House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete.

How to handle exceptions in Spring MVC Framework?

Controller Based: We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation. Global Exception Handler: Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler. HandlerExceptionResolver implementation: For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

What is the difference between DROP and TRUNCATE commands?

DROP command removes a table and it cannot be rolled back from the database whereas TRUNCATE command removes all the rows from the table.

What do you mean by data integrity?

Data Integrity defines the accuracy as well as the consistency of the data stored in a database. It also defines integrity constraints to enforce business rules on the data when it is entered into an application or a database.

What is DML?

Data Manipulation Language (DML) is used to access and manipulate data in the existing objects. DML statements are insert, select, update and delete and it won't implicitly commit the current transaction.

Explain the role of DispatcherServlet

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.

How do we display rows from the table without duplicates?

Duplicate rows can be removed by using the keyword DISTINCT in the select statement.

What is Encapsulation?

Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number of methods, which can be accessed by other objects and change its internal data. In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages. Some of the advantages of using encapsulation are listed below: - The internal state of every objected is protected by hiding its attributes. - It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended. - It improves modularity by preventing objects to interact with each other, in an undesired way.

Hibernate Session is thread safe?

Hibernate Session object is not thread safe, every thread should get it's own session instance and close it after it's work is finished.

What is hibernate configuration file?

Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.

What is hibernate mapping file?

Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can't use annotations. (.hbm)

Why we should not make Entity Class final?

Hibernate use proxy classes for lazy loading of data, only when it's needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.

What is inheritance?

Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides re-usability of code and can be used to add additional features to an existing class, without modifying it.

Hibernate SessionFactory is thread safe?

Internal state of SessionFactory is immutable, so it's thread safe. Multiple threads can access it simultaneously to get Session instances.

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 2. Native-API driver (partially java driver) 3. Network Protocol driver (fully java driver) 4. Thin driver (fully java driver)

How is JSP better than Servlet technology?

JSP is a technology on the server's side to make content generation simple. They are document centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside HTML template file. It provides the framework for development of a Web Application.

What are some of the key new features in HTML5?

Key new features of HTML5 include: - Improved support for embedding graphics, audio, and video content via the new <canvas>, <audio>, and <video> tags. - Extensions to the JavaScript API such as geolocation and drag-and-drop as well for storage and caching. - Introduction of "web workers". - Several new semantic tags were also added to complement the structural logic of modern web applications. These include the <main>, <nav>, <article>, <section>, <header>, <footer>, and <aside> tags. - New form controls, such as <calendar>, <date>, <time>, <email>, <url>, and <search>.

What new features were added in Java 8?

Lambda Expressions − a new language feature allowing treating actions as objects Method References − enable defining Lambda Expressions by referring to methods directly using their names Optional − special wrapper class used for expressing optionality Functional Interface - an interface with maximum one abstract method, implementation can be provided using a Lambda Expression Default methods − give us the ability to add full implementations in interfaces besides abstract methods Nashorn, JavaScript Engine − Java-based engine for executing and evaluating JavaScript code Stream API − a special iterator class that allows processing collections of objects in a functional manner Date API − an improved, immutable JodaTime-inspired Date API

What are features of Spring?

Lightweight: Spring is lightweight when it comes to size and transparency. Inversion of control (IOC): Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects. Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services. Container: Spring contains and manages the life cycle and configuration of application objects. MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS. Transaction Management: Spring framework provides a generic abstraction layer for transaction management.

What is the use of CallableStatement ?

Name the method, which is used to prepare a CallableStatement. A CallableStatement is used to execute stored procedures. Stored procedures are stored and offered by a database. Stored procedures may take input values from the user and may return a result. The usage of stored procedures is highly encouraged, because it offers security and modularity.

What is exception hierarchy in java?

Object -> Throwable -> (Exception -> (Checked, Unchecked), Error -> (VirtualMachineError, AssertionError) )

Why Java is platform independent?

Platform independent practically means "write once run anywhere". Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.

What is Request Dispatcher?

RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. There are two methods defined in this interface: 1.void forward() 2.void include()

What are SET operators?

SET operators are used with two or more queries and those operators are Union, Union All, Intersect and Minus.

What is the difference between SQL and MySQL?

SQL is a standard language which stands for Structured Query Language based on the English language whereas MySQL is a database management system. SQL is the core of relational database which is used for accessing and managing database, MySQL is an RDMS (Relational Database Management System) such as SQL Server, Informix etc.

List the different Scopes of Spring bean

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.

What are the different methods of session management in servlets?

Some of the common ways of session management in servlets are: 1. User Authentication 2. HTML Hidden Field 3. Cookies 4. URL Rewriting 5. Session Management API

What is synchronization?

Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.

What is JDBC Connection interface?

The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData. createStatement( ) createStatement(resultSetType, resultSetConcurrency) setAutoCommit(boolean status) commit( ) rollback( ) close( )

What is 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.

What is the role of JDBC DriverManager class?

The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

What is the use of NVL function?

The NVL function is used to replace NULL values with another or given value

What does the "static" keyword mean and can you override private or static method in Java ?

The static keyword denotes that a member variable or method can be accessed, without requiring an instantiation of the class to which it belongs. A user cannot override static methods in Java, because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. A static method is not associated with any instance of a class so the concept is not applicable.

What are the collection types in Hibernate?

There are five collection types in hibernate used for one-to-many relationship mappings. Bag Set List Array Map

Explain different ways of creating a thread.Which one would you prefer and why ?

There are three ways that can be used in order for a Thread to be created: - A class may extend the Thread class. - A class may implement the Runnable interface. - An application can use the Executor framework, in order to create a thread pool. The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily.

What is transient variable?

Transient variables cannot be serialized. During serialization process, transient variable states will not be serialized. State of the value will be always defaulted after deserialization.

What is a View? (Oracle SQL)

View is a logical table which based on one or more tables or views. The tables upon which the view is based are called Base Tables and it doesn't contain data.

What is volatile?

Volatile is a declaration that a variable can be accessed by multiple threads and hence shouldnt be cached.

What are wrapper classes?

Wrapper classes converts the java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they "wrap" the primitive data type into an object of that class.

Can we write multiple catch blocks under single try block?

Yes we can have multiple catch blocks under single try block but the approach should be from specific to general.

What is a Spring?

an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring is essentially a lightweight, integrated framework that can be used for developing enterprise applications in java.

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

doGET: The GET method appends the name-value pairs on the request's URL. Thus, there is a limit on the number of characters and subsequently on the number of values that can be used in a client's request. Furthermore, the values of the request are made visible and thus, sensitive information must not be passed in that way. doPOST: The POST method overcomes the limit imposed by the GET request, by sending the values of the request inside its body. Also, there is no limitations on the number of values to be sent across. Finally, the sensitive information passed through a POST request is not visible to an external client.

What are the differences between forward() method and sendRedirect() methods?

forward( ): forward( ) sends the same request to another resource. forward( ) method works at server side. forward( ) method works within the server only. sendRequest( ): sendRedirect() method sends new request always because it uses the URL bar of the browser. sendRedirect() method works at client side. sendRedirect() method works within and outside the server.

What are the differences between get and load methods?

get( ) 1. Returns null if object is not found. 2. get( ) method always hit the database. 3. It returns real object not proxy. 4. It should be used if you are not sure about the existence of instance. load( ) 1. Throws ObjectNotFoundException if object is not found. 2. load() method doesn't hit the database. 3. It returns proxy object. 4. It should be used if you are sure that instance exists.

What are the differences between include directive and include action?

include directive: - The include directive includes the content at page translation time. - The include directive includes the original content of the page so page size increases at runtime. - It's better for static pages. include action: - The include action includes the content at request time. - The include action doesn't include the original content rather invokes the include() method of Vendor provided class. - It's better for dynamic pages.

What are the life-cycle methods for a jsp?

init( ) service( ) destroy( )

Explain public static void main(String args[])

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.

What are the differences between throw and throws?

throw: - Throw is used to explicitly throw an exception. - Checked exceptions can not be propagated with throw only. - Throw is followed by an instance. - Throw is used within the method. - You cannot throw multiple exception throws: - Throws is used to declare an exception. - Checked exception can be propagated with throws. - Throws is followed by class. - Throws is used with the method signature. - You can declare multiple exception e.g. public void method()throws IOException,SQLException.

What is a servlet?

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

What are the important benefits of using Hibernate Framework?

1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic. 2. Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent. 3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association. 4. Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums. 5. Hibernate is easy to integrate with other Java EE frameworks, it's so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications. 6. Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it's required. 7. Hibernate cache helps us in getting better performance. 8. For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

What are the advantages of Hibernate over JDBC?

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. 9. Hibernate supports JPA annotations, so code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.

What are some of the important Spring annotations which you have used?

@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.

What is a Stored Procedure?

A Stored Procedure is a function which consists of many SQL statements to access the database system. Several SQL statements are consolidated into a stored procedure and execute them whenever and wherever required which saves time and avoid writing code again and again.

Tell us about the new Date and Time API in Java 8

A long-standing problem for Java developers has been the inadequate support for the date and time manipulations required by ordinary developers. The existing classes such as java.util.Date and SimpleDateFormatter aren't thread-safe, leading to potential concurrency issues for users. Poor API design is also a reality in the old Java Data API. Here's just a quick example - years in java.util.Date start at 1900, months start at 1, and days start at 0 which is not very intuitive. These issues and several others have led to the popularity of third-party date and time libraries, such as Joda-Time. In order to address these problems and provide better support in JDK, a new date and time API, which is free of these problems, has been designed for Java SE 8 under the package java.time.

What is Autoboxing and Unboxing ?

Autoboxing is the automatic conversion made by the Java compiler between the primitive types and their corresponding object wrapper classes. For example, the compiler converts an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this operation is called unboxing.

What differences exist between HashMap and Hashtable ?

Both the HashMap and Hashtable classes implement the Map interface and thus, have very similar characteristics. However, they differ in the following features: - A HashMap allows the existence of null keys and values, while a Hashtable doesn't allow neither null keys, nor null values. - A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in single-threaded environments, while a Hashtable is suitable for multi-threaded environments. - A HashMap provides its set of keys and a Java application can iterate over them. Thus, a HashMap is fail-fast. On the other hand, a Hashtable provides an Enumeration of its keys. - The Hashtable class is considered to be a legacy class.

What is the difference between CSS and CSS3?

CSS3 is upgraded version of CSS with new future like Selectors, Box Model, Backgrounds and Borders, Text Effects,2D/3D Transformations, Animations, Multiple Column Layout, User Interface etc.

What are the differences between Checked Exception and Unchecked Exception?

Checked Exception: - The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. - Checked exceptions are checked at compile-time. Example -- IOException, SQLException etc. Unchecked Exception: - The classes that extend RuntimeException are known as unchecked exceptions. - Unchecked exceptions are not checked at compile-time. Example -- ArithmeticException, NullPointerException etc.

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. Finally Finally is used to place important code, it will be executed whether exception is handled or not. Finalize Finalize is used to perform clean up processing just before object is garbage collected.

What are JSP actions ?

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. JSP actions are executed when a JSP page is requested. They can be dynamically inserted into a file, re-use JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.Some of the available actions are listed below: jsp:include - includes a file, when the JSP page is requested. jsp:useBean - finds or instantiates a JavaBean. jsp:setProperty - sets the property of a JavaBean. jsp:getProperty - gets the property of a JavaBean. jsp:forward - forwards the requester to a new page. jsp:plugin - generates browser-specific code.

What are the basic interfaces of Java Collections Framework ?

Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are: Collection, which represents a group of objects known as its elements. Set, which is a collection that cannot contain duplicate elements. List, which is an ordered collection and can contain duplicate elements. Map, which is an object that maps keys to values and cannot contain duplicate keys.

Why java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive datatypes such as boolean, byte, char, int, float, double, long, short which are not objects.

Name the different modules of the Spring framework

Some of the important Spring Framework modules are: - 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.

What is Hibernate Framework?

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa. Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration. Similarly hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.

What are the differences between processes and threads?

Process: Definition - An executing instance of a program is called a process. Communication - Processes must use inter-process communication to communicate with sibling processes. Control - Processes can only exercise control over child processes. Changes - Any change in the parent process does not affect child processes. Memory - Run in separate memory spaces. Controlled by - Process is controlled by the operating system. Dependence - Processes are independent. Threads: Definition - A thread is a subset of the process. Communication - Threads can directly communicate with other threads of its process. Control - Threads can exercise considerable control over threads of the same process. Changes - Any change in the main thread may affect the behavior of the other threads of the process. Memory - Run in shared memory spaces. Controlled by - Threads are controlled by programmer in a program. Dependence - Threads are dependent.

What is Spring IOC container?

The Spring IOC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The spring container uses dependency injection (DI) to manage the components that make up an application.

Which protocol will be used by browser and servlet to communicate ?

The browser communicates with a servlet by using the HTTP protocol.

What is the difference between cross join and natural join?

The cross join produces the cross product or Cartesian product of two tables whereas the natural join is based on all the columns having the same name and data types in both the tables.

List some of the important annotations in annotation-based Spring configuration.

The important annotations are: @Required @Autowired @Qualifier @Resource @PostConstruct @PreDestroy

What are the JDBC API components?

The java.sql package contains interfaces and classes for JDBC API. Interfaces: - Connection - Statement - PreparedStatement - ResultSet - ResultSetMetaData - DatabaseMetaData - CallableStatement etc. Classes: - DriverManager - Blob - Clob - Types - SQLException etc.

What is the purpose of garbage collection in Java, and when is it used ?

The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application, in order for the resources to be reclaimed and reused.

How to implement Joins in Hibernate?

There are various ways to implement joins in hibernate. - Using associations such as one-to-one, one-to-many etc. - Using JOIN in the HQL query. There is another form "join fetch" to load associated data simultaneously, no lazy loading. - We can fire native sql query and use join keyword.

How to integrate Spring and Hibernate Frameworks?

We can use Spring ORM module to integrate Spring and Hibernate frameworks, if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration. Also Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for hibernate boiler-plate code for transaction management. 1. Add hibernate-entitymanager, hibernate-core and spring-orm dependencies. 2. Create Model classes and corresponding DAO implementations for database operations. Note that DAO classes will use SessionFactory that will be injected by Spring Bean configuration. 3. If you are using Hibernate 3, you need to configure org.springframework.orm.hibernate3.LocalSessionFactoryBean or org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean in Spring Bean configuration file. For Hibernate 4, there is single class org.springframework.orm.hibernate4.LocalSessionFactoryBean that should be configured. 4. Note that we don't need to use Hibernate Transaction Management, we can leave it to Spring declarative transaction management using @Transactional annotation.

What are "web workers"?

Web workers at long last bring multi-threading to JavaScript. A web worker is a script that runs in the background (i.e., in another thread) without the page needing to wait for it to complete. The user can continue to interact with the page while the web worker runs in the background. Workers utilize thread-like message passing to achieve parallelism.

What are Directives ?

What are the different types of Directives available in JSP ? Directives are instructions that are processed by the JSP engine, when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined between < %@ and % >.The different types of directives are shown below: Include directive: it is used to include a file and merges the content of the file with the current page. Page directive: it is used to define specific attributes in the JSP page, like error page and buffer. Taglib: it is used to declare a custom tag library which is used in the page.


Ensembles d'études connexes

texas government final - lone star politics - chapter 7, 12, and 2.6

View Set