Popular Posts

Thursday, June 30, 2011

Find XpowerY in O(logN)

It will keep on dividing the power by 2.If it is odd divide by 2 and multiply with x
public class RecursiveXpowerY {
public static void main(String[] args) {
int pow = recursiveXpowY(2, 5);
System.out.println(pow);
}
/**
* It finds the value in O(logN)
* @param x
* @param y
* @return
*/
public static int recursiveXpowY(int x, int y) {
if (x == 0)
return 1;
if (y % 2 == 1) {// y is odd
return recursiveXpowY(x * x, y / 2) * x;
} else {
return recursiveXpowY(x * x, y / 2);
}
}
}


How to make Http stateful?

Fundamentally, HTTP as a protocol is stateless. In general, though, a stateless protocol can be made to act as if it were stateful, assuming you've got help from the client. This happens by arranging for the server to send the state (or some representative of the state) to theclient, and for the client to send it back again next time.
                       There are three ways this happens in HTTP. One is cookies, in which case the state is sent and returned in HTTP headers. The second is URL rewriting, in which case the state is sent as part of the response and
returned as part of the request URI. The third is hidden form fields, in which the state is sent to the client as part of the response, and returned to the server as part of a form's data (which can be in the request URI or the POST body, depending on the form's method).
                 To learn more about HTTP as a protocol, see http://www.w3.org/Protocols/



Http status codes : 

1xx: Informational
2xx: Success
3xx: Redirection
4xx: Client Error
5xx: Server Error

Wednesday, June 29, 2011

Interviews Puzzles

You can find good interview puzzles here :

  1.   http://www.techinterview.org/
  2. http://www.techinterviewpuzzles.com
  3. http://www.mytechinterviews.com/

Difference between TRUNCATE, DELETE and DROP commands

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

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

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

Refer : http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

Saturday, June 25, 2011

GCD

public static int getGcd(int a,int b){
int temp;
while(b!=0){
temp = a%b;
a=b;
b=temp;
}
return a;
}
Recursive approach :

public static int getGCDRecursively(int a,int b){
if(b==0) return a;
else if(b>a) return getGCDRecursively(b,a);
else return getGCDRecursively(b, a%b);
}

Co-prime numbers : Two numbers are called relatively prime, or coprime if their greatest common divisor equals 1. For example, 9 and 28 are relatively prime.

Friday, June 24, 2011

Combinations problem

Q : There are 10 friends planning for a movie.There is no guarantee that all people will go for movie.Either one can go or two or.....ten. How many ways they can go?

Ans: It is simple combinations problem.
10C0 + 10C1 +10C2+......_10C9+10C10 = 2powerN - 1;

OR  we can solve in different way.
Assume all people are like bits.Either one can go or cannot go.
each has two possibilities.For all 10 people it is 2powerN.But it includes the case of no one is going.
Final value is 2powerN - 1

Number of rectangles in NxN matrix is Nc2*Nc2(Square is also a rectangle)
Number of squears in NxN matrix is n*(n+1)*(2n+1)/6;
Refer :http://www.teachingideas.co.uk/maths/chess.htm

For N grid chess board,it will have N+1 rows and N+1 columns.Then answer will become (N+1c2) * (N+1c2)

Java FAQ's

Q : What is type erasure in Java?
http://blog.adaptivesoftware.biz/2009/02/what-is-type-erasure-in-java.html


volatile
    Used in field declarations to specify that the variable is modified asynchronously by concurrently running threads. Methods, classes and interfaces thus cannot be declared volatile.

interface
    Used to declare a special type of class that only contains abstract methods, constant (static final) fields and static interfaces. It can later be implemented by classes that declare the interface with the implements keyword.

instanceof
    A binary operator that takes an object reference as its first operand and a class or interface as its second operand and produces a boolean result. The instanceof operator evaluates to true if and only if the runtime type of the object is assignment compatible with the class or interface.

Shallow Copy and Deep Copy :
  http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/
http://www.java-questions.com/Cloning_interview_questions.html
http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=1

Difference b/w getClass and instanceof operators :

There are two substantially different ways of performing the check for type match in an implementation of equals() . A class can allow mixed-type comparison between super- and subclass objects by means of the instanceof operator, or a class can treat objects of different type as non-equal by means of the getClass() test. The examples above illustrated nicely that implementations of equals() using getClass() are generally more robust than those implementations using instanceof .

The instanceof test is correct only for final classes or if at least method equals() is final in a superclass. The latter essentially implies that no subclass must extend the superclass's state, but can only add functionality or fields that are irrelevant for the object's state and behavior, such as transient or static fields.

Implementations using the getClass() test on the other hand always comply to the equals() contract; they are correct and robust. They are, however, semantically very different from implementations that use the instanceof test. Implementations using getClass() do not allow comparison of sub- with superclass objects, not even when the subclass does not add any fields and would not even want to override equals() . Such a "trivial" class extension would for instance be the addition of a debug-print method in a subclass defined for exactly this "trivial" purpose. If the superclass prohibits mixed-type comparison via the getClass() check, then the trivial extension would not be comparable to its superclass. Whether or not this is a problem fully depends on the semantics of the class and the purpose of the extension.

getClass() == o.getClass() will be true only if both objects ( this and o ) belongs to exactly the same class.


Comparable vs Comparator : 
First, you say class is Comparable so for me it indicates that this class is self-comparable, or it is able-to-compare-it-self to some other object. It is self compared to or as it's method says compareTo(Object o).
Second, you say class is Comparator because it is comparing objects of other class. So what it do is to, as it's method says, compare(Object o1, Object o2). Remember that Comparator itself is not compared to anything, it just compare(...)-s two objects of some other class.
Comparable --> able-to-compares-itself compareTo(Object o)
Comparator --> compares two other objects compare(Object o1, Object o2)

-second Comparable is in lang package because it is kinda natural that classes have such a behavior by themselfs and lang package doesn't have to be imported(this is my opinion don't take it as something generally known), and Comparator is in util cause it is kinda part of everyday work which includes Collections Framework that are in the same package... 





Forcing garbage collection : 

Java runtime system performs the garbage collection asynchronously depending on the available resources. When there are no more references to an object, the object is finalized and when the Garbage Collections starts these finalized objects gets collected.
            Sometimes you need to run garbage collector explicitly just before some memory intensive task. You can run garbage collector by this statement.
   System.gc(); 
         Finalization process can also be invoked explicitly using the following statement. After the execution of this statement all the objects those are without reference, are finalized.
   System.runFinalization();



Runtime r = Runtime.getRuntime();
r.gc();
There is no guarantee that it will be invoked immediately


Why is the finalize() method in java.lang.Object “protected”?
Refer : http://stackoverflow.com/questions/2291470/why-is-the-finalize-method-in-java-lang-object-protected

Finalize :

Objects with finalizers (those that have a non-trivial finalize() method) have significant overhead compared to objects without finalizers, and should be used sparingly. Finalizeable objects are both slower to allocate and slower to collect. At allocation time, the JVM must register any finalizeable objects with the garbage collector, and (at least in the HotSpot JVM implementation) finalizeable objects must follow a slower allocation path than most other objects. Similarly, finalizeable objects are slower to collect, too. It takes at least two garbage collection cycles (in the best case) before a finalizeable object can be reclaimed, and the garbage collector has to do extra work to invoke the finalizer. The result is more time spent allocating and collecting objects and more pressure on the garbage collector, because the memory used by unreachable finalizeable objects is retained longer. Combine that with the fact that finalizers are not guaranteed to run in any predictable timeframe, or even at all, and you can see that there are relatively few situations for which finalization is the right tool to use.
If you must use finalizers, there are a few guidelines you can follow that will help contain the damage. Limit the number of finalizeable objects, which will minimize the number of objects that have to incur the allocation and collection costs of finalization. Organize your classes so that finalizeable objects hold no other data, which will minimize the amount of memory tied up in finalizeable objects after they become unreachable, as there can be a long delay before they are actually reclaimed. In particular, beware when extending finalizeable classes from standard libraries.


Fail-Fast behavior : The iterators of the Collection implementations of the Java runtime throw a ConcurrentModificationException when they detect that another thread has modified the Collection while a thread is iterating over it. Such iterators are generally called fail-fast iterators
Refer : http://java.dzone.com/articles/do-your-iterators-always-fail
Example : http://stackoverflow.com/questions/4479554/why-vector-methods-iterator-and-listiterator-are-fail-fast

CopyOnWriteArrayList : A thread-safe variant of ArrayList in which all mutative operations (addset, and so on) are implemented by making a fresh copy of the underlying array.
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

Iterator in the HashMap is fail-fast while the enumerator for the Hashtable isn't. So this could be a design consideration.

Good collection questions are here : http://www.fromdev.com/2008/05/java-collections-questions.html
Multi threading questions : http://www.fromdev.com/2008/05/java-threading-questions.html


Thread Local :This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via itsget or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

Maximum number of ones in a row of an array

Q:
Given a symmetric array which contains either 1 or 0 as elements.If a row one in a column,all next elements in that row will be ones's
ex: [0,0,0,1,1,1]
 [0,1,1,1,1,1,1]
Find the maximum number of ones which occured in a row
public class MaxNumber {
public static void main(String[] args) {

int[][] a = { { 0, 0, 0, 0, 0, 1 },
{ 0, 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1, 1 },
{ 0, 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1, 1 },
{ 0, 1, 1, 1, 1, 1 }
};
getMaxNumber(a);
}

public static void getMaxNumber(int[][] a) {
int length = a.length;
int max = length - 1;
int i = length - 1;
int j = length - 1;
while (i >= 0 && j >= 0) {
if (a[i][j] == 1)
j--;
else
i--;
}
int l = max - j;
System.out.println("maximum number of ones are : " + l);
}
}

Friday, June 17, 2011

Static in Java

The static variables or static blocks in a class will be initialised before the class gets instantiated. Also, we all know that the static variables are not tied up with the instances. So even if we have the reference as null, the variable s value had already been initalised to "hello". So calling it that way will print the values Inside Method and Hello as the variable call will be made with the class name as they are tied up with the class. If you make the variable non - static, you will get a NPE.
public class staticClass { 
public static void printH(){
System.out.println("entered into static class");
}
}
public class staticTest {
public static void main(String[] args){
staticClass sc = new staticClass();
sc.printH();
staticClass.printH();
sc=null;
sc.printH();
  staticClass scNull = null;
scNull.printH();
}
}
Output :
entered into static class
entered into static class
entered into static class
entered into static class