Tuesday, May 26, 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+” “);
    //Recursive Function
    private static void fibo(int i, int j) {
        System.out.print(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

Saturday, May 16, 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,

Sunday, May 10, 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.

Saturday, May 9, 2009

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?


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.

Monday, May 4, 2009

Java Interview Questions: Collections II

Here are some more interview questions on Collections. Recently, I had an interview in which these were asked. Well, I couldn't answer all of them. Check how many you know.

1. What is the difference between Comparator and Comparable?

Ans. Both interfaces are used to sort a list or a collection of objects. However, to implement a Comparable, a class must implement a single method compareTo(anotherObj). By doing this, you can sort a class accordingly whatever you have implemented in this method, i.e, perhaps only on a single criteria. Only one sort sequence can be created and you have to modify the class whose instances you want to sort. Through Comparable, you can compare the instances of the same class, since the logic is written inside the class itself. “The comparable interface should be used when the current object is to be compared to objects of its type only.”

The Comparator interface gives you the extra feature of sorting your collection in any number of ways. Here also, we have to implement only one method, i.e, compare(objOne,objTwo). Here, many sort sequences can be created. Instead of making changes to the class, you define a separate class from the class whose instances you want to sort. Thus, a Comparator can compare two objects(any objects for that matter) and return the result based on the criteria imposed by the Comparator. “The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn't know how to compare the objects and expects you to give it.”

2. Does a HashMap allow null as a key and value?

Ans. Yes, you can put a null as a key, and values as null as well. Whereas, Hashtable doesn’t allow anything as null, neither a key or a value. The point of allowing a null as key is not clear though.

Java Interview Questions : Collections I


1. What is the difference between the size and capacity of a Vector?

Ans. Vector is a grow-able collection of objects. The size tells us the number of elements actually stored in the vector, while it’s capacity tells us the maximum number of elements that it can store at a given instance of time. Capacity is increased automatically when the Vector is filled up with elements to a threshold level which is determined by it’s load factor.

2. What is the difference between an Iterator and a ListIterator?

Ans. Iterator is an interface which allows you to iterate all the elements in a collection, but only in the forward direction. While, ListIterator extends the Iterator, it has the added functionality of b-directional traversal of the collection.

3. How is a Set different from a List?

Ans. Set is a data structure in which no duplicates are allowed, and also it doesn’t preserve the order of the elements. List, on the other hand, allows duplicate elements to be present, and also maintains the order of the elements.

4. What is the difference between Enumeration and Iterator?

Ans. Both have the same functionality, i.e, traverse through all the elements in a collection. But they are different in only one respect, Enumeration allows you to only traverse and fetch elements from a collection, without any provision of manipulating the collection, i.e, addition, deletion, updation. Using an iterator, you can even manipulate the collection, in addition to traversal and fetching.

5. What are the differences between an ArrayList and a Vector?

Ans. Though the implementations for the both are the same, the Vector is synchronized while an ArrayList isn’t.

6. How will you remove duplicate elements in a List?

Ans. As we already know, a Set cannot contain duplicate elements, you just add the List elements to a Set. the duplicates will not be added.

7. Which data structure is to be used when fast iteration and random access is required?

Ans. ArrayList

8. When should we use LinkedList?

Ans. In LinkedList, new elements are added to the ends, ex, Queues and Stacks. However, you can still add or delete elements in a LinkedList in the middle, but this process eats up a lot of resources in breaking and making the links between two elements. So, when we don’t need any insertion or deletion in between, but only at the ends, we should use LinkedList.

9. What is the use of a hashCode() in Java?

Ans. They are used in certain collection classes where the elements are stored as key/value pairs, such as HashMap, Hashtable, where hashCodes are used for their storage and retrieval.

10. When you want to search an element by it’s index, which of these would you use?

Ans. ArrayList, of course.

Sunday, May 3, 2009

Java Interview Questions : Basics I

Here are some questions that are normally asked in interviews for Java candidates.

1. Which is the default package that is imported even if you don’t specify it explicitly?

Ans. java.lang

2. When you specify import java.package.*, does it import all the sub-packages inside it?

Ans. No, for importing them, you will need to add more import statements such as, import java.package.sub.* etc.

3. What is the concept of a package in Java, why do we need packages?

Ans. This is a feature by which you can manage your classes, and prevent class name collisions. Think of a situation when your application has 1000s of classes. Say, for a bank application, there can be a Credit Card account and a Debit Card Account. You need to have a class for Account. But, you cannot have two different classes with the same name. Putting the two accounts classes in different packages will allow you to have two classes with the same name which exist in different packages.

4. Is it an error to add a package more than once?

Ans. No, neither the compiler or the JVM will report any error. While executing, it will be imported only once, no matter how many times you import a package.

5. What is the difference between the following operations, equals() and == ?

Ans. == will only compare the references, i.e, if they are present in the same memory location, while equals() will compare the contents of the references. But the output of the equals() operator might not be as expected if the equals() method is overwritten in any class. It is imperative that whenever you overwrite the equals() method , you should also override the hashCode() method, if you want your classes to be used by some collection classes.

6. Which is the root class of all Java classes?

Ans. It is the java.lang.Object class.

7. Will there be a problem if the main method is not declared as static?

Ans. You will not get a compile time error, but at run time, it throws an error, “Main method not public”, since the JVM will look for a static main method to execute a program. The main method is the only entry point to a Java program.

8. I have an object of some type, how do I figure out it’s class?

Ans. If you want to get its class name, then 

object.getClass() will return the fully qualified Class name of that object. If you want to check if that object is a type of a specific class, you can use instanceOf keyword which will return a boolean value depending upon the match.

9. Can a constructor of a class be private?

Ans. Yes, but then, you cannot create an instance of such a class directly. This is done in building Singleton classes. Please refer to Singleton design pattern to know more.

10. Can a constructor return a value?

Ans. No, this will give a compiler error. You cannot even return a void.

11. Can a constructor be static?

Ans. No.

12. Are constructors inherited, i.e, can they be overwritten in a sub class?

Ans. No.

13. Can a constructor be declared as “native”?

Ans. No.

14. Can a constructor be synchronized?

Ans. No.

15. In Java, do we have Pass by Value or Pass by Reference?

Ans. Java doesn’t support pass by reference. Everything in Java is Pass by Value.

16. How can we restrict a class from being instantiated directly?

Ans. This can be done by either marking it as “Abstract” or making it’s constructor “private”.

17. What is the difference between J2SDK 1.5 and J2SDK 5?

Ans. No difference, they are the same, but SUN came up with a fancy name. It is widely referred to as “Java 5”.

18. A method doesn’t have an access specifier. Is this OK?

Ans. Yes, this method will now have default access, meaning within that package in which the class is defined.