You are on page 1of 26

1. What is the difference between private, protected, and public?

These keywords are for allowing privileges to components such as java methods
and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member
of a class. These are:
* Public
* Protected
* Private
* Defaults

2. What's the difference between an interface and an abstract class? Also


discuss the similarities. (Very Important)
Abstract class is a class which contain one or more abstract methods, which has
to be implemented by sub classes. Interface is a Java Object containing method
declaration and doesn't contain implementation. The classes which have
implementing the Interfaces must provide the method definition for all the
methods
Abstract class is a Class prefix with a abstract keyword followed by Class
definition. Interface is a Interface which starts with interface keyword.
Abstract class contains one or more abstract methods. where as Interface contains
all abstract methods and final declarations
Abstract classes are useful in a situation that Some general methods should be
implemented and specialization behavior should be implemented by child
classes. Interfaces are useful in a situation that all properties should be
implemented.

Differences are as follows:


* Interfaces provide a form of multiple inheritance. A class can extend only one
other class.
* Interfaces are limited to public methods and constants with no implementation.
Abstract classes can have a partial implementation, protected parts, static
methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class
may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to find corresponding method
in the actual class. Abstract classes are fast.

Similarities:
* Neither Abstract classes or Interface can be instantiated.

How to define an Abstract class?


A class containing abstract method is called Abstract class. An Abstract class
can't be instantiated.
Example of Abstract class:
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}

How to define an Interface?


Answer: In Java Interface defines the methods but does not implement them.
Interface can include constants. A class that implements the interfaces is bound
to implement all the methods defined in Interface.
Example of Interface:
public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}

3. Question: How you can force the garbage collection?


Garbage collection automatic process and can't be forced. You could request it by
calling System.gc(). JVM does not guarantee that GC will be started immediately.

Garbage collection is one of the most important feature of Java, Garbage collection
is also called automatic memory management as JVM automatically removes the
unused variables/objects (value is null) from the memory. User program can't
directly free the object from memory, instead it is the job of the garbage collector
to automatically free the objects that are no longer referenced by a program.
Every class inherits finalize() method from java.lang.Object, the finalize() method
is called by garbage collector when it determines no more references to the object
exists. In Java, it is good idea to explicitly assign null into a variable when no
more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle
the unused objects, but there is no guarantee when all the objects will garbage
collected.

4. What's the difference between constructors and normal methods?


Constructors must have the same name as the class and can not return a value.
They are only called once while regular methods could be called many times and
it can return a value or can be void.

5. Can you call one constructor from another if a class has multiple
constructors
Yes. Use this() to call a constructor from an other constructor.

6. Explain the usage of Java packages.


This is a way to organize files when a project consists of multiple modules. It also
helps resolve naming conflicts when different packages have classes with the
same names. Packages access level also allows you to protect data from being
used by the non-authorized classes.

7. Explain in your own words the "bottom line" benefits of the use of an
interface.
The interface makes it possible for a method in one class to invoke methods on
objects of other classes, without the requirement to know the true class of those
objects, provided that those objects are all instantiated from classes that
implement one or more specified interfaces. In other words, objects of classes
that implement specified interfaces can be passed into methods of other objects
as the generic type Object, and the methods of the other objects can invoke
methods on the incoming objects by first casting them as the interface type.

8. What are some advantages and disadvantages of Java Sockets?


Some advantages of Java Sockets:
Sockets are flexible and sufficient. Efficient socket based programming can be
easily implemented for general communications. Sockets cause low network
traffic. Unlike HTML forms and CGI scripts that generate and transfer whole
web pages for each new request, Java applets can send only necessary updated
information.

Some disadvantages of Java Sockets:


Security restrictions are sometimes overbearing because a Java applet running in
a Web browser is only able to establish connections to the machine where it came
from, and to nowhere else on the network Despite all of the useful and helpful
Java features, Socket based communications allows only to send packets of raw
data between applications. Both the client-side and server-side have to provide
mechanisms to make the data useful in any way.

9. Explain the usage of the keyword transient?


Transient keyword indicates that the value of this member variable does not
have to be serialized with the object. When the class will be de-serialized, this
variable will be initialized with a default value of its data type (i.e. zero for
integers).

10. What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code
wait(1000), causes a wait of up to one second. A thread could stop waiting earlier
if it receives the notify() or notifyAll() call. The method wait() is defined in the
class Object and the method sleep() is defined in the class Thread.

11. What would you use to compare two String variables - the operator == or
the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to
check if two variables point at the same instance of a String object.

12. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.

13. What access level do you need to specify in the class declaration to ensure
that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package
access level.

14. Can an inner class declared inside of a method access local variables of this
method?
It's possible if these variables are final.

15. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A single ampersand here would lead to a NullPointerException.

16. What's the main difference between a Vector and an ArrayList?


Java Vector class is internally synchronized and ArrayList is not synchronized.

17. Describe the wrapper classes in Java.


Wrapper class is wrapper around a primitive data type. An instance of a
wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void

18. How could Java classes direct program messages to the system console, but
error messages, say to a file?
The class System has a variable out that represents the standard output, and the
variable err that represents the standard error device. By default, they both point
at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st);
System.setOut(st);

19. How do you know if an explicit object casting is needed?


If you assign a superclass object to a variable of a subclass's data type, you need
to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;

20. When you assign a subclass to a variable having a supeclass type, the
casting is performed automatically. Can you write a Java class that could be
used both as an applet as well as an application?
Yes. Add a main() method to the applet.

21. If a class is located in a package, what do you need to change in the OS


environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to
the CLASSPATH environment variable. Let's say a class Employee belongs to a
package com.xyz.hr; and is located in the file
c:\dev\com\xyz\hr\Employee.javIn this case, you'd need to add c:\dev to the
variable CLASSPATH. If this class contains the method main(), you could test it
from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

22. What's the difference between J2SDK 1.5 and J2SDK 5.0?
There's no difference, Sun Microsystems just re-branded this version.

23. Does it matter in what order catch statements for FileNotFoundException


and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException.
Exception's subclasses have to be caught first.

24. Name the containers which uses Border Layout as their default layout?
Containers which uses Border Layout as their default are: window, Frame and
Dialog classes.

25. You are planning to do an indexed search in a list of objects. Which of the
two Java collections should you use:
ArrayList or LinkedList?
ArrayList

26. When should the method invokeLater()be used?


This method is used to ensure that Swing components are updated through the
event-dispatching thread.

27. How can a subclass call a method or a constructor defined in a superclass?


Use the following syntax: super.myMethod(); To call a constructor of the
superclass, just write super(); in the first line of the subclass's constructor.

28. What do you understand by Synchronization?


Synchronization is a process of controlling the access of shared resources by the
multiple threads in such a manner that only one thread can access one resource
at a time. In non synchronized multithreaded application, it is possible for one
thread to modify a shared object while another thread is in the process of using
or updating the object's value. Synchronization prevents such type of data
corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

29. What's the difference between a queue and a stack?


Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

30. You can create an abstract class that contains only abstract methods. On the
other hand, you can create an interface that declares the same methods. So can
you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case
the interface is your only option.

31. If you're overriding the method equals() of an object, which other method
you might also consider?
hashCode()

32. What is Collection API?


The Collection API is a set of classes and interfaces that support operation on
collections of objects. These classes and interfaces are more flexible, more
powerful, and more regular than the vectors, arrays, and hashtables if effectively
replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and
TreeMap.
Example of interfaces: Collection, Set, List and Map.

33. How would you make a copy of an entire Java object with its state?
Have this class implement Cloneable interface and call its method clone().

34. How can you minimize the need of garbage collection and make the
memory use more effective?
Use object pooling and weak object references.

35. There are two classes: A and B. The class B need to inform a class A when
some important event has happened. What Java technique would you use to
implement it?
If these classes are threads I'd consider notify() or notifyAll(). For regular classes
you can use the Observer interface.

36. Explain the Encapsulation principle.


Encapsulation is a process of binding or wrapping the data and the codes that
operates on the data into a single entity. This keeps the data safe from outside
interface and misuse. One way to think about encapsulation is as a protective
wrapper that prevents code and data from being arbitrarily accessed by other
code defined outside the wrapper.

37. Explain the Inheritance principle.


Inheritance is the process by which one object acquires the properties of another
object.

38. Explain the Polymorphism principle.


The meaning of Polymorphism is something like one name many forms.
Polymorphism enables one entity to be used as as general category for different
types of actions. The specific action is determined by the exact nature of the
situation. The concept of polymorphism can be explained as "one interface,
multiple methods".
From a practical programming viewpoint, polymorphism exists in three distinct
forms in Java:

* Method overloading
* Method overriding through inheritance
* Method overriding through the Java interface

39. Is Iterator a Class or Interface? What is its use?


Iterator is an interface which is used to step through the elements of a
Collection.
40. Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user
for specific purposed. An user defined can created by simply sub-classing it to
the Exception class. This allows custom exceptions to be generated (using throw)
and caught in the same way as normal exceptions.
Example:

class myCustomException extends Exception {


/ The class simply has to exist to be an exception
}

41. What is OOPS?


OOP is the common abbreviation for Object-Oriented Programming.
There are three main principals of oops which are called Polymorphism,
Inheritance and Encapsulation.

39. Read the following program:


public class test {
public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println("Not equal");
else
System.out.println("Equal");
}
}

What is the result?


The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.
Answer: C
Answer: Transient variable can't be serialize. For example if a variable is declared
as transient in a Serializable class and the class is written to an ObjectStream, the
value of the variable can't be written to the stream instead when the class is
retrieved from the ObjectStream the value of the variable becomes null.

Re: define System.out.println(); what is the meaning!


Answer System: System refers to current java program.
#1
out: out refers to output device. by default it is
monitor.

println: to print the specific string onto output


device in
next line

System: its the class


out: its the object of the class System
println():its the method which tells the compiler
to print a new line.

Question: Explain garbage collection?


Answer: Garbage collection is one of the most important feature of Java. Garbage
collection is also called automatic memory management as JVM automatically
removes the unused variables/objects (value is null) from the memory. User
program cann't directly free the object from memory, instead it is the job of the
garbage collector to automatically free the objects that are no longer referenced
by a program. Every class inherits finalize() method from java.lang.Object, the
finalize() method is called by garbage collector when it determines no more
references to the object exists. In Java, it is good idea to explicitly assign null into
a variable when no more in use. I Java on calling System.gc() and Runtime.gc(),
JVM tries to recycle the unused objects, but there is no guarantee when all the
objects will garbage collected.

Question: How you can force the garbage collection?


Answer: Garbage collection automatic process and can't be forced.

Question: What do you understand by Synchronization?


Answer: Synchronization is a process of controlling the access of shared
resources by the multiple threads in such a manner that only one thread can
access one resource at a time. In non synchronized multithreaded application, it
is possible for one thread to modify a shared object while another thread is in the
process of using or updating the object's value. Synchronization prevents such
type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

Sql interview questions:

1. How do you 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.
It will be a good idea to read up a database designing fundamentals text book.

2. 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 nique key allows one
NULL only.

3. What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by
providing a descriptive name, and format to the database. Take for example, in
your database, there is a column called Flight_Num which appears in many
tables. In all these tables it should be varchar(8). In this case you could create a
user defined datatype called Flight_num_type of varchar(8) and use it across all
your tables.

4. What is bit datatype and what's the information that can be stored
inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill
SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support
for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third
state, which is NULL.

5. Define candidate key, alternate key, composite key


A candidate key is one that can identify each row of a table uniquely. Generally a
candidate key becomes the primary key of the table. If the table has more than
one candidate key, one of them will become the primary key, and the rest are
called alternate keys.

A key formed by combining at least two or more columns is called composite


key.

6. What are defaults? Is there a column to which a default can't be bound?


A default is a value that will be used by a column, if no value is supplied to that
column while inserting data. IDENTITY columns and timestamp columns can't
have defaults bound to them. See CREATE DEFUALT in books online.

7. What is a transaction and what are ACID properties?


A transaction is a logical unit of work in which, all the steps must be performed
or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are
the properties of a transaction. For more information and explanation of these
properties, see SQL Server books online or any RDBMS fundamentals text book.

8. Explain different isolation levels


An isolation level determines the degree of isolation of data between concurrent
transactions. The default SQL Server isolation level is Read Committed. Here are
the other isolation levels (in the ascending order of isolation): Read
Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server
books online for an explanation of the isolation levels. Be sure to read about SET
TRANSACTION ISOLATION LEVEL, which lets you customize the isolation
level at the connection level.

9. CREATE INDEX myIndex ON myTable(myColumn)


What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets
created on the primary key, unless specified otherwise.

10. What's the maximum size of a row?


8060 bytes. Don't be surprised with questions like 'what is the maximum number
of columns per table'. Check out SQL Server books online for the page titled:
"Maximum Capacity Specifications".

11. Explain Active/Active and Active/Passive cluster configurations


Hopefully you have experience setting up cluster servers. But if you don't, at
least be familiar with the way clustering works and the two clustering
configurations Active/Active and Active/Passive. SQL Server books online has
enough information on this topic and there is a good white paper available on
Microsoft site.
12. Explain the architecture of SQL Server
This is a very important question and you better be able to answer it if consider
yourself a DBA. SQL Server books online is the best place to read about SQL
Server architecture. Read up the chapter dedicated to SQL Server Architecture.

13. What is lock escalation?


Lock escalation is the process of converting a lot of low level locks (like row
locks, page locks) into higher level locks (like table locks). Every lock is a
memory structure too many locks would mean, more memory being occupied by
locks. To prevent this from happening, SQL Server escalates the many fine-grain
locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL
Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL
Server.

14. What's the difference between DELETE TABLE and TRUNCATE TABLE
commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in
the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the
rows in a table, but it won't log the deletion of each row, instead it logs the
deallocation of the data pages of the table, which makes it faster. Of course,
TRUNCATE TABLE can be rolled back.

15. Explain the storage models of OLAP


Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more
infomation.

16. What are the new features introduced in SQL Server 2000 (or the latest
release of SQL Server at the time of your interview)? What changed between
the previous version of SQL Server and the current version?
This question is generally asked to see how current is your knowledge. Generally
there is a section in the beginning of the books online titled "What's New", which
has all such information. Of course, reading just that is not enough, you should
have tried those things to better answer the questions. Also check out the section
titled "Backward Compatibility" in books online which talks about the changes
that have taken place in the new version.

1. What are constraints? Explain different types of constraints


Constraints enable the RDBMS enforce the integrity of the database
automatically, without needing you to create triggers, rule or defaults.
Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN
KEY

For an explanation of these constraints see books online for the pages titled:
"Constraints" and "CREATE TABLE", "ALTER TABLE"

2. What is an index? What are the types of indexes? How many clustered
indexes can be created on a table? I create a separate index on each column of a
table. what are the advantages and disadvantages of this approach?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server
retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When
you craete a clustered index on a table, all the rows in the table are stored in the
order of the clustered index key. So, there can be only one clustered index per
table. Non-clustered indexes have their own storage separate from the table data
storage. Non-clustered indexes are stored as B-tree structures (so do clustered
indexes), with the leaf level nodes having the index key and it's row locater. The
row located could be the RID or the Clustered index key, depending up on the
absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query


performance, as the query optimizer can choose from all the existing indexes to
come up with an efficient execution plan. At the same t ime, data modification
operations (such as INSERT, UPDATE, DELETE) will become slow, as every time
data changes in the table, all the indexes need to be updated. Another
disadvantage is that, indexes need disk space, the more indexes you have, more
disk space is used.

3. What is RAID and what are different types of RAID configurations?


RAID stands for Redundant Array of Inexpensive Disks, used to provide fault
tolerance to database servers. There are six RAID levels 0 through 5 offering
different levels of performance, fault tolerance. MSDN has some information
about RAID levels and for detailed information, check out the RAID advisory
board's homepage.

4. What are the steps you will take to improve performance of a poor
performing query?
This is a very open ended question and there could be a lot of reasons behind the
poor performance of a query. But some general issues that you could talk about
would be: No indexes, table scans, missing or out of date statistics, blocking,
excess recompilations of stored procedures, procedures and triggers without SET
NOCOUNT ON, poorly written query with unnecessarily complicated joins, too
much normalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems


are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS
IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical
execution plan in Query Analyzer.

Download the white paper on performance tuning SQL Server from Microsoft
web site. Don't forget to check out sql-server-performance.com

5. What are the steps you will take, if you are tasked with securing an SQL
Server?
Again this is another open ended question. Here are some things you could talk
about: Preferring NT authentication, using server, database and application roles
to control access to the data, securing the physical database files using NTFS
permissions, using an unguessable SA password, restricting physical access to
the SQL Server, renaming the Administrator account on the SQL Server
computer, disabling the Guest account, enabling auditing, using multiprotocol
encryption, setting up SSL, setting up firewalls, isolating SQL Server from the
web server etc.

6. What is a deadlock and what is a live lock? How will you go about resolving
deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of
data, attempt to acquire a lock on the other's piece. Each process would wait
indefinitely for the other to release the lock, unless one of the user processes is
terminated. SQL Server detects deadlocks and terminates one user's process.

A livelock is one, where a request for an exclusive lock is repeatedly denied


because a series of overlapping shared locks keeps interfering. SQL Server
detects the situation after four denials and refuses further shared locks. A
livelock also occurs when read transactions monopolize a table or page, forcing a
write transaction to wait indefinitely.

7. What is blocking and how would you troubleshoot it?


Blocking happens when one connection from an application holds a lock and a
second connection requires a conflicting lock type. This forces the second
connection to wait, blocked on the first.
Read up the following topics in SQL Server books online: Understanding and
avoiding blocking, Coding efficient transactions.

8. Explain CREATE DATABASE syntax


Many of us are used to craeting databases from the Enterprise Manager or by just
issuing the command: CREATE DATABAE MyDB. But what if you have to
create a database with two filegroups, one on drive C and the other on drive D
with log on drive E with an initial size of 600 MB and with a growth factor of
15%? That's why being a DBA you should be familiar with the CREATE
DATABASE syntax. Check out SQL Server books online for more information.

9. How to restart SQL Server in single user mode? How to start SQL Server in
minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This
EXE has some very important parameters with which a DBA should be familiar
with. -m is used for starting SQL Server in single user mode and -f is used to start
the SQL Server in minimal configuration mode. Check out SQL Server books
online for more parameters and their explanations.

10. As a part of your job, what are the DBCC commands that you commonly
use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC
CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC
SHRINKFILE etc. But there are a whole load of DBCC commands which are very
useful for DBAs. Check out SQL Server books online for more information.

11. What are statistics, under what circumstances they go out of date, how do
you update them?
Statistics determine the selectivity of the indexes. If an indexed column has
unique values then the selectivity of that index is more, as opposed to an index
with non-unique values. Query optimizer uses these indexes in determining
whether to choose an index or not while executing a query.

Some situations under which you should update statistics:


1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or
removed (that is, if the distribution of key values has changed), or the table has
been truncated using the TRUNCATE TABLE statement and then repopulated
3) Database is upgraded from a previous version
Look up SQL Server books online for the following commands: UPDATE
STATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS,
DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats

12. What are the different ways of moving data/databases between servers and
databases in SQL Server?
There are lots of options available, you have to choose your option depending
upon your requirements. Some of the options you have are:
BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP,
logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to
generate data.

13. Explain different types of BACKUPs available in SQL Server? Given a


particular scenario, how would you go about choosing a backup plan?
Types of backups you can create in SQL Sever 7.0+ are Full database backup,
differential database backup, transaction log backup, filegroup backup. Check
out the BACKUP and RESTORE commands in SQL Server books online. Be
prepared to write the commands in your interview. Books online also has
information on detailed backup/restore architecture and when one should go for
a particular kind of backup.

14. What is database replication? What are the different types of replication
you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the
same or different servers. SQL Server supports the following types of replication
scenarios:

o Snapshot replication

o Transactional replication (with immediate updating subscribers, with queued


updating subscribers)

o Merge replication

See SQL Server books online for indepth coverage on replication. Be prepared to
explain how different replication agents function, what are the main system
tables used in replication etc.

15. How to determine the service pack currently installed on SQL Server?
The global variable @@Version stores the build number of the sqlservr.exe,
which is used to determine the service pack installed. To know more about this
process visit

What are cursors? Explain different types of cursors. What are the disadvantages
of cursors? How can you avoid cursors?
Cursors allow row-by-row processing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online


for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in
a network roundtrip, where as a normal SELECT query makes only one
rowundtrip, however large the resultset is. Cursors are also costly because they
require more resources and temporary storage (results in more IO operations).
Furthere, there are restrictions on the SELECT statements that can be used with
some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an
example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike


Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each


employee's salary and update his salary according to the above formula. But the
same can be achieved by multiple update statements or can be combined in a
single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =


CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

Another situation in which developers tend to use cursors: You need to call a
stored procedure when a column in a particular row meets certain condition.
You don't have to use cursors for this. This can be achieved using WHILE loop,
as long as there is a unique key to identify each row.

17. Write down the general syntax for a SELECT statements covering all the
options
Here's the basic syntax: (Also checkout SELECT in books online for advanced
syntax).

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

18. What is a join and explain different types of joins


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.

19. Can you have a nested transaction?


Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN
and @@TRANCOUNT

20. What is an extended stored procedure? Can you instantiate a COM object
by using T-SQL?
An extended stored procedure is a function within a DLL (written in a
programming language like C, C++ using Open Data Services (ODS) API) that
can be called from T-SQL,just the way we call normal stored procedures using
the EXEC statement. See books online to learn how to create extended stored
procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from
T-SQL by using sp_OACreate stored procedure. Also see books online for
sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy.

21. What is the system function to get the current user's user id?
USER_ID().Also check out other system functions like USER_NAME(),
SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(),
HOST_NAME().
22. What are triggers? How many triggers you can have on a table? How to
invoke a trigger on demand?
Triggers are special kind of stored procedures that get executed automatically
when an INSERT, UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one
for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction
is gone, and you could create multiple triggers per each action. But in 7.0 there's
no way to control the order in which the triggers fire. In SQL Server 2000 you
could specify which trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when an


associated action (INSERT, UPDATE, DELETE) happens on the table on which
they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can
also be used to extend the referential integrity checks, but wherever possible, use
constraints for this purpose, instead of triggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation
happens. So in a way, they are called post triggers. But in SQL Server 2000 you
could create pre triggers also. Search SQL Server 2000 books online for INSTEAD
OF triggers.

23. There is a trigger defined for INSERT operations on a table, in an OLTP


system. The trigger is written to instantiate a COM object and pass the newly
insterted rows to it for some custom processing. What do you think of this
implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it
from within a trigger, it slows down the data insertion process. Same is the case
with sending emails from triggers. This scenario can be better implemented by
logging all the necessary data into a separate table, and have a job which
periodically checks this table and does the needful.

24. What is a self join? Explain it with an example


Self join is just like any other join, except that two instances of the same table will
be joined in the query. Here is an example: Employees table which contains rows
for normal employees as well as managers. So, to find out the managers of all the
employees, you need a self join.
CREATE TABLE emp
(
empid int,
mgrid int,
empname char(10)
)

INSERT emp SELECT 1,2,'Vyas'


INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]


FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid
Here's an advanced query using a LEFT OUTER JOIN that even returns the
employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager')


[Manager]
FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid

Java swings:

Java Swing is a GUI toolkit for Java. Swing is one part of the Java Foundation
Classes (JFC). Swing includes graphical user interface (GUI) widgets such as text
boxes, buttons, split-panes, and tables.

Swing widgets provide more sophisticated GUI components than the


earlier Abstract Window Toolkit. Since they are written in pure Java, they run the
same on all platforms, unlike the AWT which is tied to the underlying platform's
windowing system. Swing supports pluggable look and feel – not by using the
native platform's facilities, but by roughly emulating them. This means you can
get any supported look and feel on any platform. The disadvantage of
lightweight components is possibly slower execution. The advantage is uniform
behavior on all platforms.

History

The Internet Foundation Classes (IFC) were a graphics library for Java originally
developed by Netscape Communications Corporation and first released on Dec
16, 1996.

On April 2, 1996, Sun Microsystems and Netscape Communications Corporation


announced their intention to combine IFC with other technologies to form the
Java Foundation Classes. In addition to the components originally provided by
IFC, Swing introduced a mechanism that allowed the look and feel of every
component in an application to be altered without making substantial changes to
the application code. The introduction of support for a pluggable look and feel
allowed Swing components to emulate the appearance of native components
while still retaining the benefits of platform independence. This feature also
makes it easy to have an individual application's appearance look very different
from other native programs.

Originally distributed as a separately downloadable library, Swing has


been included as part of the Java Standard Edition since release 1.2. The Swing
classes are contained in the javax.swing package hierarchy.

Architecture

The Swing library makes heavy use of the Model/View/Controller software


design pattern, which attempts to separate the data being viewed from the
method by which it is viewed. Because of this, most Swing components have
associated models (typically as interfaces), and the programmer can use various
default implementations or provide their own. For example, the JTable has a
model called TableModel that describes an interface for how a table would access
tabular data. A default implementation of this operates on a two-dimensional
array.

Swing favors relative layouts (which specify the positional relationships between
components), as opposed to absolute layouts (which specify the exact location
and size of components). The motivation for this is to allow Swing applications
to work and appear visually correct regardless of the underlying systems colors,
fonts, language, sizes or I/O devices. This can make screen design somewhat
difficult and numerous tools have been developed to allow visual designing of
screens.

Swing also uses a publish subscribe event model (as does AWT), where listeners
subscribe to events that are fired by the application (such as pressing a button,
entering text or clicking a checkbox). The model classes typically include, as part
of their interface, methods for attaching listeners (this is the publish aspect of the
event model).

The frequent use of loose coupling within the framework makes Swing
programming somewhat different from higher-level GUI design languages and
4GLs. This is a contributing factor to Swing having such a steep learning curve.

Look and feel

Swing allows one to specialize the look and feel of widgets, by modifying the
default (via runtime parameters), deriving from an existing one, by creating one
from scratch, or, beginning with J2SE 5.0, by using the skinnable Synth Look and
Feel, which is configured with an XML property file. The look and feel can be
changed at runtime, and early demonstrations of Swing would frequently
provide a way to do this.

Relationship to AWT

Since early versions of Java, a portion of the Abstract Windowing Toolkit (AWT)
has provided platform independent APIs for user interface components. In AWT,
each component is rendered and controlled by a native peer component specific
to the underlying windowing system.

By contrast, Swing components are often described as lightweight because they


do not require allocation of native resources in the operating system's
windowing toolkit. The AWT components are referred to as heavyweight
components.

Much of the Swing API is generally a complementary extension of the AWT


rather than a direct replacement. In fact, every Swing lightweight interface
ultimately exists within an AWT heavyweight component because all of the top-
level components in Swing (JApplet, JDialog, JFrame, and JWindow) extend an
AWT top-level container. The core rendering functionality used by Swing to
draw its lightweight components is provided by Java2D, another part of JFC.
However, the use of both lightweight and heavyweight components within the
same window is generally discouraged due to Z-order incompatibilities.

Relationship to SWT

The Standard Widget Toolkit (SWT) is a competing toolkit originally developed


by IBM and now maintained by the Eclipse Foundation. SWT's implementation
has more in common with the heavyweight components of AWT. This confers
benefits such as more accurate fidelity with the underlying native windowing
toolkit, at the cost of an increased exposure to the native resources in the
programming model.

The advent of SWT has given rise to a great deal of division among Java desktop
developers with many strongly favouring either SWT or Swing. A renewed focus
on Swing look and feel fidelity with the native windowing toolkit in the
approaching Java SE 6 release (as of February 2006) is probably a direct result of
this.

Example

The following is a Hello World program using Swing.

import javax.swing.JFrame;
import javax.swing.JLabel;

public final class HelloWorld extends JFrame {


private HelloWorld() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().add(new JLabel("Hello, World!"));
pack();
setLocationRelativeTo(null);
}

public static void main(String[] args) {


new HelloWorld().setVisible(true);
}
}

Applets
A Java applet is an applet delivered in the form of Java bytecode. Java applets
can run in a Web browser using a Java Virtual Machine (JVM), or in Sun's
AppletViewer, a stand alone tool to test applets. Java applets were introduced in
the first version of the Java language in 1995. Java applets are usually written in
the Java programming language but they can also be written in other languages
that compile to Java bytecode such as Jython.

Applets are used to provide interactive features to web applications that


cannot be provided by HTML. Since Java's bytecode is platform independent,
Java applets can be executed by browsers for many platforms, including
Windows, Unix, Mac OS and Linux. There are open source tools like applet2app
which can be used to convert an applet to a stand alone Java
application/windows executable. This has the advantage of running a Java
applet in offline mode without the need for internet browser software.

A Java Servlet is sometimes informally compared to be "like" a server-side


applet, but it is different in its language, functions, and in each of the
characteristics described here about applets.

Technical information

Java applets are executed in a sandbox by most web browsers, preventing them
from accessing local data. The code of the applet is downloaded from a web
server and the browser either embeds the applet into a web page or opens a new
window showing the applet's user interface. The applet can be displayed on the
web page by making use of the deprecated applet HTML element or the
recommended object element. This specifies the applet's source and the applet's
location statistics.

A Java applet extends the class java.applet.Applet, or in the case of a Swing


applet, javax.swing.JApplet. The class must override methods from the applet
class to set up a user interface inside itself (Applet is a descendant of Panel which
is a descendant of Container).

Advantages of applets

A Java applet can have any or all of the following advantages:

* it is simple to make it work on Windows, Mac OS and Linux, i.e. to make it


cross platform
* the same applet can work on "all" installed versions of Java at the same time,
rather than just the latest plug-in version only. However, if an applet requires a
later version of the JRE the client will be forced wait during the large download.
* it runs in a sandbox, so the user does not need to trust the code, so it can work
without security approval
* it is supported by most web browsers
* it will cache in most web browsers, so will be quick to load when returning to a
web page
* it can have full access to the machine it is running on if the user agrees
* it can improve with use: after a first applet is run, the JVM is already running
and starts quickly, benefiting regular users of Java
* it can run at a comparable (but generally slower) speed to other compiled
languages such as C++
* it can be a real time application
* it can move the work from the server to the client, making a web solution more
scalable with the number of users/clients

Disadvantages of applets

A Java applet is open to any of the following disadvantages:

* it requires the Java plug-in, which isn't available by default on all web browsers
* it can't start up until the Java Virtual Machine is running, and this may have
significant startup time the first time it is used
* if it is uncached, it must be downloaded (usually over the internet), and this
takes time
* it is considered more difficult to build and design a good user interface with
applets than with HTML-based technologies
* if untrusted, it has severely limited access to the user's system - in particular
having no direct access to the client's disc or clipboard
* some organizations only allow software installed by the administrators. As a
result, many users cannot view applets by default.
* applets may require a specific JRE.

Compatibility issues

Sun has made a considerable effort to ensure compatibility is maintained


between Java versions as they evolve. For example, Microsoft's Internet Explorer,
the most popular web browser since the late 1990s, used to ship with Microsoft's
own JVM as the default. The MSJVM had some extra non-Java features added
which, if used, would prevent MSJVM applets from running on Sun's Java (but
not the other way round). Sun sued for breach of trademark, as the point of Java
was that there should be no proprietary extensions and that code should work
everywhere. Development of MSJVM was frozen by a legal settlement, leaving
many users with an extremely outdated Java virtual machine. Later, in October
2001, MS stopped including Java with Windows, and for some years it has been
left to the computer manufacturers to ship Java independently of the OS. Most
new machines now ship with official Sun Java.

Some browsers (notably Firefox) do not do a good job of handling height=100%


on applets which makes it difficult to make an applet fill most of the browser
window (Javascript can, with difficulty, be used for this). Having the applet
create its own main window is not a good solution either, as this leads to a large
chance of the applet getting terminated unintentionally and leaves the browser
window as a largely useless extra window.

Alternatives

Alternative technologies exist (for example, DHTML and Flash) that satisfy some
of the scope of what is possible with an applet.

Another alternative to applets for client side Java is Java Web Start, which runs
outside the browser. In addition to the features available to applets, a simple
permissions box can give Java Web Start programs read and/or write access to
specified files stored on the client, and to the client's clipboard.

You might also like