Popular Posts

Tuesday, March 29, 2011

java faq

    What is a marker interface?
Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. Thejava.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.
When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.

Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.

What are the differences between Interface and Abstract class?
Abstract ClassInterfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden.An interface cannot provide any code at all,just the signature.
In case of abstract class, a class may extend only one abstract class.A Class may implement several interfaces.
An abstract class can have non-abstract methods.All methods of an Interface are abstract.
An abstract class can have instance variables.An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.An Interface visibility must be public (or) none.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
An abstract class can contain constructors .An Interface cannot contain constructors .
Abstract classes are fast.Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.

What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

What is super?
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword. 

What is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.

What is the difference between abstraction and encapsulation?
  • Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
  • Abstraction solves the problem in the design side while Encapsulation is the Implementation.
  • Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.


How are this() and super() used with constructors?
  • Constructors use this to refer to another constructor in the same class with a different parameter list.
  • Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
What are the uses of final method?
There are two reasons for marking a method as final:
  • Disallowing subclasses to change the meaning of the method.
  • Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.

What is static block?
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.

What are static variables?

Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.

What is the difference between Enumeration and Iterator?
EnumerationIterator
Enumeration doesn't have a remove() methodIterator has a remove() method
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objectsCan be abstract, final, native, static, or synchronized

Note: So Enumeration is used whenever we want to make Collection objects as Read-only.

What are the advantages of ArrayList over arrays ?
Some of the advantages ArrayList has over arrays are:
  • It can grow dynamically
  • It provides more powerful insertion and search mechanisms than arrays.
ifference between ArrayList and Vector ?
ArrayListVector
ArrayList is NOT synchronized by default.Vector List is synchronized by default.
ArrayList can use only Iterator to access the elements.Vector list can use Iterator and Enumeration Interface to access the elements.
The ArrayList increases its array size by 50 percent if it runs out of room.A Vector defaults to doubling the size of its array if it runs out of room
ArrayList has no default size.While vector has a default size of 10.



Why insertion and deletion in ArrayList is slow compared to LinkedList ?
  • ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.
  • During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.


How do you decide when to use ArrayList and When to use LinkedList?
If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.

Difference between HashMap and Hashtable ?
HashMapHashtable
HashMap lets you have null values as well as one null key.HashTable  does not allows null values as key and value.
The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know).The enumerator for the Hashtable is not fail-safe.
HashMap is unsynchronized.Hashtable is synchronized.

Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.Hash Set also allows to store Null.
Good article on hash tables : http://softwarelearner.blogspot.in/2011/04/hash-tables.html
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

What Are the different Collection Views That Maps Provide?
Maps Provide Three Collection Views.
  • Key Set - allow a map's contents to be viewed as a set of keys.
  • Values Collection - allow a map's contents to be viewed as a set of values.
  • Entry Set - allow a map's contents to be viewed as a set of key-value mappings.



Which class is the superclass of every class?Object.
Name primitive Java types.
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.



What is the difference between the boolean & operator and the && operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped



What is the difference between declaring a variable and defining a variable?
In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String (”bob”); Or String s = “bob”; are both definitions.



What type of parameter passing does Java support?
In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.



Can an application have multiple classes having main method?
Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.
Can I have multiple main methods in the same class?
We can have multiple overloaded main methods but there can be only one main method with the following signature :
public static void main(String[] args) {}
No the program fails to compile. The compiler says that the main method is already defined in the class.
Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.

What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.


What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Min element in an array

A sorted array has been rotated so that the elements might appear in the order 3 4 5 6 7 1 2. How would you find the minimum element?

Finding the minimum element in an array isn’t a particularly interesting algorithm (you could just iterate through all the elements), nor does it use the information provided (that the array is sorted). It’s unlikely to be useful here.
However, binary search is very applicable. You know that the array is sorted, but rotated. So, it must proceed in an increasing order, then reset and increase again. The minimum element is the “reset” point.

If you compare the first and middle element (3 and 6), you know that the range is still increasing. This means that the reset point must be after the 6 (or, 3 is the minimum element and the array was never rotated). We can continue to apply the lessons from binary search to pinpoint this reset point, by looking for ranges where LEFT > RIGHT. That is, for a particular point, if LEFT < RIGHT, then the range does not contain the reset. If LEFT > RIGHT, then it does.
public class GetMinElement {
public static void main(String[] args) {
int[] a = { 3, 4, 5, 6, 2 };
int pos = getMinimumElementInRotatedArray(a, 0, a.length - 1);
System.out.println(a[pos]);
}

private static int getMinimumElementInRotatedArray(int[] a, int first,
int last) {
int mid;
while (first < last) {
mid = (first + last) / 2;
if (a[mid] > a[last]) {
first = mid + 1;
} else {
last = mid;
}
}
return first;
}
}

Horse Race Problem

 There are 25 horses and the race track only allows 5 horses to race at a given time. Given that there is no stop watch available your task is to determine the fastest 3 horses. Assume that each horses speed is constant in different races, what is the minimum number of races to determine the fastest 3?


Answer=7

The key here is to keep the search space to only those horses which can be the top 3 horses.
Initially all 25 can be the required horses. So divide among groups of 5 and perform the race. Let the result be:
A1 A2 A3 A4 A5
B1 B2 B3 B4 B5
C1 C2 C3 C4 C5
D1 D2 D3 D4 D5
E1 E2 E3 E4 E5

Now perform the race for winners of each group to reduce the search space. Let the result be:

A1 B1 C1 D1 E1
This implies A1 is the best. Also, the search space for top 3 horses reduces to:

A1 A2 A3 B1 B2 C1

Now conduct the last race for A2 A3 B1 B2 C1. Select top 2 from this race which will be overall runner-up and second runner-up.

Total race count = 7.



http://dailybrainteaser.blogspot.com/2011/03/28march.html

Ugly Number

Ugly numbers are numbers whose only prime factors are 2, 3 or 5. First 10 ugly numbers are:

1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...

By convention, 1 is included. Write a program to find and print the first 1000 ugly numbers.

http://tech-queries.blogspot.com/2011/03/ugly-number.html

Maximum Area Rectangle In Histogram

Find the maximum rectangle (in terms of area) under a histogram in linear time. I mean the area of largest rectangle that fits entirely in the Histogram.

http://tech-queries.blogspot.com/2011/03/maximum-area-rectangle-in-histogram.html

Character Combination For Numbers


Question: Suppose you represent every number with a character like
0 –> a, 1 –> b, 2 –> c, ………………24 –> y, 25 –> z

Now given a number, give words combinations for it.

Example: 1234
=> 1-2-3-4, 12-2-4, 1-23-4
=> bcde, mde, bxe

Java code for simple backtracking approach : 
public class CharCombinationWithNumbers {

private static char[] alphabet = "abcdefghijklmnopqrstyuvxyz".toCharArray();

public static void main(String[] args) {
printPossibilities("", "1234");
}

private static void printPossibilities(String partialString, String string) {
if (string == null || string.length() < 1) {
System.out.println(partialString);
return;
}
int digit = Integer.parseInt(string.substring(0, 1));
printPossibilities(partialString + alphabet[digit], string.substring(1));
if (string.length() > 1) {
digit = Integer.parseInt(string.substring(0, 2));
if (digit >= 10 && digit < alphabet.length) {
printPossibilities(partialString + alphabet[digit], string
.substring(2));
}
}
}
}


Refer : http://tech-queries.blogspot.com/2011/03/character-combination-for-numbers.html

Which Loop Is Faster?

A very basic programming puzzle is being asked in programming interviews since last few years. The question is that out of below two lops, which will run faster?

public class FasterLoop {

public static void main(String[] args) {
int k = 0, l = 0, i, j;
for (i = 0, l++; i < 10; i++, k++)
for (j = 0, l++; j < 100; j++, k++);
System.out.println(k + " " + l);
k = 0;
l = 0;
for (i = 0, l++; i < 100; i++, k++)
for (j = 0, l++; j < 10; j++, k++);
System.out.println(k + " " + l);
}
}
  o/p:    1010   11
            1100  101
Refer :http://tech-queries.blogspot.com/2010/09/which-loop-is-faster.html

Number conversions

Convert an roman integer in its decimal equivalent : http://tech-queries.blogspot.com/2010/03/convert-roman-integer-in-decimal.html


Convert IP Address From String To HexaDecimal : http://tech-queries.blogspot.com/2010/03/convert-ip-address-from-string-to-int.html
public static void convertToHexaDecimal(String s) {    
StringTokenizer st = new StringTokenizer(s,".");
System.out.print("0x");
int i = Integer.parseInt(st.nextToken());
System.out.print(Integer.toHexString(i));

i = Integer.parseInt(st.nextToken());
System.out.print(Integer.toHexString(i));

i = Integer.parseInt(st.nextToken());
System.out.print(Integer.toHexString(i));

i = Integer.parseInt(st.nextToken());
System.out.print(Integer.toHexString(i));
}


The letters used in Roman numbers are:
  • I = 1
  • V = 5
  • X = 10
  • L = 50
  • C = 100
  • D = 500
  • M = 1000
Convert Decimal number into roman number :

public class ConvertDecimalToRoman {

public static void main(String[] args) {

long num = 50;
// convert decimal number into roman number
StringBuilder roman = new StringBuilder("");

long count = 0;

if (num >= 1000) {
count = num / 1000;
while (count-- != 0)
roman.append("M");
num %= 1000;
}

if (num >= 500) {
count = num / 500;
while (count-- != 0)
roman.append("D");
num %= 500;
}

if (num >= 100) {
count = num / 100;
while (count-- != 0)
roman.append("L");
num %= 100;
}

if (num >= 50) {
count = num / 50;
while (count-- != 0)
roman.append("L");
num %= 50;
}

if (num >= 10) {
count = num / 10;
while (count-- != 0)
roman.append("X");
num %= 10;
}

if (num >= 5) {
count = num / 5;
while (count-- != 0)
roman.append("V");
num %= 5;
}

while (num != 0) {
roman.append("I");
num--;
}
System.out.println(roman);
}
}