Saturday, March 26, 2011

recursion to iterative

f(){

if( condition = false)
return;

f();
g()
}

change to iterative
f(){
while(condition = true){
g();
}
}

powerSet -- binary approach


The binary approach just means you're considering each element of the original set(e) as a bit value of a binary number. So if you have an original set of four elements(A, B, C, D) you would consider each one a bit value.

A - 00000001
B - 00000010
C - 00000100
D - 00001000

The size of a power set is calculated by 2^N of the original set. So in this case the size of the power set will be 2^4 or 16. This means that you must create sixteen elements for your power set with binary values starting at 0 and ending at 15 in binary. For each binary value you would add the elements of the original set which have similar bits.

Example:

00000000 - (O) - {Empty Set}
00000001 - (1) - {A}
00000010 - (2) - {B}
00000011 - (3) - {A, B}
00000100 - (4) - {C}
00000101 - (5) - {A,C}
00000111 - (6) - {A,B,C}

collection of technical interview questions

http://www.scribd.com/doc/7691861/A-collection-of-technical-interview-questions

Thursday, March 24, 2011

How do you test a large amount of data

1. check if there is specification of the data to see if you can narrow down the format/definition of the data so you can run your program with no/little error.
2. write your code to write in the log when running into exception of the specification.
3. run your test over PART of the data until there is no exception thrown.
4. estimate based on 2 number of errors/exception you might see in production.
5. later on, you will be finding rare exceptions that might only occur a couple of times in the input. Just solve these by hand

if there is no spec, try to see if you can normalize the data

Monday, March 14, 2011

String/StringBuffer/StringBuilder

http://www.java-tips.org/java-se-tips/java.lang/difference-between-string-stringbuffer-and-stringbu.html

String is immutable whereas StringBuffer and StringBuilder can change their values.

The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among String, StringBuffer and StringBuilder

  1. If your text is not going to change use a string Class because a String object is immutable.
  2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
  3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

Friday, March 11, 2011

can a class be declared static

http://www.javaworld.com/javaqa/1999-08/01-qa-static2.html

There are 2 types of classes.
Top-level class, and Inner class.

there are 4 types Inner classes:
1. Anonymous
2. local class--it is like local variables. local classes aren't allowed to be declared public, protected, private, or static.
3. Member class : this is the only one you can declare static
class TopLevelClass{

class MemberClass
}
4. Nested top-level

class TopLevelClass{

static class MemberClass
}

new TopLevelClass.MemberClass

Basic Algorithm Code

http://algs4.cs.princeton.edu/code/

Thursday, March 10, 2011

Why use Singleton over Static classes?

http://my.opera.com/zomg/blog/2007/09/17/singleton-pattern-vs-static-classes

If you want a simple class that's accessible from everywhere in your code, you could easily use a static class to achieve this.

The singleton does have some advantages though...


With Singleton, you can keep track of who's using it easily. This is because you need to call the getInstance() or whatever method which returns an instance of the class.

Also, because of the above, you can control the amount of actual instances. In some special cases, it might be useful to have multiple instances of the singleton class, for example for load balancing.


You can also give a singleton some parameters. When working with static classes, you may need to pass a lot of parameters to the methods of the class because you aren't "constructing" it. This can, however, be avoided by using a method in the static class that saves the parameters and calling the method you want after that which is pretty much equal to first calling the singleton's getInstance with your parameters and then calling its method.


Singleton also gives a reference/pointer to the class instance. You can then pass this reference as a parameter for some other function for example. If you were using static classes, the other function would have to use the class statically too and if you ever needed to change the behavior, you would need to rewrite parts of that function too instead of just having the first one pass a different class as the parameter.

There's also an another side to the reference thing. If you use the reference in your class and decide that you won't need a singleton anymore, but a normal class, you will just need to change the behavior of the class itself and perhaps replace the line which gets an instance of it to constructing a new one or such. If you were using a static class, you would have to rewrite a lot of the code to use the new reference to the class instead of the static class name. A singleton class should also work almost out of the box as a normal class too. If you had a static class and wanted to convert it to a normal one, you would have to rewrite many parts of it.


You can't extend static classes, but singletons you can. Except it doesn't work very well in PHP due to some issues with static method inheritance, but it's not the only language in the world and it can be done but slightly hackily.

Wednesday, March 9, 2011

Deep Copy and Shallow copy

http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/

Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy

clone() method in Object is protected.

to overwrite clone(), you must implement Cloneable marker interface or else you will get CloneNotSupportedException.

deep copy the copied object contains some other object its references are copied recursively . be careful with cyclic.
If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.

Thursday, March 3, 2011

Thread Safety

1 .All threads inside a Java virtual machine (JVM) share the same heap and method area
2. Because multithreading is built into Java, it is possible that any class you design eventually may be used concurrently by multiple threads.

Given the architecture of the JVM, you need only be concerned with instance and class variables when you worry about thread safety. Because all threads share the same heap, and the heap is where all instance variables are stored,

You needn't worry about multithreaded access to local variables, method parameters, and return values, because these variables reside on the Java stack. In the JVM, each thread is awarded its own Java stack. No thread can see or use any local variables, return values, or parameters belonging to another thread.

Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately.

Three ways to make an object thread-
Synchronize critical sections
public void setColor(int r, int g, int b) {
checkRGBVals(r, g, b);
synchronized (this) {
this.a = r
this.b = g
}
}

public synchronized void invert() {
r = 255 - r;
g = 255 - g;
b = 255 - b;
}

Make it immutable

public RGBColor invert() {
RGBColor retVal = new RGBColor(255 - r,
255 - g, 255 - b);
return retVal;
}

Use a thread-safe wrapper

http://www.artima.com/designtechniques/threadsafety7.html

The third approach to making an object thread-safe is to embed that object in a thread-safe wrapper object. In this approach you leave the original class (which isn't thread-safe) unchanged and create a separate class that is thread-safe.

-------------
thread safety may involve a performance penalty
Synchronized method invocations generally are going to be slower than non-synchronized method invocations.

Synchronized method invocations generally are going to be slower than non-synchronized method invocations.

Unnecessary synchronized method invocations (and synchronized blocks) can cause unnecessary blocking and unblocking of threads, which can hurt performance.

Immutable objects tend to be instantiated more often, leading to greater numbers of often short-lived objects that can increase the work of the garbage collector.

Synchronization gives rise to the possibility of deadlock, a severe performance problem in which your program appears to hang.

Wednesday, March 2, 2011

How to reduce the number of bugs when coding?

Junit , run code coverage, find bugs tool.

Avoid fancy coding. The more complicated the code, the more likely there's bugs. Usually on modern systems, clearly written code will be fast and small enough.

Use available libraries. The easiest way to not have bugs writing a utility routine is to not write it.

Learn a few formal techniques for the more complicated stuff. If there's complicated conditions, nail them down with pen and paper. Ideally, know some proof techniques. If I can prove code correct, it's almost always good except for big, dumb, obvious bugs that are easy to fix. Obviously, this only goes so far, but sometimes you can formally reason about small but complicated things.

Beyond that, set the highest warning level your compiler offers, and make sure warnings are treated as errors. Bugs often hide in those "erroneous" errors.

  • Don't ignore error codes - e.g. don't assume that you got a valid result, that a file has been successfully created, etc... Because some day, something will happen.
  • Don't assume that your code will never enter some condition and that therefore "it's safe to ignore that condition".
  • Test your code, then have it tested by someone else. I find I'm the worst person to test my own code.
  • Take a break, then re-read your code and see if you "missed the obvious". Often happens to me.
if you're so sure that condition X will never happen... use an assert to make sure that when condition X happens, you'll know about it (through an exception, or logging, or whatever).

I found that if I pass all of the context to a function (or method) that that function needs to do its job, and return the meaningful data that I'm looking for, that my code has become much more robust.

Implicit state is the enemy and in my experience is the #1 source of bugs. This state can be global variables or member variables, but if results are dependent on something that's not passed to the function you're asking for trouble. Clearly it is not feasible to eliminate state, but minimizing it has huge positive effects on program reliability.

Involve your testers as early as you can


http://programmers.stackexchange.com/questions/7927/how-to-reduce-the-number-of-bugs-when-coding