Anda di halaman 1dari 44

S.

No Question Answer
CORE JAVA 12/16/2016
1 What is the difference between an interface and an An abstract class can have both concrete and abstract methods whereas an interface must have
abstract class? only abstract methods if any.

2 Can you instantiate an abstract class? an No and No. Abstact classes are made to be extended only.
interface?
3 What is the difference between ArrayList and Vector is synchronized whereas ArrayList is not.
Vector?
4 What is the difference between Treeset and The two general purpose Set implementations are HashSet and TreeSet. HashSet is much faster
HashSet? (constant time versus log time for most operations) but offers no ordering guarantees.

5 What type of Collection would not allow duplicate Set.


elements?

6 What is the difference between Hashtable and a.     Hashtable is synchronized whereas Hashmap is not.
Hashmap?
b.     Hashmap permits null values and the null key.

7 How do you serialize (persist) an object in Java? a.     Step 1: An object is marked serializable by implementing the java.io.Serializable interface,
which signifies to the underlying API that the object can be flattened into bytes and subsequently
inflated in the future.

b.     Step 2: The next step is to actually persist the object. That is done with the
java.io.ObjectOutputStream class. That class is a filter stream--it is wrapped around a lower-level
byte stream (called a node stream) to handle the serialization protocol for us. Node streams can be
used to write to file systems or even across sockets. That means we could easily transfer a flattened
object across a network wire and have it be rebuilt on the other side!

c.      To restore the object back, you use ObjectInputStream.readObject() method call. The method
call reads in the raw bytes that we previously persisted and creates a live object that is an exact
replica of the original. Because readObject () can read any serializable object, a cast to the correct
type is required. With that in mind, the class file must be accessible from the system in which the
restoration occurs. In other words, the object's class file and methods are not saved; only the
object's state is saved.

8 What is a stored procedure and how would you call A stored procedure is an executable block of code that is written in PL/SQL and stored in the
it in Java? Oracle database. A stored procedure is called from a Java class using a CallableStatement object.
When the procedure is called, its name and any relevant parameters are sent over
the JDBC connection to the DBMS, which executes the procedure and returns the results (if
applicable) via the connection.

9 What is the difference between Statement and PreparedStatements are pre-compiled by the JVM. The database doesn’t have to compile the SQL
PreparedStatement? each and every time it is executed. PreparedStatement can be parameterized, which can make the
SQL more readable. Furthermore, PreparedStatement will properly escape reserved characters to
prevent SQL injection attacks.

10 How can you force Garbage Collection? Garbage collection cannot be forced but only requested using System.gc().

11 What is final, finalize() and finally? a.     final: final keyword can be used for class, method and variables. A final class cannot be
subclassed and it prevents other programmers from subclassing a secure class to invoke insecure
methods. A final method can’t be overridden. A final variable can’t change from its initialized value.

b.     finalize(): finalize method is used just before an object is destroyed and called just prior to
garbage collection.

c.      finally: finally, a key word used in exception handling, creates a block of code that will be
executed after a try/catch block has completed and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown. For example, if a method
opens a file upon exit, then you will not want the code that closes the file to be bypassed by the
exception-handling mechanism. This finally keyword is designed to address this contingency.

12 What is a Marker Interface? A marker interface is an interface which has no methods at all. Example: Serializable, Remote,
Cloneable. Generally, they are used to give additional information about the behavior of a class.

13 How would you clone an object? First, tag the class with the Cloneable marker interface. Next, invoke clone (). The clone method is
declared in java.lang.Object and does a shallow copy.
14 Why are strings immutable in java? Identical String literals are collected in the "String pool" in an effort to conserve memory. Reference
variables will then point to the same String object instance. Changing the object's state in the
String pool will make changes to all references to that String object. Instead, when a change to a
String is made, the JVM makes a new String object, and the reference variable points to the new
String in the String pool.

15 What is the difference between String, Strings are immutable. Both StringBuilder and StringBuffer are mutable. Furthermore,
StringBuilder, and StringBuffer? StringBuffer is sychronized while StringBuilder is not.

16 What is the difference between static and final Static variable is a global variable shared by all the instances of objects and it has only single copy.
variables? A final variable is a constant variable and it cannot be changed.

17 What are the implicit modifiers required for public static final
interface variables?
18 What are transient variables? Transient variables are those variables which cannot be serialized.

19 What are access modifiers? public – can be accessed from any package.
private – only members of the same class can access.
protected – can be accessed by classes inside the package and subclasses anywhere.
default - no access by classes or subclasses outside the package

20 What is a wrapper class? Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their
corresponding class instances e.g. a boolean data type can be represented as a Boolean class
instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a
wrapper class instance cannot be changed further.

21 What is Reflection API? The first component of the Reflection API is the mechanism used to fetch information about a class.
This mechanism is built into the class named Class. The special class Class is the universal type
for the meta information that describes objects within the Java system. Class loaders in the Java
system return objects of type Class. Up until now the three most interesting methods in this class
were:
forName, which would load a class of a given name, using the current class loader
getName, which would return the name of the class as a String object,which was useful for
identifying object references by their class name
newInstance, which would invoke the null constructor on the class (if it exists) and return you an
object instance of that class of object

To these three useful methods the Reflection API adds some additional methods to class Class.
These are as follows:
getConstructor, getConstructors, getDeclaredConstructor
getMethod, getMethods, getDeclaredMethods
getField, getFields, getDeclaredFields
getSuperclass
getInterfaces
getDeclaredClasses

22 Is Java pass by value or pass by reference? Java is strictly pass by value.

23 What is encapsulation? Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is tightly
controlled by an interface.

24 In what ways can you create a thread? By extending the Thread Class or by implementing the Runnable Interface. You must call Thread's
start() method to start it as a new thread of execution.
25 What is the difference between "==" and equals()? "==" - tests to see if two reference variables refer to the exact same instance of an object.

equals() - tests to see if the two objects being compared to each other are equivalent, but they need
not be the exact same instance of the same object.

26 What is polymorphism? Subclasses of a class can define their own unique behaviors and yet share some of the same
functionality of the parent class. An object can also be referenced by its supertype "parent" class,
for example ParentClass obj = new SubClass( );

27 What is inheritance? A class that is derived from another class is called a subclass (also a derived class, extended class,
or child class). The class from which the subclass is derived is called a superclass (also a base class
or a parent class).

28 What is the difference between method overriding Method overriding - In a subclass when one declares an identical method from the superclass, this
and method overloading? method overrides the one in the superclass.
Method overloading - Within the same class when one declares more than method with the same
name but different signature (parameters).
S.No Question Answer
SQL
1 What is a primary key? A primary key is a column or set of columns that uniquely identify each row of a table. A driver's
license number, a VIN number, or UPC (universal product code) are example of a primary key. A
primary key must be unique and not null.

2 What is a foreign key? A foreign key is a column (or columns) that references a column (most often the primary key) of
another table. This is to establish a relationship between records in separate tables.

3 What is referential integrity? Referential integrity means that the foreign key in any referencing table must always refer to a valid
row in the referenced table. Referential integrity ensures that the relationship between two tables
remains synchronized during updates and deletes.

4 How can you retrieve rows from a database table? Using a SELECT statement (aka query). The basic syntax is:
SELECT [ column_list | * ]
[FROM table]
[JOIN table ON join_predicate] ...
[WHERE where_condition]
[GROUP BY {col_name}
[ASC | DESC]]
[HAVING condition]
[ORDER BY {col_name}
[ASC | DESC]]

5 What is the difference between INNER JOIN and The difference between an inner join and an outer join is that an inner join will return only the
OUTER JOIN? rows that actually match based on the join predicate. An outer join will also return rows that are
not common between both tables.

6 How do you add a record to a table? The INSERT statement. The basic syntax to insert a value for each and every column is:

INSERT INTO TABLE VALUES( ___ , ___ , ___ , ___ )


To insert only specific columns and leave others null:
INSERT INTO TABLE(col1, col2) VALUES( ___ , ___ )

7 How would use IN and EXISTS? What is the IN works best for a small finite set of data, whereas EXISTS is better for subqueries. In most cases,
difference? EXISTS will be much more efficient (and faster) than an IN statement. When using an IN combined
with a subquery, the database must process the entire subquery first, then process the overall
query as a whole, matching up based on the relationship specified for the IN. With an EXISTS or a
JOIN, the database will return true/false while checking the relationship specified. Unless the table
in the subquery is very small, EXISTS or JOIN will perform much better than IN.

8 What is the WHERE clause? What is the purpose of The SQL WHERE clause is used to specify a condition while fetching the data from single table or
AND and OR? joining with multiple tables.

If the given condition is satisfied then only it returns specific rows from the table. You would use
WHERE clause to filter the records and fetching only necessary records.

The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE
statement, etc.

The SQL AND and OR operators are used to combine multiple conditions to narrow data in an SQL
statement. These two operators are called conjunctive operators.

These operators provide a means to make multiple comparisons with different operators in the
same SQL statement.

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] AND [condition2]…OR [conditionN];

9 How do you add a column to the table? The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

ALTER TABLE table_name


ADD column_name datatype
10 Can you have more than one primary key in one No. A table can have one and only one primary key constraint. However, a primary key can contain
table? Can a primary key contain more than one more than one column. A composite key is a combination of two or more columns in a table that
column? can be used to uniquely identify each row in the table. Uniqueness is only guaranteed when the
columns are combined; when taken individually the columns do not guarantee uniqueness.

11 What are one-to-one, one-to-many and many-to- One-to-One (1:1) relationship is defined as the relationship between two tables where both the
many relationships, and how do you implement? tables should be associated with each other based on only one matching row. This relationship can
be created using Primary key-Unique foreign key constraints. With One-to-One Relationship in
SQL, for example, a person can have only one passport.

The One-to-Many (1:M) relationship is defined as a relationship between two tables where a row
from one table can have multiple matching rows in another table. This relationship can be created
using Primary key-Foreign key relationship. In the One-to-Many Relationship in SQL, for example,
a book can have multiple authors.

A Many-to-Many (M:N) relationship is defined as a relationship between two tables where many
rows from one table can have multiple matching rows in another table. Neither table can support a
foreign key to relate the tables, so a junction table (aka join table or associative entity) is created. A
junction table is a database table that contains foreign key references to two or more other
database tables. It is the standard way of creating a many-to-many relationship between tables.

12 How do you drop a table? Using the DROP TABLE statement. It removes one or more table definitions and all data, indexes,
triggers, constraints, and permission specifications for those tables. Any view or stored procedure
that references the dropped table must be explicitly dropped by using DROP VIEW or DROP
PROCEDURE.

DROP TABLE [ IF EXISTS ] [ database_name . [ schema_name ] . | schema_name . ]


table_name

13 What is the difference between DELETE, The DELETE command is used to remove rows from a table. A WHERE clause can be used to only
TRUNCATE, and DROP? remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a
DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change
permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will
be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.

The DROP command removes a table from the database. All the tables' rows, indexes and privileges
will also be removed. No DML triggers will be fired. The operation cannot be rolled back.

14 What is an entity relational diagram (ERD)? An entity-relationship diagram—otherwise known as an ERD—is a data modeling technique that
creates an illustration of an information system's entities and the relationships between those
entities.

There are 3 ingredients in a standard entity-relationship diagram:


•Entities, which represent people, places, items, events, or concepts.
•Attributes, which represent properties or descriptive qualities of an entity. These are also known
as data elements.
•Relationships, which represent the link between different entities.

Entities, attributes, and relationships can be represented in one of three ways: with a conceptual
model, logical model, or physical model. These models increase in complexity as you move from
conceptual to logical to physical. It's usually best to start with a conceptual ERD model, so you can
understand—at the highest level—the entities in your data and how they relate to each other. As
you transform a conceptual ERD to a physical model, you'll learn exactly how to implement
modeled information into the database of your choice.

There are two main types of ERD notations: Crow's Foot notation and Chen notation.
15 What are various constraints in SQL? NOT NULL - Indicates that a column cannot store NULL value
UNIQUE - Ensures that each row for a column must have a unique value
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or
combination of two or more columns) have a unique identity which helps to find a particular record
in a table more easily and quickly
FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another
table
CHECK - Ensures that the value in a column meets a specific condition
DEFAULT - Specifies a default value for a column

16 What is the difference between WHERE and HAVING specifies a search condition for a group or an aggregate function used in SELECT
HAVING? statement. WHERE cannot be used to apply restrictions to an aggregate function.

17 What is normalization? Normalization is the process of organizing data in a database. This includes creating tables and
establishing relationships between those tables according to rules designed both to protect the data
and to make the database more flexible by eliminating redundancy and inconsistent dependency.
There are six normal forms, though many organizations only use the first three.

(1NF) Eliminate repeating groups in individual tables. Create a separate table for each set of related
data. Identify each set of related data with a primary key.

(2NF) A table is in 2NF if it is in 1NF and every non-key attribute of the table is dependent on the
primary key as a whole (no partial dependencies). Therefore, a table is automatically in 2NF if the
table does not use a composite key.

(3NF) The table is in third normal form if it is in 2NF and every non-key attribute is not dependent
upon any non-key attribute (aka transitive dependency)

18 What is UNION, UNION ALL, MINUS, INTERSECT? The UNION operator returns only distinct rows that appear in either result, while the UNION ALL
In these statements, what conditions must be met? operator returns all rows. The UNION ALL operator does not eliminate duplicate selected rows. The
INTERSECT operator returns only those rows returned by both queries. The MINUS operator
returns only unique rows returned by the first query but not by the second. The corresponding
expressions in the select lists of the component queries of a compound query must match in
number and must be in the same datatype group (such as numeric or character).

19 What is a nested query (or subquery)? A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause. A subquery is used to return data that will be used in the main query as
a condition to further restrict the data to be retrieved. Subqueries can be used with the SELECT,
INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN,
BETWEEN etc.

20 What is an orphan? Orphaned records are records that reference a key which no longer exists in the foreign table. If
referential integrity is enforced by using a foreign key constraint, this cannot happen.

21 What is the purpose of SELECT INTO? The SELECT INTO statement selects data from one table and inserts it into a new table.

SELECT *
INTO new_table
FROM table1

22 What is a cross join? A cross join does not have a WHERE or ON clause, therefore it produces the Cartesian product of
the tables involved in the join. The size of a Cartesian product result set is the number of rows in
the first table multiplied by the number of rows in the second table.

23 What is the difference between INNER JOIN, LEFT INNER JOIN: Returns all rows when there is at least one match in BOTH tables
JOIN, RIGHT JOIN, and FULL JOIN? LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables

24 What is a cascade delete? A foreign key with cascade delete means that if a record in the parent table is deleted, then the
corresponding records in the child table will automatically be deleted. This is called a cascade
delete in SQL Server.

A foreign key with cascade delete can be created using either a CREATE TABLE statement or an
ALTER TABLE statement.
25 What are some of the String manipulation methods SUBSTRING, TRIM, LTRIM, RTRIM, REVERSE, REPLACE, LENGTH, CONCAT, UCASE, LCASE, etc.
in SQL?

26 What is GRANT and REVOKE? You can grant users various privileges to tables and revoke those privileges. These privileges can be
any combination of SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER, INDEX, or ALL.

GRANT privileges ON object TO user;


REVOKE privileges ON object FROM user;

27 What is the difference between Order By and Group The ORDER BY keyword is used to sort the result-set by one or more columns. The ORDER BY
By? keyword sorts the records in ascending order by default (ASC). To sort the records in a descending
order, you can use the DESC keyword.

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-
set by one or more columns.

28 What is a view? In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows
and columns, just like a real table. The fields in a view are fields from one or more real tables in the
database. You can add SQL functions, WHERE, and JOIN statements to a view and present the
data as if the data were coming from one single table.

CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

29 What's an index? An index can be created in a table to find data more quickly and efficiently. Indexes allow the
database application to find data fast; without reading the whole table. The users cannot see the
indexes, they are just used to speed up searches/queries. Updating a table with indexes takes more
time than updating a table without (because the indexes also need an update). So you should only
create indexes on columns that will be frequently searched against. You can use indexes or unique
indexes (which require a unique value).

30 What is a trigger? Triggers are stored programs in PL/SQL, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE). A database definition
(DDL) statement (CREATE, ALTER, or DROP). A database operation (SERVERERROR, LOGON,
LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.

31 How do you prevent SQL injection? Option #1: Use of Prepared Statements (Parameterized Queries)
Option #2: Use of Stored Procedures
Option #3: Escaping all User Supplied Input
Also Enforce: Least Privilege
Also Perform: White List Input Validation

32 What is connection pooling? A connection pool contains a group of JDBC connections that are created when the connection pool
is registered—when starting up WebLogic Server or when deploying the connection pool to a target
server or cluster. Connection pools use a JDBC driver to create physical database connections.
Your application borrows a connection from the pool, uses it, then returns it to the pool by closing
it.

33 What is a scalar function? SQL scalar functions return a single value, based on the input value.
•UCASE() - Converts a field to upper case
•LCASE() - Converts a field to lower case
•MID() - Extract characters from a text field
•LEN() - Returns the length of a text field
•ROUND() - Rounds a numeric field to the number of decimals specified
•NOW() - Returns the current system date and time
•FORMAT() - Formats how a field is to be displayed
34 What is an aggregate function? SQL aggregate functions return a single value, calculated from values in a column.
•AVG() - Returns the average value
•COUNT() - Returns the number of rows
•FIRST() - Returns the first value
•LAST() - Returns the last value
•MAX() - Returns the largest value
•MIN() - Returns the smallest value
•SUM() - Returns the sum

35 What is a cursor? Oracle creates a memory area, known as context area, for processing an SQL statement, which
contains all information needed for processing the statement, for example, number of rows
processed, etc.

A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds
is referred to as the active set.

You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors: Implicit cursors and
Explicit cursors

36 What is an implicit cursor? Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and
the information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.

37 What is an explicit cursor? Explicit cursors are programmer defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.
CURSOR cursor_name IS select_statement;

Working with an explicit cursor involves four steps:

Declaring the cursor for initializing in the memory


Opening the cursor for allocating memory
Fetching the cursor for retrieving data
Closing the cursor to release allocated memory
S.No Question Answer
HIBERNATE
1 What is ORM ? ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java
application to the tables in a relational database.

2 What does ORM consists of ? An ORM solution consists of the following four pieces:
●     API for performing basic CRUD operations
●     API to express queries referring to classes
●     Facilities to specify metadata
●     Optimization facilities : dirty checking,lazy associations fetching

3 What are the ORM levels ? The ORM levels are:


●     Pure relational (stored procedure.)
●     Light objects mapping (JDBC)
●     Medium object mapping
●     Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4 What is Hibernate? Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows
you to map plain old Java objects to relational database tables using (XML) configuration files.Its
purpose is to relieve the developer from a significant amount of relational data

5 Why do you need ORM tools like Hibernate? The main advantage of ORM like hibernate is that it shields developers from messy SQL.

●     Improved productivity


○     High-level object-oriented API
○     Less Java code to write
○     No SQL to write

●     Improved performance


○     Sophisticated caching
○     Lazy loading
○     Eager loading

●     Improved maintainability


○     A lot less code to write

●     Improved portability


○     ORM framework generates database-specific SQL for you

6 What are the core interfaces are of the Hibernate


The five core interfaces are used in just about every Hibernate application. Using these interfaces,
framework?
you can store and retrieve persistent objects and control transactions.
●     Session interface
●     SessionFactory interface
●     Configuration interface
●     Transaction interface
●     Query and Criteria interfaces

7 What are the types of Hibernate instance states ? Three types of instance states:
●     Transient - not associated with any data. After instantiation.
●     Persistent - associated with data. After CRUD method (save, update, delete).
●     Detached - no longer associated with the data. After session is closed.

8 What are the essential properties of a transaction? The transaction must be atomic, consistent, isolated and durable (ACID).
● Atomic means the transaction must execute completely or not at all.
● Consistency refers to integrity of the underlying data store.
● Isolated refers to transaction execution without interference from other processes or
transactions.
● Durability means that data is not lost during system crashes.
9 What are Transaction Isolation Levels? The transaction isolation level indicates the degree to which two transactions interact with each
other over the same data. The transaction problems that can occur are: lost update, dirty read,
unrepeatable read, and phantom read.

Isolation Description
Read Uncommitted Permits dirty reads but not lost updates
Read Committed Permits unrepeatable reads but not dirty reads
Repeatable Read Permits neither unrepeatable reads nor dirty reads but permits
phantom reads
Serializable Provides strictest isolation. Most inefficient. No concurrency.
Locks entire table during each transaction.

10 What is the difference between the first and second First level cache Second level cache
level caches in Hibernate? ● Default ● Optional/pluggable
● Transaction scoped. ● Might be scoped to the process or cluster.
● Formed by the session object. ● Formed by the SessionFactory object.
● Single session availability. ● Multiple session availability.
● Guarantees object identity inside a ● Can be configured on per class or per association
transaction. basis.

11 Name some second level (L2) cache providers for EHCache, OSCache, SwarmCache, and JBossCache
Hibernate.

12 How do you configure an L2 cache in Hibernate? ● Choose an L2 cache vendor that has the desired properties.
● In hibernate.cfg.xml include a cache provider tag:
<property name="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider
</property>
● Set the cache properties in the cache provider's xml or use annotations in the persistent class.

Example:
<cache
name="com.somecompany.someproject.domain.Country"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>

13 What are some common JPA annotations used in Some common annotations for the Hibernate POJO to eliminate the mapping file are:
Hibernate?

@Entity This required annotation above the class declaration maps the class to a table with the
same name.
@Id This required annotation above an instance variable makes it a primary key.
@Table and @Column which each have many attributes are both optional.

14 What is the difference in the hibernate.cfg.xml for the Mapping file implementation: <mapping resource="myTable.hbm.xml"/>
mapped (hbm) and annotation driven class?
Annotated POJO implementation: <mapping class="myTable"/>
15 What is the need for Hibernate xml mapping file? Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.
Typical mapping file look as follows:

16 What are the important tags of hibernate.cfg.xml? Following are the important tags of hibernate.cfg.xml:

17 What role does the Session interface play in The Session interface is the primary interface used by Hibernate applications. It is a single-
Hibernate? threaded, short-lived object representing a conversation between the application and the persistent
store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();

Session interface role:


●     Wraps a JDBC connection
●     Factory for Transaction
●     Holds a mandatory (first-level) cache of persistent objects, used when navigating the object
graph or looking up objects by identifier
18 What role does the SessionFactory interface play in The application obtains Session instances from a SessionFactory. There is typically a single
Hibernate? SessionFactory for the whole application created during application initialization. The
SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses
at runtime. It also holds cached data that has been read in one unit of work and may be reused in
a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

19 What is the general flow of a Hibernate communication The general flow of Hibernate communication with RDBMS is :
with the RDBMS?
●     Load the Hibernate configuration file and create configuration object. It will automatically load
all hbm mapping files
●     Create session factory from configuration object
●     Get one session from this session factory
●     Create HQL Query
●     Execute query to get list containing Java objects

20 What is Hibernate Query Language (HQL)? Hibernate offers a query language that embodies a very powerful and flexible mechanism to query,
store, update, and retrieve objects from a database. This language, the Hibernate query Language
(HQL), is an object-oriented extension to SQL.

21 How do you map Java Objects with Database tables? ●     First we need to write Java domain objects (beans with setter and getter).
●     Write hbm.xml, where we map java class to table and database columns to Java class
variables.

Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>

22 What’s the difference between load() and get()? load() get()


●  Only use the load() method if you are sure that the ●  If you are not sure that the object exists,
object exists. then use one of the get() methods.
●  load() method will throw an exception if the unique ●  get() method will return null if the unique
id is not found in the database. id is not found in the database.
●  load() just returns a proxy by default and database ●  get() will hit the database immediately.
won’t be hit until the proxy is first invoked.

23 What is the difference between and merge and Use update() if you are sure that the session does not contain an already persistent instance with
update ? the same identifier, and merge() if you want to merge your modifications at any time without
consideration of the state of the session.

24 How do you define sequence generated primary key in Using <generator> tag.
hibernate?

Example:-
<id column="USER_ID" name="id" type="java.lang.Long">
<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>

25 Define cascade and inverse option in one-many cascade - enable operations to cascade to child entities.
mapping?

cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.

inverse="true|false"

Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a
parent who has a collection of children, should you ask the parent for its list of children, or ask the
children who the parents are?
26 What is a Named SQL Query? Named SQL queries are defined in the mapping xml document and called wherever required.

Example:
<sql-query name = "empdetails">
<return alias="emp" class="com.test.Employee"/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

Invoke Named Query :


List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();

27 How do you invoke Stored Procedures? Stored procedures are defined in the mapping xml document and called wherever required.

<sql-query name="selectAllEmployees_SP" callable="true">


<return alias="emp" class="employee">
<return-property name="empid" column="EMP_ID"/>

<return-property name="name" column="EMP_NAME"/>


<return-property name="address" column="EMP_ADDRESS"/>

</return>
</sql-query>

28 Explain Criteria API Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very
convenient approach for functionality like "search" screens where there is a variable number of
conditions to be placed upon the result set.

Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();

29 How do you switch between different relational For an application managed datasource:
databases? In hibernate.cfg.xml change the driver properties (URL, username, and password) to the new
database.
Use the appropriate connector jar for the new database in the project classpath.
For a server managed datasource:
In the hibernate.cfg.xml change the JNDI name to the one for the new database.

In either case:
In hibernate.cfg.xml change the property tag: name = dialect to the new database dialect.
No changes to the java code are required!

30 If you want to see the Hibernate generated SQL In Hibernate configuration file set as follows:
statements on console, what should we do? <property name="show_sql">true</property>

31 What is the difference between sorted and ordered sorted collection order collection
collection in hibernate? A sorted collection is sorting a collection by utilizing Order collection is sorting a collection by
the sorting features provided by the Java collections specifying the order-by clause for sorting
framework. The sorting occurs in the memory of JVM this collection when retrieval.
which running Hibernate, after the data being read
from database using java comparator.

If your collection is not large, it will be more efficient If your collection is very large, it will be
way to sort it. more efficient way to sort it .

32 What are the Collection types in Hibernate ? ●     Bag


●     Set
●     List
●     Array
●     Map
33 What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:-

●     An implicit association join


●     An ordinary join in the FROM clause
●     A fetch join in the FROM clause.
●     A theta-style join in the WHERE clause.

34 What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will
initially return CGLIB proxies which implement the named interface. The actual persistent object
will be loaded when a method of the proxy is invoked.

35 What is the use of dynamic-insert and dynamic-update


attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very
convenient approach for functionality like "search" screens where there is a variable number of
conditions to be placed upon the result set.

●     dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime
and contain only those columns whose values have changed

●     dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime
and contain only the columns whose values are not null.

36 What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the
application needs to navigate the association. Fetch strategies may be declared in the O/R mapping
metadata, or over-ridden by a particular HQL or Criteria query.

37 What is automatic dirty checking? Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to
update the database when we modify the state of an object inside a transaction.

38 What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database
foreign key constraint violations but is still sufficiently predictable to the user. This feature is called
transactional write-behind.

39 What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting
happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate
applications don't need to implement these callbacks, but they're useful for implementing certain
kinds of generic functionality.

40 What are the types of inheritance models in Hibernate? There are three types of inheritance models in Hibernate:
●     Table per class hierarchy
●     Table per subclass
●     Table per concrete class
41 What is the advantage of Hibernate over jdbc? JDBC Hibernate
With JDBC, developer has to write code to map an Hibernate is flexible and powerful ORM
object model's data representation to a relational data solution to map Java classes to database
model and its corresponding database schema. tables. Hibernate itself takes care of this
mapping using XML files so developer does
not need to write code for this.

With JDBC, the automatic mapping of Java objects Hibernate provides transparent persistence
with database tables and vice versa conversion is to be and developer does not need to write code
taken care of by the developer manually with lines of explicitly to map database tables tuples to
code. application objects during interaction with
RDBMS.

JDBC supports only native Structured Query Hibernate provides a powerful query
Language (SQL). Developer has to find out the efficient language Hibernate Query Language
way to access database, i.e. to select effective query (independent from type of database) that is
from a number of queries to perform same task. expressed in a familiar SQL like syntax and
includes full support for polymorphic
queries. Hibernate also supports native SQL
statements. It also selects an effective way
to perform a database manipulation task
for an application.

Application using JDBC to handle persistent data Hibernate provides this mapping itself. The
(database tables) having database specific code in large actual mapping between tables and
amount. The code written to map table data to application objects is done in XML files. If
application objects and vice versa is actually to map there is change in Database or in any table
table fields to object properties. As table changed or then the only need to change XML file
database changed then it’s essential to change object properties.
structure as well as to change code written to map
table-to-object/object-to-table.

With JDBC, it is developer’s responsibility to handle Hibernate reduces lines of code by


JDBC result set and convert it to Java objects through maintaining object-table mapping itself and
code to use this persistent data in application. So with returns result to application in form of Java
JDBC, mapping between Java objects and database objects. It relieves programmer from
tables is done manually. manual handling of persistent data, hence
reducing the development time and
maintenance cost.

With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence,


cache is set to application work space.
Relational tuples are moved to this cache as
a result of query. It improves performance if
client application reads same data many
times for same write. Automatic
Transparent Persistence allows the
developer to concentrate more on business
logic rather than this application code.

In JDBC there is no check that always every user has Hibernate enables developer to define
updated data. This check has to be added by the version type field to application, due to this
developer. defined field Hibernate updates version field
of database table every time relational tuple
is updated in form of Java class object to
that table. So if two users retrieve same
tuple and then modify it and one user save
this modified tuple to database, version is
automatically updated for this tuple by
Hibernate. When other user tries to save
updated tuple to database then it does not
allow saving it because this user does not
have updated data.
S.No Question Answer
SPRING
1 What is IOC? A key characteristic of IOC is the calling code has the ability to customize the calling methods
according to an external configuration (XML) file. IOC is used heavily in all frameworks such as
Spring, Struts, and EjB. The most common implementation of IOC is dependency injection.

2 What is dependency injection? A software design pattern that uses a Builder pattern to obtain valid instances of your object's
dependencies and pass them to your object during the object's creation and/or initialization. Using
polymorphism and interfaces, the class that needs the dependency does not need to reference the
concrete class type. Instead, you declaratively express dependencies through a configuration
medium (like XML). The main goal is to decouple classes and test concrete classes in isolation.

3 What are the different types of dependency There are three types of dependency injection:
injection and which does Spring support?
●     Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as
constructor parameters.

●     Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex:
setter methods).

●     Interface Injection (e.g. Avalon): Injection is done through an interface.

Note: Spring supports only Constructor and Setter Injection

4 What are the benefits of IOC ? Benefits of IOC are as follows:

●     Minimizes the amount of code in your application. With IOC containers you do not care about
how services are created and how you get references to the ones you need. You can also easily add
additional services by adding a new constructor or a setter method with little or no extra
configuration.

●     Make your application more testable by not requiring any singletons or JNDI lookup
mechanisms in your unit test cases. IOC containers make unit testing and switching
implementations very easy by manually allowing you to inject your own objects into the object
under test.

●     Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory
design pattern is more intrusive because components or services need to be requested explicitly
whereas in IOC the dependency is injected into requesting piece of code. Also some containers
promote the design to interfaces not to implementations design concept by encouraging managed
objects to implement a well-defined service interface of your own.

●     IOC containers support eager instantiation and lazy loading of services. Containers also
provide support for instantiation of managed objects, cyclical dependencies, life cycles
management, and dependency resolution between managed objects etc.

5 What is Spring ? Spring is an open source framework created to address the complexity of enterprise application
development. One of the chief advantages of the Spring framework is its layered architecture, which
allows you to be selective about which of its components you use while also providing a cohesive
framework for J2EE application development.
6 What are some features of Spring ? ●     Lightweight:
spring is lightweight when it comes to size and transparency. The basic version of spring framework
is around 1MB. And the processing overhead is also very negligible.

●     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. But other frameworks can be easily used
instead of Spring MVC Framework.

●     Transaction Management:


Spring framework provides a generic abstraction layer for transaction management. This allowing
the developer to add the pluggable transaction managers, and making it easy to demarcate
transactions without dealing with low-level issues. Spring’s transaction support is not tied to J2EE
environments and it can be also used in container less environments.

●     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

7 Name the modules of Spring. The basic Spring Framework contains the following libraries grouped by functionality.

1) Core Container
org.springframework.core
org.springframework.beans
org.springframework.expression
org.springframework.context
org.springframework.context.support

2) Test
org.springframework.test

3) AOP
org.springframework.aop
org.springframework.aspects

4) Instrumentation
org.springframework.instrument
org.springframework.instrument.tomcat

5) Web and Remoting


org.springframework.web
org.springframework.web.portlet
org.springframework.web.servlet
org.springframework.web.struts

6) Data Access and Integration


org.springframework.jdbc
org.springframework.jms
org.springframework.orm
org.springframework.oxm
org.springframework.transaction
8 What is Bean Factory? A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds
Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for
by clients.

●     BeanFactory is able to create associations between collaborating objects as they are
instantiated. This removes the burden of configuration from bean itself and the beans client.

●     BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization
and destruction methods.

9 What is Application Context? A bean factory is fine to simple applications, but to take advantage of the full power of the Spring
framework, you may want to move up to Springs more advanced container, the application context.
On the surface, an application context is same as a bean factory.Both load bean definitions, wire
beans together, and dispense beans upon request. ApplicationContext will preinstantiate singleton
beans and also provides:

●     A means for resolving text messages, including support for internationalization.
●     A generic way to load file resources.
●     Events to beans that are registered as listeners.

10 What is the difference between BeanFactory and On the surface, an ApplicationContext is the same as a the bean factory, but it offers much more..
ApplicationContext ?
●     ApplicationContext preinstantiates the beans (Singletons) while BeanFactory does lazy
initialization.

●     ApplicationContext provides a means for resolving text messages including support for I18N.

●     ApplicationContext provide a generic way to load file resources such as images.

●     ApplicationContext can publish events to beans that are registered as listeners.

●     Certain operations on the container or beans in the container, which have to be handled in a
programmatic fashion with a bean factory, can be handled declaratively in an application context.

●     ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for
handling low-level resources. An ApplicationContext itself is a ResourceLoader, Hence provides an
application with access to deployment-specific Resource instances.

●     MessageSource support: The ApplicationContext implements MessageSource, an interface


used to obtain localized messages, with the actual implementation being pluggable.

11 What are the common implementations of the The three commonly used implementation of ‘Application Context’ are
Application Context ?
●     ClassPathXmlApplicationContext : It loads context definition from an XML file located in the
classpath, treating context definitions as classpath resources. The application context is loaded
from the application’s classpath by using the code .

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

●     FileSystemXmlApplicationContext : It loads a context definition from an XML file in the file
system. The application context is loaded from the file system by using the code .
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");

●     XmlWebApplicationContext : It loads context definition from an XML file contained within a
web application.
12 What is the typical Bean life cycle in Spring Bean Bean life cycle in Spring Bean Factory Container is as follows:
Factory Container ?
●     The spring container finds the bean’s definition from the XML file and instantiates the bean.

●     Using the dependency injection, spring populates all of the properties as specified in the bean
definition

●     If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing
the bean’s ID.

●     If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(),
passing an instance of itself.

●     If there are any BeanPostProcessors associated with the bean, their post-
ProcessBeforeInitialization() methods will be called.

●     If an init-method is specified for the bean, it will be called.

●     Finally, if there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.

13 What do you mean by bean wiring ? The act of creating associations between application components (beans) within the Spring
container is referred to as Bean wiring.

14 What do you mean by autowiring? The Spring container is able to autowire relationships between collaborating beans. This means
that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by
inspecting the contents of the BeanFactory. The autowiring functionality has four modes.

●     byName
●     byType
●     constructor
●     autodetect

15 Name the design pattern used in the Spring MVC The design pattern followed by all MVC frameworks including Struts, JSF, and Spring is the Front
architecture and the control element? Controller pattern. The central control element in Spring MVC is the Dispatcher Servlet.

16 What does DefaultAnnotationHandlerMapping do This is one of five handler mapping classes available in Spring. It is used by DispatcherServlet to
in Spring MVC? map requests to specific controllers and controller methods annotated with @RequestMapping.

17 What does the ViewResolver do in Spring MVC? The last task to be perfomed in HTTP request handling is rendering output to the user. The
ViewResolver exchanges a logical view name supplied by the controller for a an actual view (JSP)
that renders the result. There are 12 ViewResolver classes to choose from depending on the desired
rendering technology.

18 How do you turn ON annotation support in Spring Use <mvc:annotation-driven /> in mvc-dispatcher-servlet.xml to switch ON annotation support,
MVC? form validation, message conversion, and field formatting.

19 List the annotations used to configure a basic The annotations required to configure a basic spring controller class are:
controller class in Spring MVC.
@Controller This registers the class as a controller and must be used in conjunction with
<context: component-scan /> tag in the XML to automatically discover and register the controllers
as Spring beans.

@RequestMapping This identifies the method as a request handler type for a given path.

20 How do you turn ON annotation-based autowiring To turn ON autowiring use the <context:annotation-config/> tag in the spring xml.
in Spring? This will enble @Autowired, @Inject (JSR-330), and @Resource (JSR-250).

21 How does the @Autowired annotation work? It is used to automatically wire values into properties, methods, and constructors. It works similar
to xml-based autowiring but can be selectively used. Bean properties can be annotated direcly
allowing removal of the setters in the class and the <property> tags in the spring xml. If no bean is
found to wire to the annotated property a NoSuchBeanDefinitionException is thrown by default.

22 What annotations are used to register a class as a By default, <context:component-scan> in the spring.xml tells the container to look for classes that
spring bean? are annotated with one of the following:
@Component The class defines a Spring component.
@Controller The class defines a Spring MVC controller.
@Repository The class defines a data repository such as a DAO implementation class.
@Service The class defines a service.
23 How do you integrate Struts with Spring? Using ContextLoaderPlugIn:
● Install the ContextLoaderPlugin in struts-config.xml
● In the "type" attribute of the action tag use:
org.springframework.web.struts.DelegatingActionProxy.
● In action-servlet.xml map the HTML action to the action class and reference the injected bean.
● In appContext.xml map the injected bean to a bean class.
● In the action class install a setter for the injected bean.

24 What ORMs does Spring support ? Spring supports the following ORMs :

●     Hibernate
●     iBatis
●     JPA (Java Persistence API)
●     TopLink
●     JDO (Java Data Objects)
●     OJB

25 What are the ways to access Hibernate using There are several ways to achieve this; however, the two popular approaches to Spring’s Hibernate
Spring? integration are:

●    Hibernate Contextual Sessions (newer)


●    HibernateTemplate (older)

26 How do you integrate Spring and Hibernate using There are two popular approaches to this declarative, POJO-based integration:
Contextual Sessions?
1) XML approach:
●   Create the DaoImpl class with a setter for the Session Factory.
●   Wire up the following beans: DataSource, SessionFactory, HibernateTransactionManager, and
DaoImpl class.
●    Bind each CRUD method to a transaction in the appContext.xml. Define the AOP configuarion
using the <aop:config> tags and the transaction advice using the <tx:advice> tags and the
transaction properties (propagation, isolation, and rollback) for each method with the <tx:method>
tags.

2) Annotation approach:
●   Create the annotated (@Repository) DaoImpl class with an annotated (@Inject) sessionFactory.
●   Wire up the following beans: DataSource, SessionFactory, and HibernateTransactionManager in
the appContext.xml
● Use <context:component-scan> to find the annotated classes.
● Include a PersistenceExceptionTranslationPostProcessor bean definition to convert platform
specific exceptions to a richer set of Spring runtime data access exceptions.
● Bind and annotate (@Transactional) each CRUD method to a transaction in the DaoImpl class
and use the <tx:annotation-driven> tag in appContext.xml.

27 Define HibernateTemplate. org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different


methods for querying/retrieving data from the database. It also converts checked
HibernateExceptions into unchecked DataAccessExceptions.

28 What benefits does the HibernateTemplate provide? The benefits of the Hibernate Template are:
●     HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
●     Common functions are simplified to single method calls.
●     Sessions are automatically closed.
●     Exceptions are automatically caught and converted to runtime exceptions.

29 How did you integrate Spring and Hibernate using Follow this three-step process:
Template Injection? ●   Wire up the following beans in the spring.xml: DataSource, SessionFactory,
HibernateTransactionManager, and DaoImpl class.
●   Place a setter for the HibernateTemplate in the DaoImpl class and
●   Create an anonymous inner class to implement the doInHibernate method of the Callback
interface and place the desired Template CRUD method there. Pass the inner class object to the
Template execute method to invoke the desired CRUD operation.
30 What are Bean scopes in Spring Framework ? The Spring Framework supports exactly five scopes (of which three are available only if you are
using a web-aware ApplicationContext). The scopes supported are listed below:

Scope Description
singleton Scopes a single bean definition to a single object
instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object
instances.
request Scopes a single bean definition to the lifecycle of a
single HTTP request; that is each and every HTTP
request will have its own instance of a bean created off
the back of a single bean definition. Only valid in the
context of a web-aware Spring ApplicationContext.

session Scopes a single bean definition to the lifecycle of a


HTTP Session. Only valid in the context of a web-aware
Spring ApplicationContext.

global session Scopes a single bean definition to the lifecycle of a


global HTTP Session. Typically only valid when used in
a portlet context. Only valid in the context of a web-
aware Spring ApplicationContext.

31 What is AOP? Aspect-oriented programming, or AOP, is a programming technique that allows programmers to
modularize crosscutting concerns, or behavior that cuts across the typical divisions of
responsibility, such as logging and transaction management. The core construct of AOP is the
aspect, which encapsulates behaviors affecting multiple classes into reusable modules.

32 How is AOP used in Spring? AOP is used in the Spring Framework to provide declarative enterprise services, especially as a
replacement for EJB declarative services. The most important such service is declarative
transaction management, which builds on the Spring Framework’s transaction abstraction.To allow
users to implement custom aspects, complementing their use of OOP with AOP.

33 What do you mean by Aspect ? A modularization of a concern that cuts across multiple objects. Transaction management is a good
example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented
using regular classes (the schema-based approach) or regular classes annotated with the @Aspect
annotation (@AspectJ style).

34 What do you mean by join point? A point during the execution of a program, such as the execution of a method or the handling of an
exception. In Spring AOP, a join point always represents a method execution.

35 What do you mean by Advice? Action taken by an aspect at a particular join point. Different types of advice include “around,”
“before” and “after” advice. Many AOP frameworks, including Spring, model an advice as an
interceptor, maintaining a chain of interceptors “around” the join point.

36 What are the types of Advice? Types of advice:


●     Introduction : Introduction advice cannot be used with any pointcut, as it applies only at class,
rather than method, level. You can only use introduction advice with the IntroductionAdvisor.

●     Before advice: Advice that executes before a join point, but which does not have the ability to
prevent execution flow proceeding to the join point (unless it throws an exception).

●     After returning advice: Advice to be executed after a join point completes normally: for example,
if a method returns without throwing an exception.

●     After throwing advice: Advice to be executed if a method exits by throwing an exception.

●     After (finally) advice: Advice to be executed regardless of the means by which a join point exits
(normal or exceptional return).

●     Around advice: Advice that surrounds a join point such as a method invocation. This is the
most powerful kind of advice. Around advice can perform custom behavior before and after the
method invocation. It is also responsible for choosing whether to proceed to the join point or to
shortcut the advised method execution by returning its own return value or throwing an exception

37 What are the types of the transaction management Spring Framework supports:
Spring supports?
●     Programmatic transaction management.
●     Declarative transaction management.
38 What are the benefits of the Spring Framework The Spring Framework provides a consistent abstraction for transaction management that delivers
transaction management? the following benefits:

●     Provides a consistent programming model across different transaction APIs such as JTA,
JDBC, Hibernate, JPA, and JDO.

●     Supports declarative transaction management.

●     Provides a simpler API for programmatic transaction management than a number of complex
transaction APIs such as JTA.

●     Integrates very well with Spring’s various data access abstractions.

39 When to use programmatic and declarative Programmatic transaction management is usually a good idea only if you have a small number of
transaction management ? transactional operations. On the other hand, if your application has numerous transactional
operations, declarative transaction management is usually worthwhile. It keeps transaction
management out of business logic, and is not difficult to configure.

40 What is Spring's jdbc template? Spring’s JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate
provides many convenience methods for doing things such as converting database data into
primitives or objects, executing prepared and callable statements, and providing custom database
error handling.

JdbcTemplate template = new JdbcTemplate(myDataSource);


S.No. Question Answer
SOA
1 What is SOA? SOA is a architecture for building business applications using loosely coupled services which act
like black boxes and can be orchestrated to achieve a specific functionality by linking them
together.
2 In SOA do we need to build systems from scratch? No. If you need to integrate or make an existing system as a business service, you just need to
create loosely coupled wrappers which will wrap your custom systems and expose the systems
functionality in generic fashion to the external world.

3 What is the difference between services and Services are logical grouping of components to achieve business functionality. Components are
components? implementation approaches to make a service. The components can be in JAVA, C#, C++ but the
services will be exposed in a general format like Web Services.

4 Are web-services SOA ? SOA is thinking. It’s an architectural concept and web service is one of the technical approach to
complete it. Web services are the preferred standards to achieve SOA.

• In SOA we need the services to be loosely coupled. A web service communicates using SOAP
protocol which is XML based which is very loosely coupled. It answers the what part of the service.

• SOA services should be able to describe themselves.WSDL describes how we can access the
service.
• SOA services are located in a directory.UDDI describes where we can get the web service. This
nothing but implementation of SOA registry.

5 What is a reusable service? It is an autonomous, reusable, discoverable, stateless functionality that has the necessary
granularity, and can be part of a composite application or a composite service.

A reusable service should be identified with a business activity described by the service
specifications (design-time contract).

A service’s constraints, including security, QoS, SLA, usage policies, may be defined by multiple
run-time contracts, multiple interfaces (the WSDL for a SOAP Web Service), and multiple
implementations (the code).

A reusable service should be governed at the enterprise level throughout its entire lifecycle, from
design-time through run-time. Its reuse should be promoted through a prescriptive process, and
that reuse should be measured.

6 How can you achieve loose coupling in a soa ? One strategy for achieving loose coupling is to use the service interface (the WSDL for a SOAP Web
Service) to limit this dependency, hiding the service implementation from the consumer. Loose
coupling can be addressed by encapsulating the service functionalities in a manner that limits the
impact of changes to the implementation on the service interface. However, at some point you will
need to change the interface and manage versioning without impacting service consumers, in
addition to managing multiple security constraints, multiple transports, and other considerations
7 What is ESB? Enterprise Service Bus (ESB) provides an infrastructure to implement this SOA concept.
Instead of going back again to point to point integration to implement SOA. ESBs facilitate
standards based integration but are not limited only to do a web services based integration e.g. the
messages are not required to use only http protocol for communication. A service consumer can
send his request using http protocol but the service provider provides data using JMS. The ESBs
make this communication possible. In general, they support message based transport and also
provide describe and discover facility for service provider and service consumer. Although WSDL is
used to describe the interfaces, UDDI based registries are not very common yet.

ESBs also provide mechanisms for security, mechanisms for implementing some level of
service level agreements (SLA), routing and transformation capabilities all of which vary to
some extend from Service to Service.

8 What are the common pitfalls of SOA ? One of the most common pitfalls is to view SOA as an end, rather than a means to an end.
Developers who focus on building an SOA solution rather than solving a specific business problem
are more likely to create complex, unmanageable, and unnecessary interconnections between IT
resources.

Another common pitfall is to try to solve multiple problems at once, rather than solving small pieces
of the problem. Taking a top-down approach—starting with major organization-wide infrastructure
investments—often fails either to show results in a relevant timeframe or to offer a compelling
return on investment.
S.No Question Answer
WEB SERVICES
1 What is a Webservice? Many people and companies have debated the exact definition of Web services. At a minimum,
however, a Web service is any piece of software that makes itself available over the Internet and
uses a standardized XML messaging system. 

2 Why are webservices needed? Provides interoperability between platforms, promotes code reuseability, allows for distributed
business applications, can be "firewall friendly" when using http transport protocol.

3 What are the types of web services? SOAP (Simple Object Access Protocol): a description of an xml messaging protocol

REST (Representational State Transfer): a description of an architecture for distributed hypermedia


systems
4 What are the differences between SOAP and REST? SOAP REST
● WSDL contract ● No contract
● WS-Security for SOAP plus SSL for HTTP. ● SSL for HTTP only.
● WS-Reliable Messaging for SOAP. ● No reliable messaging built-in.
● WS-Transactions (atomic) for SOAP. ● No transactions built-in.
● Tools required to implement the web service. ● No tools required.
● Greater information bandwidth due to SOAP ● Lower information bandwidth.
headers
● SOAP message within transport message. ● Raw XML or JSON within transport
message.

5 In what situations would you propose using SOAP Use SOAP for any situations requiring xml message encryption, reliable messaging in environments
or REST? with erratic connectivity, or atomic transactions because these functions are built-in.

Use REST whenever you need simple data manipulation of a resource such as that provided by the
http verbs GET, PUT, POST, and DELETE

6 What is the ultimate goal of using web services? Ultimately, the goal of web services is to achieve a SOA within the organization.

7 What are the two approaches to create a SOAP Top Down or Contract First: From WSDL one generates java classes.
based webservice? Bottom Up or Contract Last: From java classes one generates a WSDL

8 What is the webservice protocol stack? The Web service protocol stack is an evolving set of protocols used to define, discover, and
implement Web services. The core protocol stack consists of four layers: 

Service Transport: This layer is responsible for transporting messages between applications.
Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible
Exchange Protocol (BEEP). 

XML Messaging: This layer is responsible for encoding messages in a common XML format so that
messages can be understood at either end. Currently, this includes XML-RPC and SOAP. 

Service Description: This layer is responsible for describing the public interface to a specific Web
service. Currently, service description is handled via the WSDL. 

Service Discovery: This layer is responsible for centralizing services into a common registry, and
providing easy publish/find functionality. Currently, service discovery is handled via the UDDI. 

9 Is SOAP stateful or stateless protocol? Stateless.

10 What is an XML schema, how does it differ from a A schema describes an XML markup language. Specifically it defines which elements and attributes
DTD? are used in a markup language, how they are ordered and nested, and what their data types are. To
address limitation of DTDs, the W3C which manages the fundamental XML standards, created a
new way to describe markup languages called XML Schema. DTDs have done an adequate job of
telling us how elements and attributes are organized in a markup language, but they fail to address
data typing. While constraints provided by DTDs are useful for validating XML instances, the
probability that an XML instance will have a valid organization but invalid data is pretty high.
DTDs have a very weak typing system that restricts elements to four broad types of data: EMPTY,
ANY, element content or mixed element and text content. DTD don’t support types like integer,
decimal, boolean and enumeration. XML Schema, by contrast, provides a much stronger type
system which includes simple primitives (integer, double, boolean etc) as well as facilities for more
complex types. XML schema facilitates type inheritance, which allows simple or complex types to be
extended or restricted to create new types. In addition, X ML schema supports the use of XML
namespaces to create compound documents composed of multiple markup languages.
11 What is the difference between complex types and Complex types describe how elements are organized and nested. Simple types are the primitive data
simple types in XML schemas? types contained by elements and attributes. Simple types resemble Java primitive types in that
both are atomic; they cannot be broken down into constituent parts. It will only contain data. The
XML schema specification defines many standard simple types (string, integer, float etc). Whereas a
Complex Type is analogous to a Java class definition with fields but no methods.

12 What is an XML namespace? An XML namespace provides a qualified name for an XML element or attribute, the same way that a
Java package provides a qualified name for a Java class. Java package names allow us to separate
Java classes into distinct namespaces, which improves organization and access control, and helps
us avoid name conflicts. XML namespaces are similar to Java packages, and serve the same
purposes; an X ML namespace provides a kind of package name for individual elements and
attributes.

13 What is SOAP? SOAP 1.1 is simply a distributed object protocol like DCOM and CORBA IIOP. SOAP 1.1 is the
standard messaging protocol used by J2EE Web Services, and is the de facto standard for Web
services in general. SOAP’s primary application is Application to Application communication. SOAP
has a clear purpose: exchanging data over networks. The most significant difference between SOAP
1.1 and other distributed object protocols is that SOAP is based on XML. EJB 2.1 and J2EE 1.4 are
standardized on SOAP 1.1. SOAP is defined by its own XML Schema and relies heavily on the use of
XML Namespaces. Every SOAP message that is sent across the wire is an XML document that
consists of standard SOAP elements and application data. The use of namespaces differentiates the
standard SOAP elements from the application data. Specifically, its used in B2B and EAI: Both
focus on integration software applications and sharing data. To be truly effective in B2B and EAI, a
protocol must be platform independent, flexible and based on standard technologies.

14 Explain the basic structure of a SOAP 1.1 SOAP message is a kind of XML document. SOAP 1.1 has its own XML schema, namespaces and
message? processing rules. A SOAP 1.1 message is composed of the following elements:

<soap: Envelope> is the root of the SOAP message; all other elements are contained by it. It
contains two different children: the Header element and the Body element.

<soap: Header> element is generally used for carrying infrastructure data such as security tokens,
transaction IDs, routing information, and so on. Header element is optional.

<soap: Body> element carries the application specific data or a fault message. Application-specific
data is the information that we want to exchange with a web service.

15 What are the different SOAP messaging modes? Although SOAP supports four modes of messaging (RPC/Literal, Document/Literal, RPC/Encoded
and Document/Encoded) the Webservice Base Profile permits the use of RPC/Literal or
Document/Literal only. The RPC/Encoded and Document/Encoded modes are explicitly prohibited.
A messaging mode is defined by its messaging style (RPC or Document) and its encoding style. The
term “Literal” means that the XML document fragment can be validated against its XML schema.

16 What is Document/Literal mode? In this mode of messaging, a SOAP Body element contains an XML document fragment, a well-
formed XML element that contains arbitrary application data that belongs to an XML schema and
namespace.

17 What is RPC/Literal mode? This mode of messaging enables SOAP messages to model calls to procedures or method calls with
parameters and return values. In RPC/Literal messaging, the contents of the Body are always
formatted as a struct. An RPC request message contains the method name and the input
parameters of the call. An RPC response contains the return value and any output parameters. In
many cases, RPC/Literal messaging is used to expose traditional, components as Webservices.

18 What are the different Messaging Exchange One-Way and Request/Response.


Patterns?

19 SOAP messages are delivered using which protocol? HTTP. Its possible to deliver SOAP messages using other protocols, such as SMTP and FTP as well,
but details of these non-HTTP bindings are not specified by SOAP and are not supported by the
Webservices Basic Profile.

20 Are SOAP messages delivered using HTTP POST or HTTP requests are typified by the messages that your browser sends to a Web server to request a
HTTP GET? Web page or submit a form. A request for a Web page is usually made in an HTTP GET message,
while submission of a form is done with an HTTP POST message. While HTTP GET request is
perfectly suited for request Web pages, it doesn’t have a payload area and therefore cannot be used
to carry SOAP messages.

21 What is WSDL? WSDL 1.1(Web Service Description Language) is an XML markup language used to describe a
WebService. WSDL is used to specify the exact message format, Internet protocol, and address that
a client must use to communicate with a particular Webservice.
22 Can you explain the basic structure of WSDL? A WSDL document is an XML document that adheres to the WSDL XML schema. As an X ML
document instance, a WSDL document must use the correct elements in the correct fashion if it is
to be valid and well formed. A WSDL document contains seven important elements: types, import,
message, portType, operations, binding and service which are nested in the definitions element, the
root element of a WSDL document.

23 What is UDDI? UDDI (Universal Description, Discovery and Integration) is a specification for creating a registry
service that catalogs organizations (corporations) and their Webservices. You can access the data in
a UDDI directory using SOAP, which makes a UDDI registry a Webservice. The UDDI specification
describes about thirty different SOAP operations that allow you to add, update, delete and find
information contained in a UDDI registry.

24 What is SAAJ? SOAP with Attachments API for Java (SAAJ) is an API for manipulating the structure of a SOAP
message. SAAJ is an API you can use to create, read or modify SOAP messages using Java. SAAJ
provides a number of interfaces you can use to construct a simple SOAP document. SAAJ is based
on the Abstract Factory Pattern. Message Handlers in JAX-RPC use SAAJ to represent SOAP
message.

25 Which API is used to implement web services?


· Java API for XML Web Services (JAX-WS)

The Java API for XML Web Services (JAX-WS) is the centerpiece of a newly architected API stack for
Web services, the so-called "integrated stack" that includes JAX-WS 2.0, JAXB 2.0, and SAAJ 1.3.

For historical reasons, in the previous Web services stack there was considerable overlap of data
binding functionality between JAX-RPC 1.x and JAXB 1.x APIs. This is because JAX-RPC 1.x
originally included basic data binding functionality. When JAXB 1.x emerged after JAX-RPC, and
as data binding functionality became more comprehensive with enhanced standards such as XML
Schema and Relax NG, the need to separate the Web services definition and data binding
components became clearer. The result is an easier-to-understand architecture for Web services
development. You can use the Java API for XML Web Services (JAX-WS) to build Web applications
and Web services, incorporating the newer XML-based Web Services functionality.

· Java API for XML-Based RPC (JAX-RPC)


You can use the Java API for XML-based RPC (JAX-RPC) to build Web applications and Web
services, incorporating XML-based RPC functionality according to the SOAP 1.1 specification.

· Java API for XML Restful Services (JAX-RS)


The Java programming language API that provides support in creating web services according to
the Representational State Transfer (REST) architectural style.

26 What is JAXB? Java API for XML Binding (JAXB) provides a convenient way to bind an XML schema to a
representation in Java code. This makes it easy for you to incorporate XML data and processing
functions in applications based on Java technology without having to know much about XML itself.

27 What is JAX-RPC? Java API for XML based RPC is basically Java RMI over SOAP. JAX-RPC is deigned as a Java API
for Webservices, so that J2EE applications can interoperate with non-Java applications. JAX-RPC
is the very soul of J2EE Webservices. It defines the standard programming model for both
Webservice clients and endpoints in J2EE. There are essentially two sides to the JAX-RPC model:
client-side and server-side. The client-side programming model allows you to access a remote
Webservice as if it were a local object, using methods that represent SOAP operations. The server-
side programming model allows you to develop Webservice endpoints as Java objects or EJBs,
which run on the J2EE platform.

28 What are the various ways of accessing a 1.     Asynchronous Call


webservice? The application can make a call to the Webservice and then continue to do whatever it wants to do.
When the service is ready it will notify the application.

The easiest and most powerful way to to implement an asynchronous call is using a delegate object.
A delegate object wraps up a callback function. The idea is to pass a method in the invocation of
the web method. When the web method has finished, it will call this callback function to process
the result.

2.     Synchronous Call


The application has to wait until it has completed.
S.No Question Answer
REST
1 What are REST and RESTful Web Services? REST represents REpresentational State Transfer; it is relatively new aspect of writing web api.

RESTFUL is referred for web services written by applying REST architectural concept are called
RESTful services, it focuses on system resources and how state of resource should be transported
over HTTP protocol to a different clients written in different language. In RESTFUL web service http
methods like GET, POST, PUT and DELETE can be used to perform CRUD operations.

2 Explain the architectural style for creating web api? The architectural style for creating web api are
•HTTP for client server communication
•XML/JSON as formatting language
•Simple URI as the address for the services
•Stateless communication

3 What are the HTTP methods supported by REST? HTTP methods supported by REST are:
•GET: It requests a resource at the request URL. It should not contain a request body as it will be
discarded. May be it can be cached locally or on the server.
•POST: It submits information to the service for processing; it should typically return the modified
or new resource
•PUT: At the request URL it update the resource
•DELETE: At the request URL it removes the resource
•OPTIONS: It indicates which techniques are supported
•HEAD: About the request URL it returns meta information

4 What are resources in a REST architecture? Resources are identified by logical URLs; it is the key element of a RESTful design. Unlike, SOAP
web services in REST, you view the product data as a resource and this resource should contain all
the required information.

5 Mention some key characteristics of REST? Some key characteristics of REST includes
•REST is stateless, so there is no storage of session data on the client
•With a well applied REST API, the server could be restarted between two calls as every data is
passed to the server
•Web service mostly uses POST method to make operations, whereas REST uses GET to access
resources

6 Explain how JAXB related to RESTful web api? JAXB stands for Java API for Xml Binding. This framework is used to bind XML or JSON to Java
objects without the need for creating XML or JSON parsers.

7 What is the difference between PUT and POST? “PUT”puts a file or resource at a particular URI and exactly at that URI. If there is already a file or
resource at that URI, PUT changes that file or resource. If there is no resource or file there, PUT
makes one

POST sends data to a particular URI and expects the resource at that URI to deal with the request.
The web server at this point can decide what to do with the data in the context of specified resource

8 Which markup language can be used in RESTful JSON and XML are the two markup language that can be used in Restful web api
API?

10 List out the tools or API for developing or testing Testing tools for web services for REST APIs includes
web api? •Spring REST
•Jersey (Oracle)
•CXF (Apache)
•Restlet
•REST Easy (JBOSS)
12 Which protocol is used by RESTful webservices? RESTful web services make use of HTTP protocol as a medium of communication between client
and server.

13 What is messaging in RESTful webservices? A client sends a message in form of a HTTP Request and server responds in form of a HTTP
Response. This technique is termed as Messaging. These messages contain message data and
metadata i.e. information about message itself.

14 What are the core components of a HTTP Request? A HTTP Request has five major parts −
Verb − Indicate HTTP methods such as GET, POST, DELETE, PUT etc.
URI − Uniform Resource Identifier (URI) to identify the resource on server.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Request Header − Contains metadata for the HTTP Request message as key-value pairs. For
example, client ( or browser) type, format supported by client, format of message body, cache
settings etc.
Request Body − Message content or Resource representation.

15 What are the core components of a HTTP response? A HTTP Response has four major parts −
Status/Response Code − Indicate Server status for the requested resource. For example 404
means resource not found and 200 means response is ok.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Response Header − Contains metadata for the HTTP Response message as key-value pairs. For
example, content length, content type, response date, server type etc.
Response Body − Response message content or Resource representation.

16 What is URI? URI stands for Uniform Resource Identifier. Each resource in REST architecture is identified by its
URI. Purpose of an URI is to locate a resource(s) on the server hosting the web service. A URI is of
following format −
<protocol>://<service-name>/<ResourceType>/<ResourceID>

17 What is statelessness in RESTful Webservices? As per REST architecture, a RESTful web service should not keep a client state on server. This
restriction is called statelessness. It is responsibility of the client to pass its context to server and
then server can store this context to process client's further request. For example, session
maintained by server is identified by session identifier passed by the client.

18 What is the purpose of HTTP Status Code? HTTP Status code are standard codes and refers to predefined status of task done at server. For
example, HTTP Status 404 states that requested resource is not present on server.

19 What HTTP Status Code 200 states? It means, OK, shows success.
20 What HTTP Status Code 201 states? It means, CREATED, when a resource is successful created using POST or PUT request. Return
link to newly created resource using location header.
21 What HTTP Status Code 204 states? It means, NO CONTENT, when response body is empty for example, a DELETE request.

22 What HTTP Status Code 400 states? It means, BAD REQUEST, states that invalid input is provided e.g. validation error, missing data.

23 What HTTP Status Code 403 states? It means, FORBIDDEN, states that user is not having access to method being used for example,
delete access without admin rights.
24 What HTTP Status Code 404 states? It means, NOT FOUND, states that method is not available.
25 What HTTP Status Code 500 states? It means, INTERNAL SERVER ERROR, states that server has thrown some exception while
executing the method.
26 What are the best practices to be followed while As RESTful web services work with HTTP URLs Paths so it is very important to safeguard a RESTful
designing a secure RESTful web service? web service in the same manner as a website is be secured. Following are the best practices to be
followed while designing a RESTful web service −
Validation − Validate all inputs on the server. Protect your server against SQL or NoSQL injection
attacks.
Session based authentication − Use session based authentication to authenticate a user
whenever a request is made to a Web Service method.
No sensitive data in URL − Never use username, password or session token in URL , these values
should be passed to Web Service via POST method.
Restriction on Method execution − Allow restricted use of methods like GET, POST, DELETE.
GET method should not be able to delete data.
Validate Malformed XML/JSON − Check for well formed input passed to a web service method.
Throw generic Error Messages − A web service method should use HTTP error messages like 403
to show access forbidden etc.
S.No Question Answer
CLIENT-SIDE TECHNOLOGIES
1 What is JavaScript? JavaScript is a client-side scripting language that can be inserted into HTML pages and is
understood by web browsers.
2 What are the JavaScript data types? Number, String, Boolean, Function, Object, Null, Undefined
3 What is the use of isNaN function? isNan function returns true if the argument is not a number otherwise it is false.
4 What is negative infinity? Negative Infinity is a number in JavaScript which can be derived by dividing negative number by
zero.
5 What are undeclared and undefined variables? Undeclared variables are those that do not exist in a program and are not declared. If the program
tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value.
If the program tries to read the value of an undefined variable, an undefined value is returned.

6 How can you add new elements dynamically? Using functions like document.createElement( ) and specifying a DOM tag. You can also use
appendChild( ) on that element to add a Node beneath your newly created element.

7 What are global variables? How are these variable Global variables are those that are available throughout the length of the code, that is, these have
declared and what are the problems associated no scope. The var keyword is used to declare a local variable or object. If the var keyword is
with using them? omitted, a global variable is declared.
The problems that are faced by using global variables are the clash of variable names of local and
global scope. Also, it is difficult to debug and test the code that relies on global variables.

8 Explain the working of timers in JavaScript? Also Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval
discuss the drawbacks of using the timer, if any? of time. This is done by using the functions setTimeout, setInterval and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a particular function
after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute
the given function in the mentioned delay and only halts when cancelled. The clearInterval(id)
function instructs the timer to stop.

Timers are operated within a single thread, and thus events might queue up, waiting to be
executed.

9 What is === operator? “==” checks only for equality in value whereas “===” is a stricter equality test and returns false if
either the value or the type of the two variables are different.
10 Explain how can you submit a form using To submit a form using JavaScript use document.getElementById("myform").submit();
JavaScript?
11 What is an undefined value in JavaScript? Undefined value means the
•Variable used in the code doesn’t exist
•Variable is not assigned to any value
•Property doesn’t exist

12 What are some common JavaScript events? onchange, onclick, onmouseover, onmouseout, onkeydown, onload

13 What is jQuery? jQuery is not a programming language but a well written JavaScript code. It is a JavaScript code,
which do document traversing, event handling, Ajax interactions and Animations.

14 What are the methods used to provide effects? Some of the effects methods are:
Show( )
Hide( )
Toggle( )
FadeIn( )
FadeOut( )

15 In what scenarios jQuery can be used? jQuery can be used in following scenarios: Apply CSS static or dynamic, Calling functions on
events, Manipulation purpose, Mainly for Animation effects

16 What are the basic selectors in jQuery? Following are the basic selectors in jQuery: Element ID, CSS Name, Tag Name, DOM hierarchy

17 Can we add more than one ‘document.ready’ Yes, we can add more than one document.ready function in a page. But, body.onload can be added
function in a page? once in a page.

18 What are the four parameters used for jQuery.ajax •URL – Need to specify the URL to send the request
method? •type – Specifies type of request(Get or Post)
•data – Specifies data to be sent to server
•Cache – Whether the browser should cache the requested page
19 What is Ajax? Ajax is abbreviated as Asynchronous Javascript and XML. It is new technique used to create better,
faster and more interactive web systems or applications. Ajax uses asynchronous data transfer
between the Browser and the web server. This technique is used to make internet faster and user
friendly. The core object of Ajax is the XMLHttpRequest object--used for tranferring data between
client and server.

20 What are the advantages of Ajax? •Bandwidth utilization – It saves memory when the data is fetched from the same page.
•More interactive
•Speeder retrieval of data

21 What are the disadvantages of Ajax? 1.AJAX is dependent on Javascript. If there is some Javascript problem with the browser or in the
OS, Ajax will not support
2.Ajax can be problematic in Search engines as it uses Javascript for most of its parts.
3.Source code written in AJAX is easily human readable. There will be some security issues in Ajax.
4. Debugging is difficult
5. Increases size of the requests
6. Slow and unreliable network connection.
7.Problem with browser back button when using AJAX enabled pages.

22 How many types of triggers are present in update There are two types of triggers used in update panel:
panel? •PostBackTrigger – This works as full postback and it cannot work asynchronously
•AsyncPostBackTrigger – Partial post back asynchronously

23 What are all the controls of Ajax? •ScriptManager


•ScriptManagerProxy
•UpdatePanel
•UpdateProgress
•Timer

24 What is update panel? Update panel is a server control used to update the specified portion of a web page. Script Manager
needs to be used whenever update panel is used. Using update panel, user cannot handle outside
controls.

25 What are all the technologies used by Ajax? •JavaScript


•XMLHttpRequest
•Document Object Model (DOM)
•Extensible HTML (XHTML)
•Cascading Style Sheets (CSS)

26 What is JSON in Ajax? JSON is abbreviated as JavaScript Object Notation. JSON is a safe and reliable data interchange
format in JavaScript, which is easy to understand for both users and machines.

27 What is AngularJS? AngularJS is a javascript framework used for creating single web page applications. It allows you
to use HTML as your template language and enables you to extend HTML’s syntax to express your
application’s components clearly

28 What is scope in AngularJS? Scope refers to the application model, it acts like glue between application controller and the view.
Scopes are arranged in hierarchical structure and impersonate the DOM ( Document Object Model)
structure of the application. It can watch expressions and propagate events.

29 What are directives? Mention some of the most A directive is something that introduces new syntax, they are like markers on DOM element which
commonly used directives in AngularJS attaches a special behavior to it. In any AngularJS application, directives are the most important
application. components. Some of the commonly used directives are ng-model, ng-app, ng-bind, ng-repeat , ng-
show etc

30 What are the advantages of using AngularJS AngularJS has several advantages in web development.
•AngularJS supports MVC pattern
•Can do two ways data binding using AngularJS
•It has per-defined form validations
•It supports both client server communication
•It supports animations

31 What is injector? An injector is a service locator. It is used to retrieve object instances as defined by provider,
instantiate types, invoke methods and load modules. There is a single injector per Angular
application, it helps to look up an object instance by its name.

32 What is the difference between link and compile in •Compile function: It is used for template DOM Manipulation and collect all of the directives.
Angular.js? •Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is
executed once the template has been cloned.
33 What are the styling form that ngModel adds to ngModel adds these CSS classes to allow styling of form as well as control
CSS classes ? •ng- valid
•ng- invalid
•ng-pristine
•ng-dirty

34 Explain what is DI (Dependency Injection ) and how DI or Dependency Injection is a software design pattern that deals with how code gets hold of its
an object or function can get a hold of its dependencies. In order to retrieve elements of the application which is required to be configured
dependencies? when module gets loaded , the operation “config” uses dependency injection.

These are the ways that object uses to hold of its dependencies
•Typically using the new operator, dependency can be created
•By referring to a global variable, dependency can be looked up
•Dependency can be passed into where it is required

35 What is the difference between AngularJS and AngularJS combines the functionalities of most of the 3rd party libraries, it supports individual
backbone.js? functionalities required to develop HTML5 Apps. While Backbone.js do their jobs individually.
S.No Question Answer
MAVEN
1 What is Maven? Maven is a project management and comprehension tool. Maven provides developers a complete
build lifecycle framework. Development team can automate the project's build infrastructure in
almost no time as Maven uses a standard directory layout and a default build lifecycle.

2 What is the POM? POM stands for Project Object Model. It is fundamental Unit of Work in Maven. It is an XML file. It
always resides in the base directory of the project as pom.xml. It contains information about the
project and various configuration details used by Maven to build the project(s). POM contains the
some of the following configuration information − project dependencies, plugins, goals, build
profiles, project version, developers, mailing list

3 What are the elements of a project's coordinates? <groupId>:<artifactId>:<version>

4 What are the different Maven build lifecycles? default (aka build), clean, site

5 What are the phases of the default lifecycle? validate, compile, test, package, integration-test, verify, install, deploy

6 What would the command mvn clean do? This command removes the target directory with all the build data before starting the build process.

7 What is a goal? A goal represents a specific task which contributes to the building and managing of a project. It
may be bound to zero or more build phases. A goal not bound to any build phase could be executed
outside of the build lifecycle by direct invocation.

8 What is an archetype? Archetype is a Maven plugin whose task is to create a project structure as per its template.

9 What is a dependency? A dependency is an artifact that Maven will include as part of the build. This is analogous to
including JAR files in your classpath in an Eclipse build.

10 How do you perform a build with Maven? In command prompt: mvn [options] [<goal(s)>] [<phase(s)>]

11 What is a Maven repository? What are the local and A repository is a place i.e. directory where all the project jars, library jar, plugins or any other
central repositories? project specific artifacts are stored and can be used by Maven easily. Maven local repository is a
folder location on your machine. It gets created when you run any maven command for the first
time. Maven local repository keeps your project's all dependencies (library jars, plugin jars etc). It is
repository provided by Maven community. It contains a large number of commonly used libraries.
When Maven does not find any dependency in local repository, it starts searching in central
repository using following URL: http://repo1.maven.org/maven2/.

12 What is the default location of your local ~/.m2/repository. This can be changed by editing the conf/settings.xml file in the Maven directory
repository? and changing the value in the <localRepository> tag to a custom location.

13 How do you deploy a Web application using Maven? Using the appropriate Maven plugin, such as weblogic-maven-plugin or tomcat-maven-plugin. The
plugin information must be included in the POM file, and the server configurations must be
included in the execution tag (i.e. server URL, port, credentials, etc.). Then, simply execute the goal
associated with the plugin (i.e. mvn weblogic:deploy)

14 What is a SNAPSHOT? SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions,
Maven checks for a new SNAPSHOT version in a remote repository for every build.

15 How do you install a JAR file to your local mvn install:install-file -Dfile={Path/to/your/jar.jar} -DgroupId=com.example
repository? -DartifactId=artifact -Dversion=1.0.0 -Dpackaging=jar

16 What is the command to create a new project based mvn archetype:generate -DgroupId=[your project's group id] -DartifactId=[your project's artifact id] -
on an archetype? DarchetypeArtifactId=maven-archetype-archetype

17 What is the use of the execution element in the The <execution> element contains information's required for the execution of a plugin.
POM file?
18 In what order does Maven resolve dependencies? 1 − Search dependency in local repository, if not found, move to step 2 else if found then do the
further processing.

2 − Search dependency in central repository, if not found and remote repository is mentioned then
move to step 4 else if found, then it is downloaded to local repository for future reference.

3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws
error

4 − Search dependency in remote repository or repositories, if found then it is downloaded to local


repository for future reference
S.No Question Answer
JENKINS
1 What is Jenkins? Jenkins is an open source tool with plugin built for continuous integration purpose. The principle
functionality of Jenkins is to keep a track of version control system and to initiate and monitor a
build system if changes occur. It monitors the whole process and provides reports and notifications
to alert.

2 What is continous integration? In software development, when multiple developers or teams are working on different segments of
same web application, we need to perform integration test by integrating all modules. In order to
do that an automated process for each piece of code is performed on daily bases so that all your
code get tested.

3 What is the requirement for using Jenkins? To use Jenkins you require:
•A source code repository which is accessible, for instance, a Git repository
•A working build script, e.g., a Maven script, checked into the repository

4 What are the advantages of using Jenkins? Advantage of Jenkins include


•At integration stage, build failures are cached
•For each code commit changes an automatic build report notification generates
•To notify developers about build report success or failure, it is integrated with LDAP mail server
•Achieves continuous integration agile development and test driven development
•With simple steps, maven release project is automated
•Easy tracking of bugs at early stage in development environment than production

5 What are the commands you can use to start To start Jenkins manually, you can use either of the following:
Jenkins manually? •(Jenkins_url)/restart: Forces a restart without waiting for builds to complete
•(Jenkin_url)/safeRestart: Allows all running builds to complete
• java -jar jenkins.war --httpPort=9090

6 What are some of the useful plugins for Jenkins? Some of the important plugins in Jenkin includes
•Maven 2 project
•Amazon EC2
•HTML publisher
•Copy artifact
•Join
•Green Balls

7 How can you create a backup of files in your Jenkins saves all the setting, build artifacts and logs in its home directory, to create a back-up of
Jenkins server? your Jenkins setup, just copy this directory. You can also copy a job directory to clone or replicate
a job or rename the directory.

8 How do you create a Jenkins job? To create a project that is handled via jobs in Jenkins. Select New item from the menu, once this
done enter a name for the job and select free-style job. Then click OK to create new job in Jenkins.
The next page enables you to configure your job.

9 What is a build trigger? A build trigger tells Jenkins when to execute the job. Some build triggers include:
◦Start a build job once another build job has completed
◦Kick off builds at periodical intervals
◦Poll the SCM (Git, SVN, etc.) for changes

10 What is a pre-build and post-build step? What can Pre-build and post-build steps include executing Windows batch commands, executing top-level
you do in these steps? Maven targets, etc. before and after a job is started or completed.

11 What components are Jenkins usually integrated Jenkin is mainly integrated with two components
with? •Version Control system like GIT, SVN
•And build tools like Apache Maven.
S.No Question Answer
AMAZON WEB SERVICES
1 What is Amazon EC2 Service? EC2 uses Xen virtualization. Each virtual machine, called an “instance”. You can use Amazon EC2
to launch as many or as couple of virtual servers as you need, design security and networking, and
manage storage. Amazon EC2 empowers you to scale up or down to handle changes in
requirements.

2 What is the relation between EC2 Instance and We can launch different types of instances from a single AMI. An instance type essentially
AMI? determines the hardware of the host computer used for your instance. Each instance type offers
different compute and memory capabilities.

After we launch an instance, it looks like a traditional host, and we can interact with it as we would
any computer. We have complete control of our instances; we can use sudo to run commands that
require root privileges.

3 What is Amazon Machine Image (AMI)? An Amazon Machine Image (AMI) is a template that contains a software configuration (for example,
an operating system, an application server, and applications). From an AMI, we launch an instance,
which is a copy of the AMI running as a virtual server in the cloud. We can launch multiple
instances of an AMI.

5 Explain storage for Amazon EC2 instance. Amazon EC2 provides many data storage options for your instances. Each option has a unique
combination of performance and durability. These storage can be used independently or in
combination to suit your requirements. There are mainly four types of storage provided by AWS:

Amazon EBS
Amazon EC2 Instance Store
Amazon S3
Adding Storage

7 What is EBS? EBS is durable, block-level storage volumes that you can attach to a running Amazon EC2
instance. The Amazon EBS volume persists independently from the running life of an Amazon EC2
instance. After an EBS volume is attached to an instance, you can use it like any other physical
hard drive. Amazon EBS encryption feature supports encryption feature.

8 What is Amazon EC2 Instance Store? Storage disk that is attached to the host computer is referred to as instance store. Instance storage
provides temporary block-level storage for Amazon EC2 instances. The data on an instance store
volume persists only during the life of the associated Amazon EC2 instance; if you stop or
terminate an instance, any data on instance store volumes is lost.

6 What is Amazon S3 storage? Amazon S3 provides access to reliable and inexpensive data storage infrastructure. It is designed to
make web-scale computing easier by enabling you to store and retrieve any amount of data, at any
time, from within Amazon EC2 or anywhere on the web.

7 What is Route 53? Amazon Route 53 is a highly available and scalable cloud Domain Name System (DNS) web service.
It is designed to give developers and businesses an extremely reliable and cost effective way to route
end users to Internet applications by translating names like www.example.com into the numeric IP
addresses like 192.0.2.1 that computers use to connect to each other.

8 What is Amazon Elastic Load Balancing? Elastic Load Balancing automatically distributes incoming application traffic across multiple
Amazon EC2 instances in the cloud. It enables you to achieve greater levels of fault tolerance in
your applications, seamlessly providing the required amount of load balancing capacity needed to
distribute application traffic.

10 What are regions and availability zones? The AWS Cloud infrastructure is built around Regions and Availability Zones (“AZs”). A Region is a
physical location in the world where we have multiple Availability Zones. Availability Zones consist
of one or more discrete data centers, each with redundant power, networking and connectivity,
housed in separate facilities. These Availability Zones offer you the ability to operate production
applications and databases which are more highly available, fault tolerant and scalable than would
be possible from a single data center. The AWS Cloud operates 32 Availability Zones within 12
geographic Regions around the world.
11 What is a Key Pair? Explain how to create a key Amazon EC2 uses public–key cryptography to encrypt and decrypt login information. Public–key
pair. cryptography uses a public key to encrypt a piece of data, such as a password, then the recipient
uses the private key to decrypt the data. The public and private keys are known as a key pair.

To log in to your instance, you must create a key pair, specify the name of the key pair when you
launch the instance, and provide the private key when you connect to the instance. Linux instances
have no password, and you use a key pair to log in using SSH. With Windows instances, you use a
key pair to obtain the administrator password and then log in using RDP.

You can create a key pair using the Amazon EC2 console or the command line. After you create a
key pair, you can specify it when you launch your instance.

12 What is a security group in Amazon EC2? What are A security group acts as a virtual firewall that controls the traffic for one or more instances. When
the features of Security Group in Amazon EC2? you launch an instance, you associate one or more security groups with the instance. You add
rules to each security group that allow traffic to or from its associated instances. You can modify
the rules for a security group at any time; the new rules are automatically applied to all instances
that are associated with the security group. When we decide whether to allow traffic to reach an
instance, we evaluate all the rules from all the security groups that are associated with the
instance.

13 How to connect to your Amazon EC2 instance? You can connect to a Linux EC2 instance using SSH or Putty. You must specify a key pair and
ensure SSH traffic is enabled on the instance. You can connect to a Windows instance using
Microsoft Remote Desktop app. Be sure to enable inbound RDP traffic from your IP address to your
instance.

14 How are you charged in Amazon EC2? The AWS cloud computing model allows you to pay for services on-demand and to use as much or
as little at any given time as you need. While resources are active under your account, you pay for
the cost of allocating those resources and for any incidental usage associated with those resources,
such as data transfer or allocated storage. To keep your costs as low as possible, you should
release or terminate unused resources as soon as you are done with them.

15 Can I vertically scale an Amazon EC2 instance? Yes. This is an incredible feature of AWS and cloud virtualization. Spinup a new larger instance
How? than the one you are currently running. Pause that instance and detach the root EBS volume from
this server and discard. Then stop your live instance, detach its root volume. Note the unique
device ID and attach that root volume to your new server. And the start it again.

16 What is auto-scaling? How does it work? Autoscaling is a feature of AWS which allows you to configure and automatically provision and
spinup new instances without the need for your intervention. You do this by setting thresholds and
metrics to monitor. When those thresholds are crossed a new instance of your choosing will be
spun up, configured, and rolled into the load balancer pool. You can scaled horizontally without
any operator intervention.

17 What automation tools can I use to spinup servers? The most obvious way is to roll-your-own scripts, and use the AWS API tools. Such scripts could
be written in bash, perl or other language or your choice. Next option is to use a configuration
management and provisioning tool like puppet or better it's successor Opscode Chef. You might
also look towards a tool like Scalr. Lastly you can go with a managed solution such as Rightscale.

18 What is configuration management? Why would I Configuration management has been around for a long time in web operations and systems
want to use it with cloud provisioning of resources? administration. Yet the cultural popularity of it has been limited. Most systems administrators
configure machines as software was developed before version control - that is manually making
changes on servers. Each server can then and usually is slightly different. Troubleshooting though
is straightforward as you login to the box and operate on it directly. Configuration management
brings a large automation tool into the picture, managing servers like strings of a puppet. This
forces standardization, best practices, and reproducibility as all configs are versioned and
managed. It also introduces a new way of working which is the biggest hurdle to its adoption.

Enter the cloud, and configuration management becomes even more critical. That's because virtual
servers such as Amazons EC2 instances are much less reliable than physical ones. You absolutely
need a mechanism to rebuild them as-is at any moment. This pushes best practices like
automation, reproducibility and disaster recovery into center stage.
19 Explain how you would simulate perimeter security Traditional perimeter security that we're already familiar with using firewalls and so forth is not
using Amazon Web Services model. supported in the Amazon EC2 world. AWS supports security groups. One can create a security
group for a jump box with SSH access - only port 22 open. From there a webserver group and
database group are created. The webserver group allows 80 and 443 from the world, but port 22
*only* from the jump box group. Further the database group allows port 3306 from the webserver
group and port 22 from the jump box group. Add any machines to the webserver group and they
can all hit the database. No one from the world can, and no one can directly SSH to any of your
boxes. For further restriction, only allow SSH access from specific IP addresses on your network, or
allow just your subnet.

20 Explain Stopping, Starting, and Terminating an Stopping and Starting an instance: When an instance is stopped, the instance performs a normal
Amazon EC2 instance. shutdown and then transitions to a stopped state. All of its Amazon EBS volumes remain attached,
and you can start the instance again at a later time. You are not charged for additional instance
hours while the instance is in a stopped state.
Terminating an instance: When an instance is terminated, the instance performs a normal
shutdown, then the attached Amazon EBS volumes are deleted unless the volume’s
deleteOnTermination attribute is set to false. The instance itself is also deleted, and you can’t start
the instance again at a later time.

21 How does cloud computing provides on-demand Cloud computing is a metaphor used for internet. It provides on-demand access to virtualized IT
functionality? resources that can be shared by others or subscribed by you. It provides an easy way to provide
configurable resources by taking it from a shared pool. The pool consists of networks, servers,
storage, applications and services. Resources are partitioned on-demand in a multi-tenancy
architecture.

23 What is the difference between scalability and Scalability is a characteristic of cloud computing through which increasing workload can be
elasticity? handled by increasing in proportion the amount of resource capacity. It allows the architecture to
provide on demand resources if the requirement is being raised by the traffic. Whereas, elasticity is
being one of the characteristic provide the concept of commissioning and decommissioning of large
amount of resource capacity dynamically. It is measured by the speed by which the resources are
coming on demand and the usage of the resources.

24 What are the different layers of cloud computing? Cloud computing consists of 3 layers in the hierarchy: IaaS, PaaS, SaaS.

Infrastructure as a Service (IaaS) provides cloud infrastructure in terms of hardware like memory,
processor speed etc. 

Platform as a Service (PaaS) provides cloud application platform for the developers. 

Software as a Service (SaaS) provides cloud applications which are used by the user directly
without installing anything on the system. The application remains on the cloud and it can be
saved and edited in there only.

25 How to secure your data for transport in cloud? Cloud computing provides very good and easy to use feature to an organization, but at the same
time it brings lots of question that how secure is the data, which has to be transported from one
place to another in cloud. So, to make sure it remains secure when it moves from point A to point B
in cloud, check that there is no data leak with the encryption key implemented with the data you're
sending.

26 How do you use Amazon SQS? Amazon Simple Queue Service (SQS) is a fast, reliable, scalable, fully managed message queuing
service. SQS makes it simple and cost-effective to decouple the components of a cloud application.
You can use SQS to transmit any volume of data, at any level of throughput, without losing
messages or requiring other services to be always available.

With SQS, you can offload the administrative burden of operating and scaling a highly available
messaging cluster, while paying a low price for only what you use.

27 How buffer is used in Amazon Web Services? Buffer is used to make the system more resilient to burst of traffic or load by synchronizing
different component. The components always receive and process the requests in unbalanced way.
Buffer keeps the balance between different components and makes them work at the same speed to
provide faster services.

28 What are the Security Best Practices for Amazon There are several best practices for secure Amazon EC2: Use AWS Identity and Access Management
EC2? (IAM) to control access to your AWS resources.
Restrict access by only allowing trusted hosts or networks to access ports on your instance.
Review the rules in your security groups regularly, and ensure that you apply the principle of least
Privilege — only open up permissions that you require.
Disable password-based logins for instances launched from your AMI. Passwords can be found or
cracked, and are a security risk.
S.No Question Answer
CHEF
1 What is configuration management? What are the Configuration management covers a set of practices for managing hardware, software, and
benefits of configuration management? infrastructure. Configuration management ensures consistent environments when managing large
infrastructures in teams of multiple system administrators. Configuration management provides
systematic and autonomous approaches to managing infrastructure.

2 What is Chef? Chef is an automation platform that configures and manages your infrastructure whether it is on-
premises or in the cloud. You can deploy to the infrastructure type that makes the most sense for
your business. You can use Chef to speed up application deployment, even creating a continual
deployment pipeline. The key to Chef’s power is that it turns infrastructure into code.

Infrastructure as code means that your computing environment has some of the same attributes as
your application:

◦ Your infrastructure is versionable.


◦ Your infrastructure is repeatable.
◦ Your infrastructure is testable.

3 What is a recipe? A recipe is a collection of resources that describes a particular configuration or policy. A recipe
describes everything that is required to configure part of a system. Recipes do things, such as
install and configure software components, manage files, deploy applications, and execute other
recipes.

4 What is a resource? A resource represents a piece of infrastructure and its desired state, such as a package that should
be installed, a service that should be running, or a file that should be generated.

5 What is a cookbook? How is it different from a A recipe is a collection of resources, and typically configures a software package or some piece of
recipe? infrastructure. A cookbook groups together recipes and other information in a way that is more
manageable than having just recipes alone.

6 What is the difference between chef-client and chef- chef-apply applies a single recipe; chef-client applies a cookbook.
apply commands?

7 What is a Chef server? What are the ways to setup The Chef server acts as a hub for configuration data. The Chef server stores cookbooks, the policies
a Chef server? that are applied to nodes, and metadata that describes each registered node that is being managed
by the chef-client. Nodes use the chef-client to ask the Chef server for configuration details, such as
recipes, templates, and file distributions. You can install an instance on your own infrastructure or
use hosted Chef

8 What is the purpose of the Chef Starter Kit? The Starter Kit provides certificates and other files that enable you to securely communicate with
the Chef server.

9 What is a node? A node represents a server and is typically a virtual machine, container instance,
or physical server – basically any compute resource in your infrastructure that's managed by Chef.

10 How can you bootstrap a node? knife bootstrap (<ip_address>) (options…)

11 What is the knife command? Knife command enables you to communicate with the Chef server (i.e. bootstrapping nodes,
uploading cookbooks, etc)

12 What is a run-list? The run-list lets you specify which recipes to run, and the order in which to run them. The run-list
is important for when you have multiple cookbooks, and the order in which they run matters.

13 What information do you need in order to bootstrap You need your node's host name or public IP address and a user name and password you can log
a node? on to your node with. Alternatively, you can use key-based authentication instead of providing a
user name and password.

14 What happens during the bootstrap process? During the bootstrap process, the node downloads and installs chef-client,
registers itself with the Chef server, and does an initial checkin. During this checkin, the node
applies any cookbooks that are part of its run-list.
15 How can you check if the bootstrap process was ◦ The Chef management console
successful? ◦ knife node list
◦ knife node show

16 How do you apply an updated cookbook to your First, update the cookbook using
node? ◦ knife cookbook upload (<cookbook>)
Then, you can either:
◦ Run knife ssh from your workstation.
◦ SSH directly into your server and run chef-client.

17 What is the Chef Supermarket? You can get reusable cookbooks that are written and maintained by the Chef community from the
Chef Supermarket at https://supermarket.chef.io.
S.No Question Answer
UNIX
1 What is an SH file? Files with the .sh extension are UNIX shell script files. This allows you to execute a chain of UNIX
commands as a single unit of work in a convenient and repeatable way.

2 What is SSH? ssh (SSH client) is a program for logging into a remote machine and for executing commands on a
remote machine. It is intended to replace rlogin and rsh, and provide secure encrypted
communications between two untrusted hosts over an insecure network.

3 How do you know what directory you are in? Using the pwd command will print the working directory.

4 How do you list all the files in a directory? The ls command prints files and subdirectories in the current folder. Expose hidden files with the -
a option.

5 How do you edit a file in UNIX? You can use the cat command or open the file with a text editor, such as vi or nano.

6 What is the cat command? The cat command reads one or more files and prints them to standard output. The operator > can
be used to combine multiple files into one. The operator >> can be used to append to an existing
file.

7 How would you change directories? Using the cd command and specifying the desired location.

8 What is echo used for? Echo prints a string value to the standard console output. You can pipe output from another
command into echo, print a variable's value, and more.

9 What is telnet? The telnet command allows you to communicate to another host using the TELNET protocol. telnet
[host [port]]

10 What is the difference between find and grep? "find" is a file locator while "grep" searches for patterns within a file.

11 What does grep do? The grep command is used to search text or searches the given file for lines
containing a match to the given strings, words, or regular expression. By default, grep displays the
matching lines.
12 What does chmod command do? In Unix operating systems, chmod is the command that can change the access permissions to files
and directories. The syntax is: chmod (options) (permissions) (filename). The permissions list
includes permissions for user, group, and other. You can use rwx (read, write, execute) notation or
0-7 digits to represent the permissions

13 If you have a variable called 'name', how would you You can prepend the $ character to the beginning of the variable name, in this case $name will
reference that? retrieve the environment variable's value. You can change and set variable values using key=value
syntax.

14 What is the diff command? diff analyzes two files and prints the lines that are different. Essentially, it outputs a set of
instructions for how to change one file in order to make it identical to the second file.
It does not actually change the files; however, it can optionally generate a script (with the -e option)
for the program ed (or ex which can be used to apply the changes. For example: diff file1.txt file2.txt

15 How would you monitor a log file? SSH on to your server then type:
tail -f /var/log/httpd/access_log
The above command will show you the last few lines of the log file. The -f option will print to your
console any new lines added to the log file in realtime. So you can get a live view of additions to the
log file.

16 What is sudo? Sudo stands for either "substitute user do" or "super user do". Sudo allows a user to run a program
as another user (most often the root user) to achieve "best practice security" on Linux. Sudo access
is temporary, and lasts only on a per-command basis.

17 What is root? root is the user name or account that by default has access to all commands and files on a Linux or
other Unix-like operating system. It is also referred to as the root account, root user and the
superuser.
18 What is RPM, yum, and apt? Red Hat Package Manager (RPM) is the package management system used for packaging in the
Linux Standard Base (LSB). RPM is used for querying and verifying packages, and installing,
upgrading, and removing packages.

Yellowdog Updater Modified (YUM) adds automatic updates and package management, including
dependency management, to RPM systems. YUM works with repositories, which are collections of
packages, typically accessible over a network connection.

Advanced Package Tool (Apt) is the package management system used by Debian and distributions
derived from Debian, such as Ubuntu.

16 Explain how to create a new user. useradd [options] username. Options include user id (must be > 999), home directory, login shell,
days until account or password expires, and comment (typically used to specify the user's full
name).

19 What is the kill command? Use the kill command to send a signal to each process specified by a pid (process identifier). The
default signal is SIGTERM (terminate the process). For example: kill PID or kill -s signalName PID
S.No Question Answer
TESTING
1 What is the difference between black box and white Internal system design is not considered in black box testing. Tests are based on requirements and
box testing? functionality. White box testing (aka glass box) is based on knowledge of the internal logic of an
application’s code. Internal software and code working should be known for this type of testing.
Tests are based on coverage of code statements, branches, paths, conditions.

2 What is unit testing? Testing of individual software components, modules, and methods. Typically done by the
programmer and not by testers, as it requires detailed knowledge of the internal program design
and code. May require developing test driver modules, stubs, or test harnesses.

3 What is integration testing? Testing of integrated modules to verify combined functionality after integration. Modules are
typically code modules, individual applications, client and server applications on a network, etc.
This type of testing is especially relevant to client/server and distributed systems.

4 What is functional testing? This type of testing ignores the internal parts and focus on the output is as per requirement or not.
Black-box type testing geared to functional requirements of an application.

5 What is system testing? Entire system is tested as per the requirements. Black-box type testing that is based on overall
requirements specifications, covers all combined parts of a system.
6 What is regression testing? Testing the application as a whole after the modification in any module or functionality to ensure
new modules do not break old modules. Difficult to cover all the system in regression testing so
typically automation tools are used for these testing types.

7 What is the difference between performance, load, Performance testing is used to check whether system meets performance requirements under
and stress testing? normal conditions. Load testing is used to check system behavior under heavy loads, such as
testing of a web site under a range of loads and incrementally ramping up requests to determine at
what point the system’s response time degrades or fails. In stress testing, the system is stressed
beyond its specifications typically in spikes to check how and when it fails.

8 What is acceptance testing? Normally this type of testing is done to verify if system meets the customer specified requirements.
User or customer do this testing to determine whether to accept application.

9 What is the difference between alpha testing and Alpha testing is a type of acceptance testing; performed to identify all possible issues/bugs before
beta testing? releasing the product to everyday users or public. The focus of this testing is to simulate real users
by using blackbox and whitebox techniques. The aim is to carry out the tasks that a typical user
might perform. Alpha testing is carried out in a lab environment and usually the testers are
internal employees of the organization.

Beta Testing of a product is performed by "real users" of the software application in a "real
environment" and can be considered as a form of external user acceptance testing. Beta version of
the software is released to a limited number of end-users of the product to obtain feedback on the
product quality. Beta testing reduces product failure risks and provides increased quality of the
product through customer validation. It is the final test before shipping a product to the customers.
10 What is usability testing? User-friendliness check. Application flow is tested, Can new user understand the application easily,
Proper help documented whenever user stuck at any point. Basically system navigation is checked
in this testing.

11 List the annotations in JUnit 4. BeforeClass, Before, Test, After, AfterClass, Ignore, Suite, RunWith

12 In what order are annotated methods executed? BeforeClass > Before > Test > After > AfterClass

13 How many times are the Before and After methods Once for each method annotated as Test. Used for setup and teardown for each test case scenario.
executed?

14 Name some of the methods available in the Assert assertArrayEquals, assertEquals, assertNotEquals, assertTrue, assertFalse, assertSame,
class. assertNotSame, assertNull, assertNotNull, assertThat, fail

15 What is test-driven development (TDD)? Test-driven development (TDD) is an evolutionary approach to development which combines test-
first development. In TDD, you write a failing unit test before you write just enough production
code to fulfill that test and then refactor.

16 What is behavior-driven development (BDD)? Similar to TDD, behavior-driven development uses a test-first develop later approach. The approach
starts by writing a failing acceptance test, typically in a plain text / business and domain readable
file. Then, developers write a failing unit test in a programming language, known as a step
implementation. Then, as in TDD, you write just enough production code to fulfill that test and
then refactor.

17 What is Cucumber? Cucumber is a BDD framework that uses Gherkin as its domain-readable language and supports
step implementations in a variety of languages, including Java and Ruby.

18 What is Gherkin? Gherkin is a Business Readable, Domain Specific Language created especially for behavior
descriptions. Gherkin serves two purposes: serving as your project’s documentation and automated
tests. The Gherkin file describes the feature, scenarios, and scenario steps for the test. It can also
contain test data examples and background data for preconditions. Gherkin supports over 60
spoken languages.

19 What is feature file in Cucumber? What does Feature file in Cucumber is written in Gherkin and consists of parameters or conditions required
feature file consist of? for executing code. They are: Feature, Scenario, Scenario Outline, Given, When, Then, etc.

20 What is step definition in Cucumber? A step definition is a method definition in a programming language that is tagged with a regular
expression that matches a step in the Gherkin feature file. When Cucumber executes the plain text,
it will (for each step) look for a registered Step Definition with a matching Regexp. If it finds one,
Cucumber will execute the method, passing all groups from the Regexp match as arguments to the
method.

21 Explain Given, When, Then. Gherkin follows a standard series of steps: Given > When > Then. GIVEN is a set of preconditions,
WHEN is the action(s) taken by the user, and THEN is the expected outcome.
22 What is the difference between Scenario and Scenario is one of the core Gherkin structures. Every scenario starts with the Scenario: keyword (or
Scenario Outline? localized one), followed by an optional scenario title. Each feature can have one or more scenarios,
and every scenario consists of one or more steps (given, when, then). Scenario Outlines allow us to
more concisely express these examples through the use of a template with placeholders instead of
copying and pasting scenarios to use different values which can quickly become tedious and
repetitive. Scenario Outline must be followed by Examples.

23 What is the difference between Examples and data Tables are arguments to steps, and they are handy for specifying a larger data set - usually as
tables? input to a Given or as expected output from a Then. While syntactically they are identical to tables
in Examples, they have a different purpose. With Examples, the value substituted for the
placeholder changes with each subsequent run of the Scenario Outline, until the end of the
Examples table is reached.

24 What is Background? Backgrounds allows you to add some context to all scenarios in a single feature. A Background is
like an untitled Scenario, containing a number of steps. The difference is when it is run: the
Background is run before each of your Scenarios.

25 What are the difference between JBehave and Although Cucumber and Jbehave are meant for the same purpose, acceptance tests are completely
Cucumber? different frameworks
•Jbehave is Java based and Cucumber is Ruby based
•Jbehave are based on stories while Cucumber is based on features

26 What are the two required files to execute a Gherkin feature file and Step definitions in Java or Ruby
Cucumber test scenario?

27 How do you allow dynamic test data in a feature In your Gherkin feature file, you can designate a dummy value in the Examples table or DataTable.
file? In your step implementation, you can check for this dummy value and replace it with dynamic data
from some other source.

28 What is the DataTable object in Cucumber JVM? DataTable is the object used to receive arguments from Gherkin tables and examples. You can
create a POJO that represents the data and can cast DataTable into a List or Map of your POJO
type. This allows you to quickly translate Gherkin tables and examples into a collection of objects.

29 What is Selenium? Selenium (more recently named WebDriver) is a tool for automating web application testing, and in
particular to verify that they work as expected. It is an automation testing tool that can open
browsers, input text, click objects on the page, and more. The benefit of this tools is that it can
almost replace much of manual testing for Web applications.

30 What are the different drivers in Selenium? InternetExplorerDriver, ChromeDriver, FirefoxDriver

31 What are the different types of locators in Selenium uses what is called locators to find and match the elements of your page that it needs to
Selenium? interact with. There are 8 locators strategies included in Selenium:
Identifier , Id , Name , Link , DOM , XPath , CSS , UI-element

32 What is an assertion in Selenium? Assertions in Selenium verify that the state of the application conforms to what is required or
expected (much like JUnit). All Selenium Assertions can be used in three modes: assert, verify, and
waitFor. For example, you can "assertText", "verifyText", and "waitForText". When assert fails, the
test is aborted. When verify fails, the test will continue but will log the failure. This allows a single
assert to ensure that the application is on the correct page, followed by a bunch of verify assertions
to test form field values, labels, etc.

33 How do you type into a textbox with Selenium? WebElement sendKeys method.

34 How do you launch a Web browser using WebDriver get(url) method


Selenium?

35 What is Xpath? XPath is a syntax for defining parts of an XML document. XPath uses path expressions to navigate
in XML documents. XPath contains a library of standard functions. XPath is a major element in
XSLT

36 What are the different types of waits? Waiting is having the automated task execution elapse a certain amount of time before continuing
with the next step. You should choose to use Explicit Waits or Implicit Waits.
37 What is explicit wait? An explicit waits is code you define to wait for a certain condition to occur before proceeding further
in the code.
38 What is implicit wait? An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to
find an element or elements if they are not immediately available. The default setting is 0. Once set,
the implicit wait is set for the life of the WebDriver object instance.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

39 How do you select from a drop-down menu? Just wrap your WebElement into Select Object:
Select dropdown = new Select(driver.findElement(By.id("identifier")));
To select an option, you can do:
dropdown.selectByVisibleText("Option1");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("value1");

40 How do you use XML to input data into WebDriver By integrating Selenium with TestNG. There are two ways by which we can achieve
tests? parameterization in TestNG:
1. Parameters annotation and TestNG XML file.
2. DataProvider annotation.

41 How would you manipulate dynamic content on a You can use Xpath to iterate through dynamically created content. Typically, generated content has
Web page? a base HTML id or name with an index identifying each dynamic element.
pageID:formID:pBlockID:pbTableID:1:dateColID
pageID:formID:pBlockID:pbTableID:2:dateColID
pageID:formID:pBlockID:pbTableID:n:dateColID

42 How would you automate a file upload using For those of you doing this locally, all you need to do is use the sendKeys command to type the
Selenium? local path of the file in any file field. This works in all drivers. When moving this test to a remote
server, use the setFileDetector method to let WebDriver know that you’re uploading files from your
local computer to a remote server instead of just typing a path.

Anda mungkin juga menyukai