Saturday, 16 June 2018

What is Marker interface?



The marker interface is a design pattern, used with languages that provide run-time type information about objects. It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies methods that an implementing class must support, a marker interface does not do so.

Marker interface in java is an interface which does not have any method. Marker interface is used to inform the JVM that the classes implementing them will have some special behavior.

Example of Marker interfaces are:-


  • java.io.Serializable - Serializability of a class is enabled by the class implementing the java.io.Serializable interface. The Java Classes that do not implement Serializable interface will not be able to serialize or deserializ their state. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
  • java.rmi.Remote - The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available remotely.
  • java.lang.Cloneable - A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.


The "instanceof" keyword in java can be used to test if an object is of a specified type. So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.

Enjoy Reading.

Static variables in Java



A static variable is associated with the class as a whole rather than with specific instances of a
class. Each object will share a common copy of the static variables i.e. there is only one copy per
class, no matter how many objects are created from it. Class variables or static variables are
declared with the static keyword in a class. These are declared outside a class and stored in
static memory. Class variables are mostly used for constants.

Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable.
Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.

Example:-
public class SampleProgram {  
      static int i = 1;  
      public static void main(String[] args) {  
           System.out.println("Initial Value:" + i);  
           incrementAndDisplay();  
      }  
      private static void incrementAndDisplay() {  
           i = i + 2;  
           System.out.println("After increment:" + i);  
      }  
 }  

Output:-

Initial Value:1
After increment:3

Static methods are implicitly final, because overriding is done based on the type of the object, and
static methods are attached to a class, not an object. A static method in a superclass can be
shadowed by another static method in a subclass, as long as the original method was not
declared final. However, you can’t override a static method with a non-static method. In other
words, you can’t change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.


Enjot Reading.

Why String class is immutable?



Strings implemented as final or immutable objects.It provides lot of advantages in its usage. Below are some advantages of String Immutability in Java


  • Immutable objects are thread-safe. Two threads can both work on an immutable object at the same time without any possibility of conflict.
  • Security: the system can pass on sensitive bits of read-only information without worrying that it will be altered
  • You can share duplicates by pointing them to a single instance.
  • You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret that makes Java substring implementation very fast.
  • Immutable objects are good fit for becoming Hashtable keys. If you change the value of any object that is used as a hash table key without removing it and re-adding it you will lose the object mapping.
  • Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth.
  • If String were not final, you could create a subclass and have two strings that look alike when "seen as Strings", but that are actually different.

Enjoy Reading.

What is immutable object in Java?



A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code.

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes(All Wrapper Classes) are the Examples of immutable objects from the JDK.

Advantage/benefits of Immutable Objects:-


  • Immutable objects are simple to use test and construct.
  • Immutable objects are automatically thread-safe.
  • Immutable objects do not require a copy constructor.
  • Immutable objects do not require an implementation of clone.
  • Immutable objects allow hashCode to use lazy initialization, and to cache its return value.
  • Immutable objects do not need to be copied defensively when used as a field.
  • Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection).
  • Immutable objects have their class invariant established once upon construction, and it never needs to be checked again.
  • Immutable objects always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state.

Enjoy Reading.

Java program execution inside JVM



When JVM executes a Java application, a runtime instance of JVM is born.This runtime instance invoke main() method of Java application.The main() method of an application serves as the starting point for that application's initial thread. The initial thread can in turn fire off other threads.

This thread has a program counter(PC) and Java stack.Whenever main() method is invoked, a stack frame is pushed onto the stack,this then becomes the active tack frame.The program counter in the new Java stack frame will point to the beginning of the method.

If there are more method invocations within main() method then this process of pushing new stack frame onto the stack for each method call is repeated as and when they are invoked.When a method returns, the active frame is popped from the stack and the one below becomes the active stack frame.The PC is set to the instruction after the method call and the method continues.

There is only one heap corresponding to an instance of JVM and all objects created are stored here.This heap is shared by all threads created in an application.

Inside the Java virtual machine, threads come in two flavors: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application--the one that begins at main()--is a non- daemon thread.

A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.

When main() returns,it terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.

Enjoy Reading

Hibernate Interview Questions and Answers



1. What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service.
This lets the users to develop persistent classes following object-oriented principles such
as association, inheritance, polymorphism, composition, and collections.

2. What is ORM?
ORM stands for Object/Relational mapping. It is the programmed and translucent
perseverance of objects in a Java application in to the tables of a relational database using
the metadata that describes the mapping between the objects and the database. It works
by transforming the data from one representation to another.

3. What does an ORM solution comprises of?
• It should have an API for performing basic CRUD (Create, Read, Update, Delete)
operations on objects of persistent classes
• Should have a language or an API for specifying queries that refer to the classes
and the properties of classes
• An ability for specifying mapping metadata
• It should have a technique for ORM implementation to interact with transactional
objects to perform dirty checking, lazy association fetching, and other optimization
functions

4. What are the different levels of ORM quality?
There are four levels defined for ORM quality.
i. Pure relational
ii. Light object mapping
iii. Medium object mapping
iv. Full object mapping

5. What is a pure relational ORM?
The entire application, including the user interface, is designed around the relational
model and SQL-based relational operations.

6. What is a meant by light object mapping?
The entities are represented as classes that are mapped manually to the relational tables.
The code is hidden from the business logic using specific design patterns. This approach
is successful for applications with a less number of entities, or applications with common,
metadata-driven data models. This approach is most known to all.

7. What is a meant by medium object mapping?
The application is designed around an object model. The SQL code is generated at build
time. And the associations between objects are supported by the persistence mechanism,
and queries are specified using an object-oriented expression language. This is best suited
for medium-sized applications with some complex transactions. Used when the mapping
exceeds 25 different database products at a time.

8. What is meant by full object mapping?
Full object mapping supports sophisticated object modeling: composition, inheritance,
polymorphism and persistence. The persistence layer implements transparent persistence;
persistent classes do not inherit any special base class or have to implement a special
interface. Efficient fetching strategies and caching strategies are implemented
transparently to the application.

9. What are the benefits of ORM and Hibernate?
There are many benefits from these. Out of which the following are the most important
one.
i. Productivity – Hibernate reduces the burden of developer by providing much of
the functionality and let the developer to concentrate on business logic.
ii. Maintainability – As hibernate provides most of the functionality, the LOC for the
application will be reduced and it is easy to maintain. By automated object/relational
persistence it even reduces the LOC.
iii. Performance – Hand-coded persistence provided greater performance than
automated one. But this is not true all the times. But in hibernate, it provides more
optimization that works all the time there by increasing the performance. If it is
automated persistence then it still increases the performance.
iv. Vendor independence – Irrespective of the different types of databases that are
there, hibernate provides a much easier way to develop a cross platform application.

10. How does hibernate code looks like?
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");
session.save(mpc);
tx.commit();
session.close();
The Session and Transaction are the interfaces provided by hibernate. There are many
other interfaces besides this.

11. What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information is provided
in an xml document. This document is called as xml mapping document. The document
defines, among other things, how properties of the user defined persistence classes’ map
to the columns of the relative tables in database.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="sample.MyPersistanceClass" table="MyPersitaceTable">
<id name="id" column="MyPerId">
<generator class="increment"/>
</id>
<property name="text" column="Persistance_message"/>
<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>
</class>
</hibernate-mapping>
Everything should be included under <hibernate-mapping> tag. This is the main tag for
an xml mapping document.
`
12. What the Core interfaces are of hibernate framework?
There are many benefits from these. Out of which the following are the most important
one.
i. Session Interface – This is the primary interface used by hibernate applications.
The instances of this interface are lightweight and are inexpensive to create and destroy.
Hibernate sessions are not thread safe.
ii. SessionFactory Interface – This is a factory that delivers the session objects to
hibernate application. Generally there will be a single SessionFactory for the whole
application and it will be shared among all the application threads.
iii. Configuration Interface – This interface is used to configure and bootstrap
hibernate. The instance of this interface is used by the application in order to specify the
location of hibernate specific mapping documents.
iv. Transaction Interface – This is an optional interface but the above three interfaces
are mandatory in each and every application. This interface abstracts the code from any
kind of transaction implementations such as JDBC transaction, JTA transaction.
v. Query and Criteria Interface – This interface allows the user to perform queries
and also control the flow of the query execution.

13. What are Callback interfaces?
These interfaces are used in the application to receive a notification when some object
events occur. Like when an object is loaded, saved or deleted. There is no need to
implement callbacks in hibernate applications, but they’re useful for implementing
certain kinds of generic functionality.

14. What is the file extension you use for hibernate mapping file?
The name of the file should be like this : filename.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this
extension.

15. What do you create a SessionFactory?
Configuration cfg = new Configuration();
cfg.addResource("myinstance/MyConfig.hbm.xml");
cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();
First, we need to create an instance of Configuration and use that instance to refer to the
location of the configuration file. After configuring this instance is used to create the
SessionFactory by calling the method buildSessionFactory().

16. What is meant by Method chaining?
Method chaining is a programming technique that is supported by many hibernate
interfaces. This is less readable when compared to actual java code. And it is not
mandatory to use this format. Look how a SessionFactory is created when we use method
chaining.
SessionFactory sessions = new Configuration()
.addResource("myinstance/MyConfig.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();

17. What does hibernate.properties file consist of?
This is a property file that should be placed in application class path. So when the
Configuration object is created, hibernate is first initialized. At this moment the
application will automatically detect and read this hibernate.properties file.
hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class =
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class =
net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

18. What should SessionFactory be placed so that it can be easily accessed?
As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI
then it can be easily accessed and shared between different threads and various
components that are hibernate aware. You can set the SessionFactory to a JNDI by
configuring a property hibernate.session_factory_name in the hibernate.properties file.

19. What are POJOs?
POJO stands for plain old java objects. These are just basic JavaBeans that have defined
setter and getter methods for all the properties that are there in that bean. Besides they
can also have some business logic related to that property. Hibernate applications works
efficiently with POJOs rather then simple java classes.

20. What is object/relational mapping metadata?
ORM tools require a metadata format for the application to specify the mapping between
classes and tables, properties and columns, associations and foreign keys, Java types and
SQL types. This information is called the object/relational mapping metadata. It defines
the transformation between the different data type systems and relationship
representations.

21. What is HQL?
HQL stands for Hibernate Query Language. Hibernate allows the user to express queries
in its own portable SQL extension and this is called as HQL. It also allows the user to
express in native SQL.

22. What are the different types of property and class mappings?
• Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
Or
<property name="description" type="string">
<column name="DESCRIPTION"/>
</property>
• Derived properties
<property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b
where b.ITEM_ID = ITEM_ID )" type="big_decimal"/>
• Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
• Controlling inserts and updates
<property name="name" column="NAME" type="string"
insert="false" update="false"/>


23. What are the different approaches to represent an inheritance hierarchy?
i. Table per concrete class.
ii. Table per class hierarchy.
iii. Table per subclass.

Enjoy Reading.

Wednesday, 13 June 2018

SQL Interview Questions with Answers



What is RDBMS?
Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers.
This allows a high degree of data independence. An RDBMS has the capability to recombine the data
items from different files, providing powerful tools for data usage.

What is normalization?
Database normalization is a data design and organization process applied to data structures based on
rules that help build relational databases. In relational database design, the process of organizing data
to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables.
The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

What are different normalization forms?
1NF: Eliminate Repeating Groups
Make a separate table for each set of related attributes, and give each table a primary key. Each field
contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data
If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key
If attributes do not contribute to a description of the key, remove them to a separate table. All
attributes must be directly dependent on the primary key
BCNF: Boyce-Codd Normal Form
If there are non-trivial dependencies between candidate key attributes, separate them out into distinct
tables.
4NF: Isolate Independent Multiple Relationships
No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF: Isolate Semantically Related Multiple Relationships
There may be practical constrains on information that justify separating logically related many-to-many relationships.
ONF: Optimal Normal Form
A model limited to only simple (elemental) facts, as expressed in Object Role Model notation.
DKNF: Domain-Key Normal Form
A model free from all modification anomalies.
Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first
fulfill all the criteria of a 2NF and 1NF database.

What is Stored Procedure?
A stored procedure is a named group of SQL statements that have been previously created and stored
in the server database. Stored procedures accept input parameters so that a single procedure can be
used over the network by several clients using different input data. And when the procedure is
modified, all clients automatically get the new version. Stored procedures reduce network traffic and
improve performance. Stored procedures can be used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.

What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE)
occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential
integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed;
the DBMS automatically fires the trigger as a result of a data modification to the associated table.
Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is
stored at the database level. Stored procedures, however, are not event-drive and are not attached to a
specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the
procedure while triggers are implicitly executed. In addition, triggers can also execute stored
procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the
trigger is fired because of data modification it can also cause another data modification, thereby firing
another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as
updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the
view was created with. It should also be noted that as data in the original table changes, so does data
in the view, as views are the way to look at part of the original table. The results of using a view are
not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views.

What is Index?
An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application.
A table scan happens when there is no index available to help a query. In a table scan SQL
Server examines every row in the table to satisfy the query results. Table scans are sometimes
unavoidable, but on large tables, scans have a terrific impact on performance.
Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this
reason, each database table may have only one clustered index.
Non-clustered indexes are created outside of the database table and contain a sorted list of references
to the table itself.

What is the difference between clustered and a non-clustered index?
A clustered index is a special type of index that reorders the way records in the table are physically
stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain
the data pages.
A nonclustered index is a special type of index in which the logical order of the index does not match
the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

What are the different index configurations a table can have?
A table can have one of the following index configurations:
No indexes
A clustered index
A clustered index and many nonclustered indexes
A nonclustered index
Many nonclustered indexes

What is cursors?
Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis,
instead of the typical SQL commands that operate on all the rows in the set at one time.
In order to work with a cursor we need to perform some steps in the following order:
Declare cursor
Open cursor
Fetch row from the cursor
Process fetched row
Close cursor
Deallocate cursor

What is the use of DBCC commands?
DBCC stands for database consistency checker. We use these commands to check the consistency of
the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.
DBCC CHECKALLOC - To check that all pages in a db are correctly allocated.
DBCC CHECKFILEGROUP - Checks all tables file group for any damage.

What is a Linked Server?
Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query
both the SQL Server dbs using T-SQL Statements. With a linked server, you can create very clean, easy
to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data.
Storped Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.

What is Collation?
Collation refers to a set of rules that determine how data is sorted and compared. Character data is
sorted using rules that define the correct character sequence, with options for specifying casesensitivity,
accent marks, kana character types and character width.

What are different type of Collation Sensitivity?
Case sensitivity
A and a, B and b, etc.
Accent sensitivity
a and á, o and ó, etc.
Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana
sensitive.
Width sensitivity
When a single-byte character (half-width) and the same character when represented as a double-byte
character (full-width) are treated differently then it is width sensitive.

What's the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by
default primary key creates a clustered index on the column, where are unique creates a nonclustered
index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key
allows one NULL only.

How to implement one-to-one, one-to-many and many-to-many relationships while
designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary
and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and
foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.

What is a NOLOCK?
Using the NOLOCK query optimiser hint is generally considered good practice in order to improve
concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are
taken when data is read. The result is a Dirty Read, which means that another process could be
updating the data at the exact time you are reading it. There are no guarantees that your query will
retrieve the most recent data. The advantage to performance is that your reading of data will not block
updates from taking place, and updates will not block your reading of data. SELECT statements take
Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but
other processes are blocked from modifying the data. The updates will queue until all the reads have
completed, and reads requested after the update will wait for the updates to complete. The result to
your system is delay(blocking).

What is difference between DELETE & TRUNCATE commands?
Delete command removes the rows from a table based on the condition that we provide with a WHERE
clause. Truncate will actually remove all the rows from a table and there will be no data in the table
after we run the truncate command.
TRUNCATE
TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the
page deallocations are recorded in the transaction log.
TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes
and so on remain. The counter used by an identity for new rows is reset to the seed for the column.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE can not be Rolled back.
TRUNCATE is DDL Command.
TRUNCATE Resets identity of the table.
DELETE
DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
If you want to retain the identity counter, use DELETE instead. If you want to remove table definition
and its data, use the DROP TABLE statement.
DELETE Can be used with or without a WHERE clause
DELETE Activates Triggers.
DELETE Can be Rolled back.
DELETE is DML Command.
DELETE does not reset identity of the table.

When is the use of UPDATE_STATISTICS command?
This command is basically used when a large processing of data has occurred. If a large amount of
deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to
take these changes into account. UPDATE_STATISTICS updates the indexes on these tables
accordingly.

What types of Joins are possible with Sql Server?
Joins are used in queries to explain how different tables are related. Joins also let you select data from
a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT
OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT
statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING
behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a
query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

What is sub-query? Explain properties of sub-query.
Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed
arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in a set of
parentheses. Sub-queries are generally used to return a single row as an atomic value, though they
may be used to compare values against multiple rows with the IN keyword.
A subquery is a SELECT statement that is nested within another T-SQL statement. A subquery SELECT
statement if executed independently of the T-SQL statement, in which it is nested, will return a result
set. Meaning a subquery SELECT statement can standalone and is not depended on the statement in
which it is nested. A subquery SELECT statement can return any number of values, and can be found
in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a
T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery
can be used anywhere an expression can be used.
Properties of Sub-Query
A subquery must be enclosed in the parenthesis.
A subquery must be put in the right hand of the comparison operator, and
A subquery cannot contain a ORDER-BY clause.
A query can contain more than one sub-queries.

What are types of sub-queries?
Single-row subquery, where the subquery returns only one row.
Multiple-row subquery, where the subquery returns multiple rows,.and
Multiple column subquery, where the subquery returns multiple columns.

What is SQL Profiler?
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of
Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to
analyze later. For example, you can monitor a production environment to see which stored procedures
are hampering performance by executing too slowly.
Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too
large, you can filter them based on the information you want, so that only a subset of the event data is
collected. Monitoring too many events adds overhead to the server and the monitoring process and can
cause the trace file or trace table to grow very large, especially when the monitoring process takes
place over a long period of time.

What is User Defined Functions?
User-Defined Functions allow to define its own T-SQL functions that can accept 0 or more parameters
and return a single scalar data value or a table data type.

What kind of User-Defined Functions can be created?
There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-
Valued and Multi-statement Table-valued.
Scalar User-Defined Function
A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp
data types are not supported. These are the type of user-defined functions that most developers are
used to in other programming languages. You pass in 0 to many parameters and you get a return
value.
Inline Table-Value User-Defined Function
An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative
to a view as the user-defined function can pass parameters into a T-SQL select command and in
essence provide us with a parameterized, non-updateable view of the underlying tables.
Multi-statement Table-Value User-Defined Function
A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional
alternative to a view as the function can support multiple T-SQL statements to build the final result
where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a TSQL
select command or a group of them gives us the capability to in essence create a parameterized,
non-updateable view of the data in the underlying tables. Within the create function command you
must define the table structure that is being returned. After creating this type of user-defined function,
It can be used in the FROM clause of a T-SQL command unlike the behavior found when using a stored
procedure which can also return record sets.

Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties –> Port
number.both on client and the server.

What are the authentication modes in SQL Server? How can it be changed?
Windows mode and mixed mode (SQL & Windows).
To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL
Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group.
Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the Security page.

Where are SQL server users names and passwords are stored in sql server?
They get stored in master db in the sysxlogins table.

Which command using Query Analyzer will give you the version of SQL server and operating
system?
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY('edition')

What is SQL server agent?
SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the
implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to
schedule your own jobs and scripts.

Can a stored procedure call itself or recursive stored procedure? How many level SP nesting
possible?
Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves.
Recursion can be defined as a method of problem solving wherein the solution is arrived at by
repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps.
Stored procedures are nested when one stored procedure calls another or executes managed code by
referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code
references up to 32 levels.

What is the difference between a local and a global variable?
A local temporary table exists only for the duration of a connection or, if defined inside a compound
statement, for the duration of the compound statement.
A global temporary table remains in the database permanently, but the rows exist only within a given
connection. When connection are closed, the data in the global temporary table disappears. However,
the table definition remains with the database for access when database is opened next time.

What are the OS services that the SQL Server installation adds?
MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)
What are three SQL keywords used to change or set someone’s permissions?
GRANT, DENY, and REVOKE.

What are primary keys and foreign keys?
Primary keys are the unique identifiers for each row. They must contain unique values and cannot be
null. Due to their importance in relational databases, Primary keys are the most fundamental of all keys
and constraints. A table can have only one Primary key.
Foreign keys are both a method of ensuring data integrity and a manifestation of the relationship
between tables.

What is data integrity? Explain constraints?
Data integrity is an important feature in SQL Server. When used properly, it ensures that data is
accurate, correct, and valid. It also acts as a trap for otherwise undetectable bugs within applications.
A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should
have a primary key constraint to uniquely identify each row and only one primary key constraint can be
created for each table. The primary key constraints are used to enforce entity integrity.
A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values
are entered. The unique key constraints are used to enforce entity integrity as the primary key
constraints.
A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the
corresponding data values. A foreign key in one table points to a primary key in another table. Foreign
keys prevent actions that would leave rows with foreign key values when there are no primary keys
with that value. The foreign key constraints are used to enforce referential integrity.
A CHECK constraint is used to limit the values that can be placed in a column. The check constraints
are used to enforce domain integrity.
A NOT NULL constraint enforces that the column will not accept null values. The not null constraints
are used to enforce domain integrity, as the check constraints.

What are the properties of the Relational tables?
Relational tables have six properties:
· Values are atomic.
· Column values are of the same kind.
· Each row is unique.
· The sequence of columns is insignificant.
· The sequence of rows is insignificant.
· Each column must have a unique name.

What is De-normalization?
De-normalization is the process of attempting to optimize the performance of a database by adding
redundant data. It is sometimes necessary because current DBMSs implement the relational model
poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while
providing physical storage of data that is tuned for high performance. De-normalization is a technique
to move from higher to lower normal forms of database modeling in order to speed up database access.

What is Identity?
Identity (or AutoNumber) is a column that automatically generates numeric values. A start and
increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers,
the value of this cannot be controled. Identity/GUID columns do not need to be indexed.

What is a Scheduled Jobs or What is a Scheduled Tasks?
Scheduled tasks let user automate processes that run on regular or predictable cycles. User can
schedule administrative tasks, such as cube processing, to run during times of slow business activity.
User can also determine the order in which tasks run by creating job steps within a SQL Server Agent
job. E.g. Back up database, Update Stats of Tables. Job steps give user control over flow of execution.
If one job fails, user can configure SQL Server Agent to continue to run the remaining tasks or to stop execution.

What is a table called, if it does not have neither Cluster nor Non-cluster Index? What is it
used for?
Unindexed table or Heap. Microsoft Press Books and Book On Line (BOL) refers it as Heap.
A heap is a table that does not have a clustered index and, therefore, the pages are not linked by
pointers. The IAM pages are the only structures that link the pages in a table together.
Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table and than do bulk of inserts and to restore those indexes after that.

What is BCP? When does it used?
BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the
structures same as source to destination.

How do you load large data to the SQL server database?
BulkCopy is a tool used to copy huge amount of data from tables. BULK INSERT command helps to
Imports a data file into a database table or view in a user-specified format.

Can we rewrite subqueries into simple select statements or with joins?
Subqueries can often be re-written to use a standard outer join, resulting in faster performance. As we
may know, an outer join uses the plus sign (+) operator to tell the database to return all non-matching
rows with NULL values. Hence we combine the outer join with a NULL test in the WHERE clause to
reproduce the result set without using a sub-query.

Can SQL Servers linked to other servers like Oracle?
SQL Server can be lined to any server provided it has OLE-DB provider from Microsoft to allow a link.
E.g. Oracle has a OLE-DB provider for oracle that Microsoft provides to add it as linked server to SQL Server group.

How to know which index a table is using?
SELECT table_name,index_name FROM user_constraints

How to copy the tables, schema and views from one SQL server to another?
Microsoft SQL Server 2000 Data Transformation Services (DTS) is a set of graphical tools and
programmable objects that lets user extract, transform, and consolidate data from disparate sources
into single or multiple destinations.

What is Self Join?
This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table. The common example is when company have a hierarchical reporting structure whereby one member of staff reports to another.

What is Cross Join?
A cross join that does not have a WHERE clause 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. The common example is when company wants to combine each product with a pricing table to analyze each product at each price.

Which virtual table does a trigger use?
Inserted and Deleted.

List few advantages of Stored Procedure.
· Stored procedure can reduced network traffic and latency, boosting application performance.
· Stored procedure execution plans can be reused, staying cached in SQL Server's memory,reducing server overhead.
· Stored procedures help promote code reuse.
· Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients.
· Stored procedures provide better security to your data.

What is DataWarehousing?
· Subject-oriented, meaning that the data in the database is organized so that all the data
elements relating to the same real-world event or object are linked together;
· Time-variant, meaning that the changes to the data in the database are tracked and recorded
so that reports can be produced showing changes over time;
· Non-volatile, meaning that data in the database is never over-written or deleted, once
committed, the data is static, read-only, but retained for future reporting;
· Integrated, meaning that the database contains data from most or all of an organization's
operational applications, and that this data is made consistent.

What is OLTP(OnLine Transaction Processing)?
In OLTP - online transaction processing systems relational database design use the discipline of data
modeling and generally follow the Codd rules of data normalization in order to ensure absolute data
integrity. Using these rules complex information is broken down into its most simple structures (a table) where all of the individual atomic level elements relate to each other and satisfy the normalization rules.

Enjoy Reading.

Database Interview Questions



  • . What is database or database management systems (DBMS)?
  • · What is SQL?
  • · What’s difference between DBMS and RDBMS?
  • · What are CODD rules?
  • · What are E-R diagrams?
  • · How many types of relationship exist in database designing? What is normalization? What are different type of normalization?
  • · What is denormalization?
  • · Can you explain Fourth Normal Form?
  • · Can you explain Fifth Normal Form?
  • · What’s the difference between Fourth and Fifth normal form?
  • · Have you heard about sixth normal form?
  • · What are DML and DDL statements?
  • · How do we select distinct values from a table?
  • · What is like operator for and what are wild cards?
  • · Can you explain Insert, Update and Delete query?
  • · What is order by clause?
  • · What is the SQL In clause?
  • · Can you explain the between clause?
  • · I have an employee salary table how do we find the second highest from it?
  • · What are different types of joins in SQL?
  • · What is “CROSS JOIN”?
  • · You want to select the first record in a given set of rows?
  • · What is the default “SORT” order for a SQL?
  • · What is a self-join?
  • · What’s the difference between DELETE and TRUNCATE?
  • · .What are Wildcard operators?
  • · Twist: - What is like clause in SQL?
  • · What’s the difference between “UNION” and “UNION ALL”?
  • · What are cursors and what are the situations you will use them?
  • · What are the steps to create a cursor?
  • · What is “Group by” clause?
  • · What is the difference between “HAVING” and “WHERE” clause?
  • · What is a Sub-Query?
  • · What are Aggregate and Scalar Functions?
  • · Can you explain the SELECT INTO Statement?
  • · What is a View?
  • · What is “Correlated Sub queries”?
  • · What is SQl injection?
  • · What is “Data Warehousing”?
  • · What are Data Marts?
  • · What are Fact tables and Dimension Tables?
  • · What is Dimensional Modeling?
  • · What is Star Schema Design?
  • · What is Snow Flake Schema design in database?
  • · What’s the difference between Star and Snow flake schema?
  • · What is ETL process in Data warehousing?
  • · What are the different stages in “Data warehousing”?
  • · What is “Data mining”?
  • · Compare “Data mining” and “Data Warehousing”?
  • · What are indexes?
  • · What are B-Trees?
  • · I have a table which has lot of inserts, is it a good database design to create
  • indexes on that table?
  • · Insert’s are slower on tables which have indexes, justify it?
  • · Why do page splitting happen?
  • · What are “Table Scan’s” and “Index Scan’s”?
  • · What are the two types of indexes and explain them in detail?
  • · What’s the difference between clustered and non-clustered indexes?
Best Of Luck

Interview questions on Project Management



  • . What is project management?
  • · Is spending in IT projects constant through out the project?
  • · Who is a stakeholder?
  • · Can you explain project life cycle?
  • · Are risk constant through out the project?
  • · Can you explain different software development life cycles?
  • · What is triple constraint triangle in project management?
  • · What is a project baseline?
  • · What is effort variance?
  • · How is normally a project management plan document organized?
  • · (I)How do you estimate a project?
  • · What is CAR (Causal Analysis and Resolution)?
  • · What is DAR (Decision Analysis and Resolution)?
  • · What is a fish bone diagram?
  • · What is pare to principle?
  • · How do you handle change request?
  • · What is internal change request?
  • · What is difference between SITP and UTP in testing?
  • · What is the software you have used for project management?
  • · What are the metrics followed in project management?
  • · You have people in your team who do not meet there deadlines or do not perform
  • what are the actions you will take?
  • · What is black box testing and White box testing?
  • · What’s the difference between Unit testing, Assembly testing and Regression
  • testing?
  • · What is V model in testing?
  • · How do you start a project?
  • · How did you do resource allocations?
  • · How will you do code reviews?
  • · What is CMMI?
  • · What are the five levels in CMMI?
  • · What is continuous and staged representation?
  • · Can you explain the process areas?
  • · What is SIX sigma?
  • · What is DMAIC and DMADV?
  • · What are the various roles in Six Sigma implementation?
  • · What are function points?
  • · What are the different types of elementary process in FPA?
  • · What are the different elements in Functions points?
  • · Can you explain in GSC and VAF in function points?
  • · What are unadjusted function points and how is it calculated?
  • · Can you explain steps in function points?
  • · What is the FP per day in your current company?
  • · Do you know Use Case points?
  • · What is COCOMO I, COCOMOII and COCOMOIII?
  • · What is SMC approach of estimation?
  • · How do you estimate maintenance project and change requests?


Best Of Luck.

Servlet and JSP Interview Questions



  • . What are Servlets?
  • · What are advantages of servlets over CGI?
  • · Can you explain Servlet life cycle?
  • · What are the two important API’s in for Servlets?
  • · Can you explain in detail “javax.servlet” package?
  • · What’s the use of Servlet Context?
  • · How do we define an application level scope for servlet?
  • · What's the difference between Generic Servlet and Http Servlet?
  • · Can you explain in detail javax.servlet.http package?
  • · What’s the architecture of a Servlet package?
  • · Why is HTTP protocol called as a stateless protocol?
  • · What are the different ways we can maintain state between requests?
  • · What is URL rewriting?
  • · What are cookies?
  • · What are sessions in Servlets?
  • · What the difference is between get Session (true) and get Session (false)?
  • · What’s the difference between “do Post” and “do get” methods?
  • · Which are the different ways you can communicate between servlets?
  • · What is functionality of “Request Dispatcher” object?
  • · How do we share data using “get Servlet Context ()”?
  • · Explain the concept of SSI?
  • · What are filters in JAVA?
  • · Can you explain in short how do you go about implementing filters using Apache Tomcat?
  • · Explain step by step of how to implement filters?
  • · What’s the difference between Authentication and authorization?
  • · Explain in brief the directory structure of a web application?
  • · Can you explain JSP page life cycle?
  • · What is EL?
  • · How does EL search for an attribute?
  • · What are the implicit EL objects in JSP?
  • · How can we disable EL?
  • · What is JSTL?
  • · Can you explain in short what the different types of JSTL tags are?
  • · (I) How can we use beans in JSP?
  • · What is the use of <jsp: include>?
  • · What is <jsp: forward> tag for?
  • · What are JSP directives?
  • · What are Page directives?
  • · What are including directives?
  • · Can you explain taglib directives?
  • · How does JSP engines instantiate tag handler classes’ instances?
  • · What’s the difference between JavaBeans and taglib directives?
  • · What are the different scopes an object can have in a JSP page?
  • · What are different implicit objects of JSP?
  • · What are different Authentication Options available in servlets?
  • · Can you explain how do we practically implement security on a resource?
  • · How do we practically implement form based authentication?
  • · How do we authenticate using JDBC?
  • · Can you explain JDBCRealm?
  • · Can you explain how do you configure JNDIRealm?
  • · How did you implement caching in JSP?
  • · What is the difference between Servletcontext and ServletConfig?
  • · How do we prevent browser from caching output of my JSP pages?
  • · Can we explicitly destroy a servlet object?
Best Of Luck

JDBC Interview Questions



  • How does JAVA interact with databases?
  • Can we interact with non-relational sources using JDBC?
  • Can you explain in depth the different sections in JDBC?
  • Can you explain in short how you go about using JDBC API in code?
  • How do you handle SQL exceptions?
    • Twist: - (A) Can you explain “SQL Exception” class in detail?
    • Twist: - (A) what is SQL State in SQL Exceptions?
  • If there is more than one exception in SQL Exception” class how to go about displaying it.
  • Explain Type1, Type2, Type3, and Type4 drivers in JDBC?
  • What are the advantages and disadvantages of using JDBC-ODBC bridge driver?
  • What are the advantages and disadvantages of using Native-API/ Partially Java Driver?
  • What are the advantages and disadvantages of using Net-Protocol/ All-Java driver?
  • What are the advantages and disadvantages of using Native-protocol/ All-Java driver
  • Advantages of using JDBC-ODBC bridge driver:-
  • Disadvantages of using JDBC-ODBC bridge driver:-
  • Advantages of using Native-API/ Partially Java Driver:-
  • Dis-advantages of using Native-API/ Partially Java Driver:-
  • Advantages of using Net-Protocol/ All-Java driver:-
  • Disadvantages of using Net-Protocol/ All- Java driver:-
  • Advantages of using Native-protocol/ All-Java driver:-
  • Disadvantages of using Native-protocol/ All-Java driver:-
  • Define meta-data?
  • What is Database Metadata?
  • Can you explain “Connection Factory” class?
  • I want to display tables of a database how do I do it?
  • Define “Result Set Meta Data”?
  • What is the difference between “Result Set” and “Row Set”?
  • Can “Result Set” objects be serialized?
  • Explain “Result Set”, “Row Set”, “Cached Row set”, “JdbcRowset” and “Web Row Set”?
  • What are the different types of result set?
  • Explain the concept of “Prepared Statement “statement interface?
  • What’s the difference between “Statement” and “Prepared Statement”?
  • How can we call stored procedure using JDBC?
  • Can you explain “Callable Statement” interface in detail?
  • How do you get a result set object from stored procedure?
  • How can we do batch updates using “Callable Statement” Interface?
  • Define transactions?
  • What is ACID in transaction?
  • What are the four essential properties of a transaction?
  • Explain concurrency and locking?
  • What are different types of locks?
  • What are the different types of levels of resource on which locks can be placed?
  • Define lock escalation?
  • What is Table level and Row level locking?
  • What are the problems that can occur if you do not implement locking properly?
  • What are different transaction levels?
  • What are different types of locks?
  • What is difference between optimistic and pessimistic locking?
  • What are deadlocks?
  • How can we set transaction level through JDBC API?
  • Can you explain transaction control in JDBC?
  • What are Save points in a transaction?

Best Of Luck.

Difference between == and equals in Java



 The == operator compares two objects to determine if they are the same object in memory i.e.
present in the same memory location. It is possible for two String objects to have the same value,
but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean
equals(Object obj) is provided by the Object class and can be overridden. The default
implementation returns true only if the object is compared with itself, which is equivalent to the
equality operator == being used to compare aliases to the object. String, BitSet, Date, and File
override the equals() method. For two String objects, value equality means that they contain the
same character sequence. For the Wrapper classes, value equality means that the primitive
values are equal.

Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           String s1 = "abc";  
           String s2 = s1;  
           String s5 = "abc";  
           String s3 = new String("abc");  
           String s4 = new String("abc");  
           System.out.println("== comparison : " + (s1 == s5));  
           System.out.println("== comparison : " + (s1 == s2));  
           System.out.println("Using equals method : " + s1.equals(s2));  
           System.out.println("== comparison : " + s3 == s4);  
           System.out.println("Using equals method : " + s3.equals(s4));  
      }  
 }  

Output:-


 == comparison : true  
 == comparison : true  
 Using equals method : true  
 false  
 Using equals method : true  

Enjoy Learning.

MindTree Interview Questions for Freshers



Aptitude Questions

1. A person losses and gains 10% on selling a object for 200.
Ans: he losses
2. Sum of 1 to 100 is divisible by 1. 1,2,4,8 2. 2 & 4 3. 2 4 none
Ans: 2
3. How many nos start and end with 2 b/w 100 and 300?
4. If a sphere of dia 3 cm is melted & formed into 3 spheres , the diameter of 1st is 1.5cm and
that of second is 2.0 cm ,
what is the diameter of the third?
5. If prizes are increased by 25% , by how much should i reduce the consumption to keep the
expenditure same??
6. "COURTESY" - how many words can be constructed with C in the begining and Y at the end
7. My mother's husband's father in laws son's child->what is the relation?
8.. 3 glasses containing mixture of water and alco in ratio 2:3 , 3:4 , 5:9 when all 3 are mixed
what is the new ratio??
9. A father has 8 children ,he takes 3 at a time to a zoo.probability of a child going to the zoo.
10. A ball is dropped from a height of 10 feet.Every time it rebounces to half of the height.
how many feet it traveled?
11. There are 3 jars. The ratio of spirit to water in each of these jars is 3:2,4:5,5:7. the three
jars are mixed into a single jar.
What is the ration of spirit to water in single jar.
12.. What is the relation with your mother's sister's brother's wife's child with you.?
13. A father has six children .all the children are born at regular intervels.if the sum of their
ages of
all the children and father is 186. calculate the age of the elder son, when the younger sons
age is 3.

logical reasoning :

1. What is the 7th digit of (202)3?
2. To type the digits from 1-1000 how many key strokes are needed?
3. A problem on the margin of votes involving winning percentage between two candidates.
4. Time & Distance- A is running faster than B by ….. kms. How much increase of speed is
needed by B to become first?
5. Problem on three pipes- two of them loading water into a tank the other one emptying,
what time will it take to fill the tank? (2 problems)
6. Four horses are tied up by rope on four corners of a square grass field. What would be the
ungrazed area by them?
7. If a person gets A% profit on cost price A. Determine the cost price? Four alternatives were
given --Ans. 40. As the thing was sold at 56/cost price--40.
8. Determine the angle between the hour & minute hand when the time is 40 past 3.
9. There is a Square. One Circle which is touching all the arms of the square is inscribed in it.
Another smaller square which ahs all corners touching the circle is inscribed inside the circle.
Obtain the ratio of the area of the two squares.
10. In a zoo there are animals & birds. No of heads are ………, No of legs …..., obtain the
number of birds & animals.
11. Simple aptitude type problems on probability. (2 problems)
12. Problems on percentage.
13.The C’ program was on simple binary tree.

GD Topic

1. Westernization of INDIA-- right or wrong
2. IT boom in INDIA—blessing or curse.
1. we have to count the 3 letter,4letter and 5letter words from a file and print the number of 3
letter,4letter and 5letter words. Delimiter is space, tab, hifen. Also we should not consider the
line in the file after we encounter # in that line. (ie after # we should not consider the portion
of line)
2. In file count the number of characters, number of words, number of line. Delimiter between
words is given as command line argument.
1hour 15 min is given for the test. we have to answer both aptitude and program with in this
time.

Some reasoning questions

1. there are six steps,5 people a,b,c,d,e . conditions are , a is two steps below c,no two people
are on same step,b is next to d. 4 Questions based on this.
2. 5 people participating in the race .conditions are given about the positions.
3.a ball is dropped from a height of 10 feet. Every time it rebounces to half of the height. how
many feet it traveled?
4.There are 3 jars. The ratio of spirit to water in each of these jars is 3:2,4:5,5:7. the three
jars are mixed into a single jar. What is the ration of spirit to water in single jar.
5. What is the relation with your mothr's sister's brother's wife's child with you.?
6.what is the relation with your mother's husband's father-in-law's son's child with you?
7.we were asked to fill the series, alphabet series 4 questions are given.
8. 5 questions are given, we are asked to find the logical connection between them. like all
managers are drinkers, all drinker are smokers ,questions like this.

Simple Mathematics:
1. A triangle on a grid was given : find the area of it.
Ans : 2
2. out of the four options which is not a right angle .
Ans :D (12,9,16)
3.In a class of 100 members 50 plays soccer 45 badminton 50 volley ball and 15 plays all the
three then how many of them play two games.
Ans: can't be determined (D) verify
4.In a class the no. of boys are more than that of girls by 25% of the total strength of the
class then the ratio of boys to girls.
Ans: (5:3)(d)
5. the radius of the circle is reduced from 5cm to 4cm then the % change of area .
Ans: 36%
6.two workers can type two pages in two minuets then how many persons can type 18 pages
in 6 minuets
Ans: 6
7.if p+q+r=0 then p^2/qr+q^2/pr+r^2/pq=? (ans:3)(d)
8.the sum of 7 consecutive numbers is 1617 then the number of prime numbers in it.(ans:2)
9.in a nock out tournament the total no. of games played are 63 then the no. of participants
Ans: 64
10. fresh mango consists of 70% water and dry mango consists of 10% water then 20Kg of
fresh mango is equivalent to how much of dry mango
Ans: 6.66 kg
11.the no. of 3 digit numbers which when divide by 7 or 8 gives a reminder of 4
a) 16 b) 17 c) 18 d) 19


Enjoy Interview.

Reverse String using recursion in Java



Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           String str = "abcde";  
           reverseStringRecurively(str);  
      }  
      private static void reverseStringRecurively(String str) {  
           if (str.length() == 1) {  
                System.out.print(str);  
           } else {  
                reverseStringRecurively(str.substring(1, str.length()));  
                System.out.print(str.substring(0, 1));  
           }  
      }  
 }  

Output:-


 edcba  

Enjoy Coding

Software testing Interview Questions asked in Sapiens


1. Write a selenium code to click all the checkboxes in a webpage.
2. Write a selenium code to check if a checkbox is checked or unchecked.
3. Write a java code to swap two numbers without using two variables.
4. Can we instantiate an abstract class?
5. Write a selenium code to double click on a web element.
6. Tell about your current project architecture.
7. Why do we use TestNG with selenium?
8. What is the difference between @Before Test and @Before Method in TestNG?
9. For following scenario :-

@Before Test
public void beforeTestMethod ()
{
System.out.prinln (“Before Test Method”) ;
}
@Before Method
public void a()
{
System.out.prinln (“a()”) ;
}
public void b()
{
System.out.prinln (“b()”) ;
}

How many times Before Test and Before Method gets executed?
10. What is priority in TestNG ?
11. For following scenario find out the execution sequences of these methods ?

@Priority (0)
Public void a()
{
System.out.prinln (“a()”) ;
}
@Priority (0)
Public void g()
{
System.out.prinln (“g()”) ;
}
@Priority (0)
Public void d()
{
System.out.prinln (“d()”) ;
}
@Priority (0)
Public void l()
{
System.out.prinln (“l()”) ;
}

12. Using TestNG annotations how can we make sure that a method b() gets executed only if method a() is successfully executed without any errors?
13. Write a selenium code to handle multiple windows.
14. Difference between a HashMap and a HashSet?
15. Brief description of your day to day activities as a QA Engineer.

Enjoy Interview.

Software Testing Interview Questions asked in Global Logic




1. Transpose of a matrix.

2. Sum of diagonal elements of a matrix.

3. Difference between HashMap and HashSet

4. Describe your Selenium Project Architecture.

5. Use of HashMap in project.

6. Use of POM xml in a selenium project.

7. Write java code to find the duplicate elements in an array and the count of occurrences of the    duplicate no.

8. Find reverse of any number in java.

9. What are locators in Selenium?

10. Differences between Absolute and Relative xpath.

11. When to use findElement and findElements in Selenium?

12. Reasons for not automating a few scenarios out of given 10 scenarios.

13. Given Scenario :- There’s a Submit button on a webpage if user clicks that button manually after entering all the required data in that page it’s clickable. But if he tries to do so via scripts he’s unable to click on the same button. What could be the reason behind this issue?

14. How to switch between frames?

15. In a given sheet of 100 scenarios what will be your priority in choosing the scenarios for scripting?

16. How to achieve parallel testing using TestNG?

17. What can be the possible reasons if the script is unable to find a specific text present in a webpage?

18. What are constructors in Java?

19. What is method overloading and method overriding in java?

20. How can we access private variables present in the same class?

21. How can we access private methods present in a different class?

22. Use of for each loop?

23. Brief description about your roles and responsibilities.

24. What do you understand by Agile Process and KanBan process?

25. For following input, write a java program to get the O/P :-
Input :- My Name Is Padmaja
Output :- Padmaja Is My Name

Enjoy Interview.

Monday, 11 June 2018

Fibonacci series using recursion in java


Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           int n = 5;  
           System.out.print("Fibonacci Series: 0 1 ");  
           for (int i = 2; i <= n; i++) {  
                System.out.print(fibonacciRecursion(i) + " ");  
           }  
      }  
      private static int fibonacciRecursion(int n) {  
           if (n == 1 || n == 2) {  
                return 1;  
           }  
           return fibonacciRecursion(n - 1) + fibonacciRecursion(n - 2);  
      }  
 }  

Output:-


 Fibonacci Series: 0 1 1 2 3 5   

Enjoy Coding.

Sum of digits in number using recursion in java



Sample Program:-


public class SampleProgram {  
      static int sum = 0;  
      public static void main(String[] args) {  
           int number = 1234;  
           System.out.println("sum of digits : " + sumOfDigits(number));  
      }  
      private static int sumOfDigits(int number) {  
           if (number == 0) {  
                return sum;  
           } else {  
                sum = sum + (number % 10);  
                sumOfDigits(number / 10);  
           }  
           return sum;  
      }  
 }  

Output:-


 sum of digits : 10  

Enjoy Coding.

Merge two sorted arrays in Java


Suppose we have 2 sorted arrays a1={1,3,5,7} and a2={2,4,6}.We have to merge this 2 arrays to generate below result

a3={1,2,3,4,5,6,7}


Sample Program:-


public class MergeSortedArray {  
      public static void main(String[] args) {  
           int[] ar1 = { 1, 3, 5, 7 };  
           int[] ar2 = { 2, 4, 6, 8 };  
           int mergedArray[] = merge(ar1, ar2);  
           System.out.print("\nMerged array: ");  
           for (int i = 0; i < mergedArray.length; i++)  
                System.out.print(mergedArray[i] + " ");  
      }  
      private static int[] merge(int[] ar1, int[] ar2) {  
           int mergedArray[] = new int[ar1.length + ar2.length];  
           int ar1Index = 0, ar2Index = 0, mergedArrayIndex = 0;  
           while (ar1Index < ar1.length && ar2Index < ar2.length)  
                if (ar1[ar1Index] < ar2[ar2Index])  
                     mergedArray[mergedArrayIndex++] = ar1[ar1Index++];  
                else  
                     mergedArray[mergedArrayIndex++] = ar2[ar2Index++];  
           while (ar1Index < ar1.length)  
                mergedArray[mergedArrayIndex++] = ar1[ar1Index++];  
           while (ar2Index < ar2.length)  
                mergedArray[mergedArrayIndex++] = ar2[ar2Index++];  
           return mergedArray;  
      }  
 }  

Output:-


 Merged array: 1 2 3 4 5 6 7 8   

Enjoy Coding.