Monday, May 25, 2009

Java Program: Fibonacci Example

The first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two.

Here is the source code for generating the Fibonacci Series by using Recursion.

public class Fibonacci {
    //Number of Fibonacci numbers to be shown
    static int limit= 10;
    static int count = 0;
    public static void main(String[] args) {       
        System.out.print(0+” “);
        fibo(0,1);
    }
    //Recursive Function
    private static void fibo(int i, int j) {
        count++;
        System.out.print(j+" ");
        if(count==limit)
            return;
        fibo(j,i+j);
    }
}

This piece of code is ready to run. Copy this code into a file called Fibonacci.java, compile it and run. Here is the sample output of the above program. To generate the required number of numbers in the sequence, adjust the value of the integer variable “limit”.

0 1 1 2 3 5 8 13 21 34 55

Friday, May 15, 2009

Java Design Patterns I

Here is a list of the most widely used design patterns in Java. I will write down about the details in my subsequent posts.

1. Creational  Patterns

  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton

2. Structural Patterns

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

3. Behavioural Patterns

  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor

4. J2EE Patterns

  • MVC
  • Business Delegate
  • Composite Entity
  • Data Access Object
  • Front Controller
  • Intercepting Filter
  • Service Locator
  • Transfer Object

Monday, May 11, 2009

Java Interview Questions: Collections III

I am writing down some more questions that could come up during an interview. A large number of questions are asked from the Collections API. But, of-course, questions from collections would sometimes require you to be comfortable with other basic Java fundamentals, like over-ridding, over-loading, hashCode(), equals() etc.

Q1. What are hashcodes used for?

Ans. Hash Codes are used for increasing the performance of large collections. The Hash Code value of an object is used by some collection classes. One might think that hash codes are unique, but there can be situations, where the hash codes of different objects become the same. But you really don’t have to bother about this, since the collection classes those use hash codes, provide for a fail-over implementations for such cases.

Q2. What should we keep in mind while over-riding equals() and hashCode()?

Ans. You should over-ride these methods in such a way that when two objects are equal, the hash codes generated for both of them must be equal.

Q2. Is it required that if two objects are not equal, their hash codes will always be different?

Ans. Not necessarily. Think of a situation like this. When you are generating a hash code for a string based on the characters.

ABC‘s hash code = 6 (Add the numeric values of the alphabets)

BAC in such a situation would also have the same hash code. Though, both the strings are different, their hash codes are the same. This design is ok, since both of them will be put into the same bucket, and still you would be able to find them. But, ensuring that, the hash codes of two different objects are never same, will only improve the performance of hash-tables.

Q3. What is a Marker Interface?

Ans. A marker interface is one which doesn’t have any method definitions. For example, Cloneable or Serializable. They are just empty interface definitions. Now, the question is what is the use of such an interface? Here we go. There is a method in the Object class, clone(), which is used to clone objects. So, we should be able to clone any kind of object anywhere. To prevent this, we have Marker Interfaces. Only if we declare that class as implementing the Cloneable, we can clone the objects of that class, else we will get an exception. Thus, implementing Cloneable class, which is a marker interface, just tags that class as “Hey, You can clone me know”. And the clone() method will not throw any exception. Same is the case with Serializable. If the class is not implementing the Serializable interface, any attempt to write the Object/ or serialize it will fail.

Q4. What are the different Marker Interfaces?

Ans. Cloneable, Serializable, EventListener,

Saturday, May 9, 2009

Java Interview Questions: Basics II

Here are another set of questions asked in interviews that test one’s foundation knowledge or concepts in Java. We read these once and tend to forget. We can only remember these tips when you regularly start using these in your programming. Let’s begin.

Q1. Which of these is thread-safe? “StringBuilder” or “StringBuffer”?

Ans. StringBuffer is synchronised, thus making it slower than the StringBuilder.

Q2. Why a String is immutable in Java?

Ans. By design, Java maintains the strings in a particular way. It has a String constant pool where all the string literals are stored. When a new string is created, it first checks if the literal is already present in the pool. If it finds one, it just returns the reference to the variable instead of creating a new literal in the memory. Thus, a single string literal in the memory can have multiple references. So, if strings weren’t immutable, changing this string literal will also affect the other references which of-course is dangerous and undesired. This is why Strings are immutable. For this reason, the String class is also marked as final so that it’s functionality cannot be over-ridden, and thus the Strings remain as immutable for everyone.

Q3. What is the difference between these two statements?

String s1 = “abc”;    and String s2 = new String(“def”);

Ans. In the first case, “abc” will go into the string constant pool and s1 will refer to it. While in the second statement, since we have mentioned the new keyword, a new string object will be created in the normal(non-pool) memory, and s2 will refer to it. Additionally, the literal “def” will be placed in the pool.

Q4. Why should we prefer not to use Strings when we need to modify it’s value again and again?

Ans. As we just discussed, every string created in the Java, puts the literal in the memory pool. So, even if a literal has no more references to it, it will still be in the memory in an abandoned state. Thus, when constant modification operations are required to be made, at the end, we might have a large number of abandoned string literals in the memory which are of no use. In such cases, we should use StringBuffer or Stringbuilder, which can be modified over and over again without filling up the memory with abandoned literals.

Q5. What is the importance of close() and flush() in file or stream I/O ?

Ans. When we are done with reading or writing, we should always close the Reader or Writer objects, so that the resources could be freed up for others to use. To do this, we should call close() method on those objects.

While writing to a file/stream, some amount of buffering is always carried out, instead of putting the data character by character or byte by byte. So, if you don’t flush the stream, before closing the Writer object, whatever data is in the buffer, will never be written onto the file/stream. So, it is always a good practice to use flush() just before close().

Q6. What are the three principles of OOP?

Ans. Encapsulation, Polymorphism and Inheritance. You would say that everyone knows this. But I was surprised when someone asked me this question. I wasn’t able to remember the word “Encapsulation”. That was really strange!!!!!   :)

Q7. What type of parameter passing does Java support?

Ans. Java supports only “Passing by values”.

Q8. Can I write multiple main methods in a class?

Ans. Yes, you can do that, but there should be one which should be declared “public static void main(String[] args){}”.

Q9. Can constructors be overridden in a sub-class?

Ans. Constructors are not inherited by a sub-class when it extends another class. Thus, there is no question of overriding a constructor.

Q10. Can a constructor have a return type?

Ans. No, if you specify a constructor with a return type, be it void, it won’t be treated as a constructor any more. It will be treated as a normal method of that class, even if the name of the method matches with the class name.

More questions would follow. If you have doubts, please comment and I will try to answer your queries as soon as possible.

Java Interview Questions: Threads I

Q1. Can we call the run() method instead of start() ?

Ans. Yes, we can do that. But, this will not start a new thread. The contents of the run method will be executed just as a method call, in the existing thread. If you want to start a new thread, you should call the start() method only. The start() method will, in turn call the run() after creating a new thread of execution.

Q2. Why is the sleep method static ?

Ans. There are many static methods in the Thread class. They all operate on the current thread, that is, the thread that executes the method. You cannot perform these operations on other threads.

Q3. What are daemon threads?

Ans. Daemon threads are nothing but a very low priority threads. They have no particular role, other than helping the other threads. When only daemon threads remain, then the program exits.

Q4. What is the default priority of a newly created thread?

Ans. NORM_PRIORITY or 5.

Q5. What are the two ways of creating a new thread?

Ans. 1. Extending the Thread class    2. Implementing the runnable interface

Q6. What are the four states associated with a thread?

Ans. new   runnable    blocked    dead

Q7. What happens if we call start() on a thread object which is already started?

Ans. Nothing will happen. A thread can only be started once. After that, even if in a dead state, a thread cannot be re-started. Calling the start method again will cause an exception (IllegalThreadStateException), a kind of RuntimeException.

Q8. What does yield() method do?

Ans. This method makes the current running thread move to runnable, to allow other threads of the same priority get their chance. A yield() call will never send a running thread to waiting/sleep/blocking state. At the most, the current thread will go to runnable thread. But again, if there are no other threads to run, this thread might again be picked up by the scheduler, thus having no superficial effect at all. That is, it is as good as, that the call was never made.

Q9. What does join() call do?

Ans. When it is required that a thread, say A, cannot proceed before the completion of another thread say, B, then we ask the thread A to join B. By doing so, we are telling A, to proceed only when the thread B has finished it’s job.

Q10. Why should we avoid unnecessary Synchronisation?

Ans. Synchronisation prevents concurrent execution. Thus, when a thread is inside a synchronised method, other threads cannot enter that method. While,the main objective of multi-threading is to allow concurrency, synchronisation prevents it. So, only when absolutely necessary, we should use synchronisation.