Sunday, September 11, 2011

In how many ways we can create an object? Explain with example.

1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
3. Using clone()The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
5. Using class loaderone more is through creation of object using classloader 
like

this.getClass().getClassLoader().loadClass(”com.amar.myobject”).newInstance();
Now you know how to create an object. But its advised to create objects only when it is necessary to do so.

Why is it that a java class implements multiple interfaces but will extend only one class

Reason:
Diamond Problem
In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?

So in java it is restricted to multiple inheritance through interface 


Java Interview questions: Write a String Reverser (and use Recursion!)

Thinking about this myself, I found some answers on how to reverse a String in Java. The answer the candidate gives is a good way to see how he thinks. You could combine this question with one about interfaces and ask for a reverser interface:
public interface Reverser {
  public String reverse(String str);
}
The best implementation in Java is to use the reverse method of the StringBuffer class in the JDK. It’s fast, efficient and knows how to handle unicode surrogate pairs, something most other solutions ignore.
public class JdkReverser implements Reverser {
       public String reverse(String str) {
            if ((null == str) || (str.length() <= 1)) {
                return str;
            }
            return new StringBuffer(str).reverse().toString();
        }
}
Not only is the chosen implementation interesting as an answer, but also does the candidate reuse the JDK or not or does he tell you at least "there has to be something in the JDK". Which is quite as good, because googling in reality will help him find the JDK solution. You don't want developers to implement everything themselves.

Handling problems

Ask him where the bug is in this code, even if there is none. Or how his code can go wrong. His answers can lead into a discussion about how to handle a null value
  • return null
  • return ""
  • throw NullPointerException
  • throw IllegalArgumentException
and the merits of every solution. The second discussion point is how to optimize the solution, like returning the string itself for "" and every one length string (which is a reversal of itself already).

Recursion

Then ask the candidate to write a recursive solution of the reversal problem (which is the most beautiful but least usable one).
        public String reverse(String str) {
            if ((null == str) || (str.length()  <= 1)) {
                return str;
            }
            return reverse(str.substring(1)) + str.charAt(0);
        }
Some developers can't handle recursion in their head. Most candidates will need some time and some help, but actually get to a solution. Those that can't handle several stages of recursion in their head probably can't handle complex problems or several layers in their head either.
You can ask them about the efficiency of the recursive solution, ask about Tail Recursion, ask about the ineffeciency of the "+" operation for Strings, how to handle that, about why Strings are immutable (most of the time at least) and ask the candidate how many String objects are created for reversing "Stephan" with his recursive solution. When discussing this one of my developers said "Easy", he was doing Lisp at the university the whole time, which I didn't know until then, excellent news!
Ask where the stop condition is in the above code to end the recursion.

More solutions

Some more solutions, one with swapping a StringBuffer in place:
        public String reverse(String str) {
            if ((null == str) || (str.length()  <= 1 )) {
                return str;
            }
            StringBuffer result = new StringBuffer(str);
            for (int i = 0; i < (str.length() / 2); i++) {
                int swapIndex = str.length() - 1 - i;
                char swap = result.charAt(swapIndex);
                result.setCharAt(swapIndex, result.charAt(i));
                result.setCharAt(i, swap);
            }
            return result.toString();
        }
One with swapping an array:
        public String reverse(String str) {
            if ((null == str) || (str.length() <= 1)) {
                return str;
            }
            char[] chars = str.toCharArray();
            int right = chars.length - 1;
            for (int left = 0; left < right; left++) {
                char swap = chars[left];
                chars[left] = chars[right];
                chars[right--] = swap;
            }
            return new String(chars);
        }
and one with appending to a StringBuffer:
        public String reverse(String str) {
            if ((null == str) || (str.length() <= 1)) {
                return str;
            }
            StringBuffer reverse = new StringBuffer(str.length());
            for (int i = str.length() - 1; i >= 0; i--) {
              reverse.append(str.charAt(i));
            }
            return reverse.toString();
        }
    }
this involves  XOR swapping solution.

Friday, September 2, 2011

Legal overridden method access

Casting in Java

Arithmetic Promotion

Arithmetic promotion happens when narrower types need to be promoted to wider types in order to make sense in an operation among other wider types.

Basic rules for binary operators and most of the unary operators:

* All arithmetic expressions are promoted to the wider of the operands.
* The promotion is at least to int, even if no int operand appears.

These rules don't apply to the unary operators: ++ and -- and assignment operators.

Example #1:

byte x = 1;

x++; // Ok. x is now equal to 2.

x = x + 1; // Error. Expression x + 1 is promoted to int.

Example #2:

byte a = 1;

byte x = 23;

x <<= a; // Ok. x is now equal to 46.

x = x << a; // Error. Expression x << a is promoted to int.

Example #3:

char a = 5;

short x = 3;

x *= a; // Ok. x is now equal to 15.

x = x * a; // Error. Expression x = x * a is promoted to int.

Example #4:

byte a = 15;

a = -a; // Error. -a is promoted to int.

a = ~a; // Error. ~a is promoted to int.

Example #5:

float a = 1.0f;

int b = 15;

int x = a * b; // Error. Expression is promoted to float.

int x = (int)(a*b); // Ok. We cast the float result back to int. 

Primitives and Casting

Casting means explicitly telling Java to make a conversion. A casting operation may widen or narrow its argument. To cast a value, you need to precede it with the name of the desired type enclosed within parentheses:

byte x = 15;

int r = (int)(x * 3);

Booleans cannot be casted. Don't bother with them, stuff like this doesn't work:

byte a = 1;

boolean status = a;

Narrowing runs the risk of loosing information, in fact, many times you know that you are going to loose information and it is important to know which part information is going to be loosen and naturally, what information will be kept.

i=i++ produces the output "0″ instead of "1″.



The code
int i = 0;
i = i++;
System.out.println(i);
produces the output "0″ instead of "1″.



because:


"i = i++" roughly translates to
int oldValue = i;
i = i + 1;
i = oldValue;

why is that in many languages including java array indices begin with Zero


A  advantage of zero-based array indexes is that this can improve efficiency under certain circumstances. To illustrate, suppose a is the memory address of the first element of an array, and i is the index of the desired element. In this fairly typical scenario, it is quite common to want the address of the desired element. If the index numbers count from 1, the desired address is computed by this expression:
a + s \times (i-1) \,\!
where s is the size of each element. In contrast, if the index numbers count from 0, the expression becomes this:
a + s \times i. \,\!
This simpler expression can be more efficient to compute in certain situations.