Posts

Showing posts from June, 2012

Problems on Bit Manipulations

Check if two numbers have opposite sign We can use the operation if    (x ^ y) < 0     where x and y are non zero numbers {  True   --- if numbers of opposite sign {  False  --- if numbers of same sign int   x=-10,y=2; System.out .println(((x ^ y) < 0)); Output :- False Check if number is power of 2 We can use    x & (x - 1)) == 0     True   --- if numbers is a power of 2                                  False  --- if numbers is not a power of 2 int  x=16; System.out.println((x & (x - 1))==0); Output :- True More bitwise tricks x&(x-1)           :---------------- Returns number x with the lowest bit set off x ^ ( x & (x-1 )   :----------------  Returns the lowest bit of a number x x & 1<<n           :----------------   Returns 1<<n if the n-th bit is set in x x | 1<<n           :----------------   Returns the number x with the n-th bit set x ^ 1<<n           :----------------   Toggles the state

Immutability in java

In Java, Object can be of two types :- Mutable Immutable Mutable objects are the ones whose state can be changes during its lifetime. This is in contrast with Immutable objects , whose state cannot be changed once created. We have many classes in Java which provide immutable objects like String, Integer etc. In this post, I will discuss the immutability in detail, with its features and where can we use this. In basic terms, Immutable objects are the ones, whose state cannot be changed.e.g Integer i = new Integer(10) ; The Integer class provides us no method which can change the state/value of i. So we say Integer is an immutable class & object i is an immutable object. We have many benefits for it: - They are good candidates to cache :- Since immutable objects do not change their state, we can share or cache them and retrieve them in future, without copying and cloning the object. Solid keys :- Immutable objects makes the best keys for Hash classes. HashCode()