Wednesday, 19 November 2008


There are two type of cryptography
1. Symmetric
2. Asymmetric (Public key encryption)

Two major algorthims are
1. Data Encryption Standard (DES)
2. Advanced Encryption Standard (AES)

Main Components of Symmetric Cryptography
  1. Plaintext (P): The original message 
  2. Encryption algorithm (EA):  Performs a complex combination of substitutions/transpositions
  3. Secret Key (K): Controls substitutions/transpositions of plaintext
  4. Ciphertext (C): The scrambled message C = EA(P,K)
  5. Decryption algorithm (DA): Retrieves the original message P = DA(C, K)

Two general ways of attacking symmetric algorithms:
1. Cryptanalysis
  • Relies on some knowledge of the algorithm, P, or even sample P-C pairs
  • Uses algorithms characteristics (weaknesses) to deduce P or K
2. Brute-force
  • Uses every possible K on C until P is obtained
  • On average, half of all possible keys must be tried before success

Asymetric  (Public key encryption and Digital Signature)

First proposed by Diffie and Hellman in the late 70s
Based on mathematical operations and not on simple bit operations
It is asymmetric, i.e., there is a public key (Kpub) and a private key (Kpri)
Entities advertise their Kpub in yellow pages but keep their Kpri secret
P = Plaintext and C = Ciphertext
The encryption and decryption algorithms E are identical
The public and private keys are different but related; either of the two can be used for encryption, with the other used for decryption.
It is computationally infeasible to determine the decryption key given only the encryption key and the knowledge of the encryption algorithm

Main mathematical properties:
1. C = E (P, Kpub) and P = E (C, Kpri)
2. C = E (P, Kpri) and P = E (C, Kpub)
Data Communications and Networking

RSA was first developed by MIT scientists Rivest, Shamir and Adleman in 1977
It is the industry standard for public-key encryption
A block cipher where P and C are integers between 0 and n-1 for some n
The basic idea:
C = Pe mod n
P = Cd mod n = (Pe)d = Ped mod n

Sender and receiver know n and e but only the receiver knows d
The keys are:
Kpub = {e, n}
Kpri = {d, n}
General requirements:
It's possible to find e, d and n such that Ped = P mod n for P <>
It's easy to calculate Pe and Cd for P <>
It's computationally infeasible to determine d given e and n

Tuesday, 11 November 2008

Servlet, JSP

1. What are methods of Servlet and Why the servlet has init() method?Servlet is Basic interface that contains these methods
  1. init(ServletConfig)
  2. service(ServletRequest, ServletResponse)
  3. destroy()
  4. getServletConfig()
  5. getServletInfo()

Then implemented abstract classes are GenericServlet and HttpServlet.
Now constructor can not be define in interface, but init can have as skeleton in interface,
so any servlet using the interface knows that what need to be override to initialize a servlet.

Q. which pattern is this? Templating pattern

2. What is necessary to override init() method of Servlet?
There are no necessary conditions to override this particular method. In case you are overridding init(ServletConfig config), then make sure to call super.init(config).

3. Context Object pattern
A context object encapsulates web server specific HTTP information in more general and portable
form. It is used when:
  1. you have components and services that need access to the system information.You want to decouple application components and services from the protocol specifics of system information.
  2. you want to expose only relevant APIs within a context.
  3. Use a context object to encapsulate state in a protocol-independent way to be shared throughout your application.
4. Life cycle of servlet and jsp
Servlet : init(), service(), destroy()
JSP: translation, and above all

5. Difference between in static and dynamic include
  1. The syntax for static include is and the syntax for dynamic include is
  2. Static include is an inline inclusion. i.e., the contents of the file will be included at translation phase. It’s something like a copy and paste. In case of dynamic include the response of the file will be included to the original response at runtime. The file will be processed separately and only the response will become the part of the original files’ response.
  3. Static include cannot have a dynamic filename. This is because the servlet container needs the files for inclusion, at translation phase itself. 
  4. Static include cannot accept a parameter dynamic can.
  5. Static includes are faster than dynamic includes.
  6. In case if the resource lost occurs, container will throw 500(Internal Server Error) for static, though 404(Page Not Found Error) for dynamic include

6. Difference between forward and sendRedirect
  1. When you invoke a forward request, the request is sent to another resource on the server, without the client being informed. This process occurs completely within the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. 
  2. In case of sendRedirect browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. 
  3. Redirect is slower than forward
  4. forward is method of RequestDespatcher and sendRedirect is of request 
7. Inversion Of Control (IoC) and Dependency Injection (DI) are concepts generally associated with the Spring Framework.  The easiest way to think of Inversion Of Control is what Rod Johnson (founder of the Spring framework) calls the Hollywood Principal, "don't call us we'll call you:.  IoC uses interfaces to acquire and release resources a prime example being JDBC connections.  This also part of the reason Spring works so well with Object/Relational Mapping (ORM) tools such as Hibernate, iBatis, and TopLink.

DI is a more specific version of IoC.  DI pushes application dependencies at runtime.  DI comes in several flavors in Spring:
    1.  Setter Injection - uses Java Bean setters (and getters) to get dependencies
    2.  Contructor Injection - dependencies come from constructor arguments
    3.  Method Injection - where the container is used to implement dependencies

8. Explain Struts navigation flow

When we deploy our application in the server, at first the container reads the information from web.xml file.Here ActionServlet object will be created and init() of ActionServlet will be called.Here ActionServlet is the backbone to the whole application.
When client send a rewuest using .jsp extension , getters() and reset() of FormBean will be called. When client fill the form and press on submit button, then setters() and validate() will be called.
If the data is not valid ,then the form redirects to another page which is specified in struts-config.xml file. If the data is valid , then only Action class object will be created.

In Action class , have execute() which have return type of ActionForward. We can specify the business logic in Model and provide that object in execute(). After completion of business logic execution , then it forwards to another page ( either success or failure) , whichis specified in struts-config.xml file.
Action classes of struts uses Command pattern and overall as a web flow, it uses MVC pattern.

Tuesday, 4 November 2008

Data structure and algorithms

1. How to reverse a string?
swap the charecters from initial to end and converge till middle point

2. How to reverse a sentence?
Put the words in linked list, and swap the nodes, this way words will also be reversed.
Other thing is,
swap the every charecter of sentence, on each space, swap the word again, sentence will be reversed but words wont

3. How to find the Median/middle of a List.
Traverse with two pointers, single and double, when double points to end, single will be at middle.

4. How to find cycle in the List.
Traverse with two pointers, single and double, at any point of time, double will reverse back and will point to single, means there is cycle, otherwise, stop till single reaches to the end, means no cycle.

5. Given a graph, find the cycle

6. Reversing a linkedlist
Again swap the first elment to last and converge to the middle.

7. Swaping two variables
1. using temp
2. Using arithmetic
  void swap(int &i, int &j) {
       i=i+j;        j=i-j;        i=i-j;    }
 3. XOR method
 void swap(int &i, int &j){
      i = i ^ j;       j = j ^ i;       i = i ^ j; 
8. Finding the merging point of two list
List1 length=L1
List2 length=L2
Start traversing from longer list, traverse till (L1-L2), Now start comparing the values of L1 and L2, after this point merge point is 
equidistant from each List, If equality found means merge point exist otherwise not. 
Mergring point index in Longer list=(L1-L2) + no of nodes required to reach merge point
Merging point index in small list= no of nodes required to reach merge point
9. How to find fibonacci of a number in o(logn) time.
Using these two formula, it can be achieved
F(2n-1) = F(n-1)2 + F(n)2
F(2n) = ( 2 F(n-1) + F(n) ) F(n)
check this link for detail
10. How to find nth max element in an Array.
By the approach of quicksort, choosing pivot at ith posivition make sure that ith max element is the pivot. We need to iterate only n times max to find out.  Other approach could be, after partitioning if n > i, then move ahead with quicksort in right  otherwise in left, and slowly we can converge to the nth index where pivot element will be only one, and of course that will the nth max element.
....??? not complete

Design Patterns

1. Singleton

Possibly the simplest design pattern is the singleton, which is a way to provide one and only one object of a particular type. 
Sample code
final class Singleton {
  private static Singleton s = new Singleton(47);
  private int i;
  private Singleton(int x) { i = x; }
  public static Singleton getReference() {
    return s;
  public int getValue() { return i; }
  public void setValue(int x) { i = x; }
1. Must make all constructors private 2. create at least one constructor to prevent the compiler from synthesizing a default constructor
3. We should protect the class by cloning also, so the final is been used.
Double Checked Locking in Sigleton Pattern
public static Singleton CreateInstance() {    
if(instance == null) 
//first check   {       
// Use a mutex locking mechanism  that suits your system       
if (instance == null) 
//second check       {         
instance = new Singleton();       
return instance;
2. Strategy Pattern: Choosing the algorithm at run time
3. Template Pattern: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Example, all servlets, JSPs, Thread
Some questions
1. Structurally, the difference between Proxy and State is simple: a Proxy has only one implementation, while State has more than one. The application of the patterns is considered (in Design Patterns) to be distinct: Proxy is used to control access to its implementation, while State allows you to change the implementation dynamically.
2. Difference between AbstractFactory and Factory
Abstract Factory:- provide an interface to create a family of related or  dependant classes without specifying their concrete classes. Abstract factory pattern is typically used for giving implementation to specification (eg., jdbc, servlet specifications etc...).

Factory Method :-  another creational pattern, Defines an interface for creating An Object, but let sub class decide which class to instantiate.

Friday, 31 October 2008

Java concepts

4.  JVM with version
version 4 - Autoboxing (wrapping primitive to objects automaticaly) and Unboxing
Version 5 - Generic/Templating, Iterator, You can create array by using triple dot ...
  - static import,  import static 
Version 6 - No Idea yet
Version 7 - Closure(Functions inside functions and functions will have a reference)

7. Serialization (Usages)
1. persistence 
2. copy mechanism
3. communication mechanism

8. Cloning: 
Deep and sallow cloning:

Thought: while doing deep cloning, copy of the object might we can not copy all the objects so easly,  so serilize it and deserilize it
   How to serilize and deserialize and object?
   Sample code:
Contact  myObject = new Contact();
System.out.println("Previous: "+myObject);
ByteArrayOutputStream fos=new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(fos);
byte[] array=fos.toByteArray();
ByteArrayInputStream fis=new ByteArrayInputStream(array);
ObjectInputStream ois = new ObjectInputStream(fis);
Contact myDeserializedObject = (Contact)ois.readObject();
System.out.println("After: "+myDeserializedObject);

9. How to make a class immutable?
1. make all variable private
2. no setter methods
3. in getter method, two things should be there
1. either we return the copy of the class variables
2. or we return a an object of class which is immutable again, like string
4. in constructor also we don't assign class variable directly to passed variables, it should copy the content

Sample questions on String immutability
String s1="abc";
String s2="abc";
s1.equals(s2), true
s1==s2, true
String s3=new String("abc");
s1.equals(s3), true
s1==s3, false

10. Why do we need to extends RuntimeException class?
Answer is consistency in approach, 
There are two basic type of exception, application exception(checked) and system exceptions (unchecked) So when we feel that some exception need not to reach to use, we'd like to wrap that in a system exception. There should be two base Exception classes, one for each and should be use whenever relevent exceptions are thrown. When SQLException is thrown, we wrap it in a custom system exception and throw it, note: checked is been converted in to unchecked.

11. Can we declare a class as static?
Top level calsses can not be declared as static, compiler error.
Inner classes can be, and it act as a static object of outer class. Static inner classes imply that the object of the inner class is not dependent upon the outer class object and can exist indepenently.
Now there are four types of Inner classes.
1. Anonymous: since Anonymous classes have not got proper class declration,     no possibility of making it static
2. Local : Local classes are the same as local variables, local classes aren't allowed to be declared public, protected, private, or static.
3. Member: The member class is the only class that you can declare static. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared. If you want to remove this restriction, you declare the member class a static class.
4. Nested top-level. A nested top-level class is a member classes with a static modifier. A nested top-level class is just like any other top-level class except that it is declared within another class or interface.


Four JDBC driver types.

Type 1: JDBC-ODBC Bridge plus ODBC Driver:
The first type of JDBC driver is the JDBC-ODBC Bridge. It is a driver that provides JDBC access to databases through ODBC drivers. The ODBC driver must be configured on the client for the bridge to work. This driver type is commonly used for prototyping or when there is no JDBC driver available for a particular DBMS.

Type 2: Native-API partly-Java Driver:
The Native to API driver converts JDBC commands to DBMS-specific native calls. This is much like the restriction of Type 1 drivers. The client must have some binary code loaded on its machine. These drivers do have an advantage over Type 1 drivers because they interface directly with the database.

Type 3: JDBC-Net Pure Java Driver:
The JDBC-Net drivers are a three-tier solution. This type of driver translates JDBC calls into a database-independent network protocol that is sent to a middleware server. This server then translates this DBMS-independent protocol into a DBMS-specific protocol, which is sent
to a particular database. The results are then routed back through the middleware server and sent back to the client. This type of solution makes it possible to implement a pure Java client. It also makes it possible to swap databases without affecting the client.

Type 4: Native-Protocol Pur Java Driver
These are pure Java drivers that communicate directly with the vendor’s database. They do this by converting JDBC commands directly into the database engine’s native protocol. This driver has no additional translation or middleware layer, which improves performance tremendously.

1. Is there any limitation for no of statments executed with in batchupdate?

No, any number of statements we can write in the batch update but all the updates only means (insert,delete,update) not select

2. What happens when we execute "Class.forname("Driver class name");"

By the end of the execution of Class.forName("Driver
class"); the driver class should be loaded into the memory
but also
1. The driver class should be initialized
2. Should be registered with the driver manager class

The above two operations are not done by forName() . So a pure Static() block is defined in which the above two tasks are manipulated and by which we are able to get connection, immediately after loading the driver class without writing any code to initialize the driver class.

3. What are the Statements in JDBC?

1. Statement: Each time you fire a query it compile and executes and returns the result set
2. PreparedStatement: It parses, compile and optimize the query and keep it, next time when query fired, it picks the compiled query and excute. Also you send dynamic sql statements.
3. Callable Statement: To execute stored procedure like pl/sql

Database concepts

1. Triggers
In a DBMS, a trigger is a SQL procedure that initiates an action (i.e., fires an action) when an event (INSERT, DELETE or UPDATE) occurs. Since triggers are event-driven specialized procedures, they are stored in and managed by the DBMS. 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 are used to maintain the referential integrity of data by changing the data in a systematic fashion.

2. Index Covering
A nonclustered index that includes (or covers) all columns used in a query is called a covering index. Index covering means that “Data can be found only using indexes, without touching the tables”.


At the very first JOIN means catesian product of two tables and join can take some codition to filter out the results.
As example consider two table and a sample query
TableA(id, name)
TableB(id, address)

select * from TableA ta $1 TableB tb on

1. if $1=INNER JOIN
JOIN is equivalent to INNER JOIN
Records will be picked up if

Records will be picked up, if union

Records will be picked up, for union

Records will be picked up, for because their column name is same in both tables.
The NATURAL JOIN keyword specifies that the attributes whose values will be matched between the two tables are those with matching names.

Records will be picked up, without any codition, Means its a INNER JOIN without comparision check.

A full outer join combines the results of both left and right outer joins

An INNER JOIN of own table


 Cursors are supported inside stored procedures and functions and triggers. The syntax is as in embedded SQL. Cursors in MySQL have these properties:

    * Asensitive: The server may or may not make a copy of its result table
    * Read only: Not updatable
    * Non-scrollable: Can be traversed only in one direction and cannot skip rows


7. How to quantize data in Database
database are quantified , by the size of the directory that
hold the database , and the number of entry on each tables

8. What is a “constraint”?
A constraint allows you to apply simple referential integrity checks to a table.

There are four primary types of constraints that are currently supported by SQL Server:

PRIMARY/UNIQUE - enforces uniqueness of a particular table column.
DEFAULT - specifies a default value for a column in case an insert operation does not provide one.
FOREIGN KEY - validates that every value in a column exists in a column of another table.
CHECK - checks that every value stored in a column is in some specified list
Each type of constraint performs a specific type of action.

9. What action do you have to perform before retrieving data from the next result set of a stored procedure?
Move the cursor down one row from its current position. A ResultSet cursor is initially positioned before the first row.

10. What are two methods of retrieving SQL?

11. What does the term unnormalized relation refer to? How did the normal forms develop historically from first normal form up to Boyc-Codd normal form?
Unnormalized relation will contain update,insert,deletion anamolies. 1nf will remove repeating colums. 2nf will remove subsets of data. In 2nf every non-key attribute should depend on entire primary key
In 3nf, all columns should depend directly upon primary key and transitive dependency should be removed(a->b b->c c->a).
In 4nf, multivalued dependancy should be removed.
In BCNF, every determinant should be a candidate key.