Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

December 29, 2009

Better method to find subarray with largest sum

static int maxSubArray2(int array[], int size)

{
int maxsofar = 0;
int currentmax = 0;
for (int i = 0; i < size; i++)
{
currentmax = (currentmax + array[i] > 0) ? currentmax + array[i]
: 0;
maxsofar = (maxsofar > currentmax) ? maxsofar : currentmax;
}
return maxsofar;

}

Program to find Subarray having maximum sum in a given integer array

public static void findSubarray(int[] arr){
int len = arr.length;
int largest = 0;
int lowerBound = 0;
int upperBound = 0;
for(int i = 0 ; i < len ; i++){

int sum = arr[i];
for(int j = i+1 ; j < len ; j++){
sum += arr[j];
if(sum > largest){
largest = sum;
lowerBound = i;
upperBound = j;
}
}
}
System.out.println("Largest sum is : "+largest );
System.out.println("Largest subarray is between "+arr[lowerBound]+ " and "+arr[upperBound]);

}

Program to find nth power of a given number

public static long findPower(long x , long pow){
if(pow == 1){
return x;
}else if(pow == 0){
return 1;
}else {
return x*findPower(x, --pow);
}
}

December 28, 2009

ex write a program to reverse 20th bit of a 32 bit int

XOR the given number with a number whose 20th digit is one and all other digits are zero. THis will always work :)

XOR : returns true if both the digits are different , false otherwise :)

http://www.vipan.com/htdocs/bitwisehelp.html

Good Prog : Exchanging values with xor

x = x ^ y;
y = x ^ y;
x = x ^ y;

Bitwise operations

Use: Shift left multiplies by 2; shift right divides by 2

y = x << 3; // Assigns 8*x to y.
y = (x << 2) + x; // Assigns 5*x to y.

Bitwise operators

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

The bitwise & operator performs a bitwise AND operation.

The bitwise ^ operator performs a bitwise exclusive OR operation.

The bitwise | operator performs a bitwise inclusive OR operation.

The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard output.


class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
System.out.println(val & bitmask); // prints "2"
}
}

Find max of three numbers using ternary operator

int a = 5;
int b = 10;
int c = 25;

int result = (a > b) ? ((a > c) ? a : c): ((b > c) ? b : c );

System.out.println(result);

Program to rotate a Matrix

public class RotateMatrix {

//~ Methods --------------------------------------------------------------------------------------------------------

/**
* @param args
*/
public static void main(String[] args) {
int[][] mat = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int[][] flipped = rotate(mat);

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {
System.out.print(" " + flipped[i][j]);
}

System.out.println();
}
}

public static int[][] rotate(int[][] inMatrix) {
int[][] outMatrix = new int[3][3];

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {
outMatrix[i][j] = inMatrix[j][i];
}
}

return outMatrix;
}
}

December 27, 2009

Little Endian and Big Endian

Little Endian means that the lower order byte of the number is stored in memory at the lowest address, and the higher order byte is stored at the highest address. That is, the little end comes first.

For example, a 4 byte, 32-bit integer


Byte3 Byte2 Byte1 Byte0


will be arranged in memory as follows:


Base_Address+0 Byte0
Base_Address+1 Byte1
Base_Address+2 Byte2
Base_Address+3 Byte3


Intel processors use "Little Endian" byte order.


"Big Endian" means that the higher order byte of the number is stored in memory at the lowest address, and the lower order byte at the highest address. The big end comes first.


Base_Address+0 Byte3
Base_Address+1 Byte2
Base_Address+2 Byte1
Base_Address+3 Byte0


Motorola, Solaris processors use "Big Endian" byte order.

In "Little Endian" form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way for all formats. They first pick up the lowest order byte at offset 0 and proceed from there. Also, because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple precision mathematic routines are easy to code. In "Big Endian" form, since the high-order byte comes first, the code can test whether the number is positive or negative by looking at the byte at offset zero. Its not required to know how long the number is, nor does the code have to skip over any bytes to find the byte containing the sign information. The numbers are also stored in the order in which they are printed out, so binary to decimal routines are particularly efficient.


Here is some code to determine what is the type of your machine


int num = 1;
if(*(char *)&num == 1)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}



And here is some code to convert from one Endian to another.



int myreversefunc(int num)
{
int byte0, byte1, byte2, byte3;

byte0 = (num & x000000FF) >> 0 ;
byte1 = (num & x0000FF00) >> 8 ;
byte2 = (num & x00FF0000) >> 16 ;
byte3 = (num & xFF000000) >> 24 ;

return((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | (byte3 << 0));
}

http://vijayinterviewquestions.blogspot.com/2007/07/what-little-endian-and-big-endian-how.html

Program to swap first two nodes of a list -> Adobe Question

public void interchangeFirstTwo(){
Node temp = head;
Node next = temp.next;
temp.next = next.next;
next.next = temp;
head = next;
}

Program to swap first and last node of a list -> Adobe Question

public void swapFirstLast(){
Node current = head;
Node previous = null;
while(current.next != null){
previous = current;
current = current.next;
}
Node temp = head;

current.next = temp.next;
previous.next = temp;
temp.next = null;
head = current;

}

Infix to Prefix - Java Program

The only difference in converting Infix to Prefix from converting Infix to Postfix is that we should reverse the input string and use the same logic and again reverse the output. The underlying logic remains the same.
ALGORITHM : Infix to Prefix


STEP 1 : Read the given infix expression into string called infix.

STEP 2 : Reverse the infix string and read one character at a time and perform the following operations :

If the read character is an operand, then add the operand to the prefix string.
If the read character is not an operand, then check
If the stack is not empty and precedence of the top of the
stack operator is higher than the read operator,
then pop the operator from stack and add this
operator to the prefix string.
Else push the operator onto the stack.

STEP 3 : Repeat STEP 2 till all characters are processed from the input string.

STEP 4 : If stack is not empty, then pop the operator from stack and add this operator to the prefix string.

STEP 5 : Repeat STEP 4 till all the operators are popped from the stack.

STEP 6 : Reverse the prefix string and display the result of the given infix expression or the resultant prefix expression stored in a string called prefix from this algorithm.

Program :
import java.util.Stack;

public class InfixToPrefix {

static Stack inputStack;

static String output = "";

public static void main(String[] args) {
String input = "1+2*4/5-7+3/6";
int len = input.length();
char[] charr = new char[len];
for (int i = 0; i < len; i++) {
charr[i] = input.charAt(i);
}

String reverseInput = reverse(input);

System.out.println(infixToPrefix(reverseInput));

}

public static String infixToPrefix(String input) {

inputStack = new Stack();

for (int i = 0; i < input.length(); i++) {
char current = input.charAt(i);
if (current == '+' || current == '-') {
isOperator(current, 1);
} else if (current == '*' || current == '/') {
isOperator(current, 2);
} else {
output += current;
}
}
while (!inputStack.isEmpty()) {
char top = (Character) inputStack.pop();
output += top;
}
output = reverse(output);
return output;
}

public static void isOperator(char c, int prec) {
while (!inputStack.isEmpty()) {
char top = (Character) inputStack.pop();
int topPrec = 0;
if (top == '+' || top == '-') {
topPrec = 1;
} else {
topPrec = 2;
}

if (topPrec >= prec) {
output += top;
} else {
inputStack.push(top);
break;
}

}
inputStack.push(c);

}

public static String reverse(String input) {
int len = input.length();
String reverse = "";
char[] charr = new char[len];
for (int i = 0; i < len; i++) {
charr[i] = input.charAt(i);
}
for (int i = 0; i < len / 2; i++) {
char temp = charr[i];
charr[i] = charr[len - i - 1];
charr[len - i - 1] = temp;
}
for (int j = 0; j < len; j++) {
reverse += charr[j];
}
return reverse;
}
}

Is there a way to find out if the converted postfix expression is valid or not

Yes. We need to associate a rank for each symbol of the expression. The rank of an operator is -1 and the rank of an operand is +1. The total rank of an expression can be determined as follows:
- If an operand is placed in the post fix expression, increment the rank by 1.
- If an operator is placed in the post fix expression, decrement the rank by 1.
At any point of time, while converting an infix expression to a postfix expression, the rank of the expression can be greater than or equal to one. If the rank is anytime less than one, the expression is invalid. Once the entire expression is converted, the rank must be equal to 1. Else the expression is invalid.

Infix to Postfix - Java Program

import java.util.LinkedList;
import java.util.Stack;

public class InfixtoPostfix {

static Stack inputStack;

static String output = "";

public static void main(String[] args) {
String input = "1+2*4/5-7+3/6";

System.out.println(infixToPostfix(input));

}

public static String infixToPostfix(String input) {

inputStack = new Stack();

for (int i = 0; i < input.length(); i++) {
char current = input.charAt(i);
if (current == '+' || current == '-') {
isOperator(current, 1);
} else if (current == '*' || current == '/') {
isOperator(current, 2);
} else {
output += current;
}
}
while(!inputStack.isEmpty()){
char top = (Character) inputStack.pop();
output += top;
}
return output;
}

public static void isOperator(char c, int prec) {
while (!inputStack.isEmpty()) {
char top = (Character) inputStack.pop();
int topPrec = 0;
if (top == '+' || top == '-') {
topPrec = 1;
} else {
topPrec = 2;
}

if (topPrec >= prec) {
output += top;
}else{
inputStack.push(top);
break;
}

}
inputStack.push(c);
}

}

December 25, 2009

Class level and Object level locks -- V.Imp.

Remember what we're talking about is multi-threading. It doesn't matter in which objects we do the invoking of methods, but which threads all those objects are executing in when the invocation is done (and since execution in a single thread is sequential, we cannot invoke the same method twice simultaneously in a single thread, unless we're using recursion).

I think it's easiest to work through this with a simple example. Let's take one class with one synchronized instance method:
view plaincopy to clipboardprint?
public class ClassA {
public synchronized void mymethod() {}
}
and also declare a couple of instances of this class I1 and I2 say. We also have three threads around and running - let's call them T1, T2 and T3.

Now, suppose within thread T1 we invoke I1.mymethod() at some point in time. Then until this invocation returns, T2 and T3 are locked out of calling I1.mymethod(). However, one of those threads may still invoke I2.mymethod() without blocking since that's a different object (albeit of the same class). Once I1.mymethod() returns, any of the threads may again invoke that method on that object. Similarly, once I2.mymethod() returns, any of the threads may invoke that method.

I think you may have understood, but it was unclear when you were referring to different classes instead of instances of the same class. Your example was correct: if we have several different classes, then we can apply the same logic as above if I1 is an instance of ClassA, I2 of ClassB and a third instance I3 of ClassC, but it's probably less obvious to consider the case where they are all of the same class first.

Now, if we make the method static:
view plaincopy to clipboardprint?
public class ClassA {
public static synchronized void mymethod();
}
then the previous explanation will fail since the lock is now a class lock so holds on all static methods of all instances of ClassA simultaneously. An invocation of I1.mymethod() from thread T1 will now lock threads T2 and T3 from calling any occurrences of any static methods on any other instances of ClassA. However, since it's a class lock, it won't block any invocations of static methods from other classes (i.e. classes other than ClassA), nor will it block invocations of instance methods.

http://www.coderanch.com/t/416338/Threads-Synchronization/java/Accesing-two-synchronized-methods

December 15, 2009

What is javaw.exe

The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window. This implies you can't get it to display the version with -version, since there is no console to display it on. Use javaw.exe when you don't want a command prompt window to appear. The javaw.exe launcher will, however, display a dialog box with error information if a launch fails for some reason.

The javaw.exe process is the Java Virtual Machine. It is used by your computer to run programs written in the java programming language. It is also used as part of the Java plugin for Internet Explorer (and/or other browsers). You should leave this process running, unless it is causing problems for your system. If this process is terminated java programs will not work.

Windows Process Description:

The process javaw.exe is a program made by Sun Microsystems, Inc. which works along with Internet Explorer as a Java plug-in. There is a similarity between the process javaw.exe and the program java.exe. The only difference is that the process javaw.exe has no console window when running. If you don't want to see a command prompt window, the process javaw.exe could most likely be used. The javaw.exe is a launcher file that will show a dialog box during times when a failure in launching of a program occurs.

This executable file javaw.exe can sometimes be used as a camouflage by some malware which usually reside on the Windows folder. These fake javaw.exe files are known to cause harmful effects to your system's performance such as system crashes and slow speeds and it is highly recommended that users should constantly check abnormal memory usage of certain files that uses the same file name as this file. It is also highly recommended to run a malware scanning tool to detect unwanted files in your system. The javaw.exe process doesn't consume a large amount of resources.

The javaw.exe process deals with computer network security. This application is also known as the Java Virtual Machine which is used by a computer for it to be able to execute programs that are written using the Java programming language. The process javaw.exe does not only work with Internet Explorer but it is also capable of performing tasks on other web browsers. It is highly recommended that you leave this process running in the background for it to be able to fully perform its designated tasks.

The javaw.exe program automatically starts during Windows boot up process so it is not necessarily recommended that you make a shortcut icon of this program on your desktop. It is also highly advised that you avoid removing the process javaw.exe process from its designated folder for you to be able to maximize the uses of this file and to avoid certain application malfunctions.

ExceptionInInitializerError

public class ExceptionInInitializerError
extends LinkageError

Signals that an unexpected exception has occurred in a static initializer. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.

December 14, 2009

Java is not 100 % OO

SmallTalk is the only lang that is 100% OO.

No. Java is not 100 Pure OOP because of following three reasons:
1) It doesnot support Multiple inheritance.
2) It allows use of primitive data types which are not an objects.
3) It allows static methods to call without creating the instance.

This disobeys OOPs concepts
Java isnt 100 pure OOPS coz if it were then everything should be classes and objects whereas java still has primitive data type which violates the above said statement...SmallTalk is the only 100 pure OOPS language

All about Strings

public class StringTest {
public static void main(String[] args) {
String str1 = new String("Pragya");
String str2 = new String("Pragya");
String str3 = str1;
String str4 = "Sumit";
String str5 = "Sumit";

System.out.println(str1 == str2);
System.out.println(str1 == str3);
System.out.println(str1.equals(str2));
System.out.println(str4 == str5);
System.out.println(str4.equals(str5));

}
}

Output :
false
true
true
true
true

In String class, equals() method has been overridden to compare the value of String, so it compares the String data and not the memory location.

Good Questions (Java)

What are the limitations with regard to Java Reflection in EJB?

In general Java Reflection is allowed in EJB, only those apis which inspect the private or protected variables are disallowed.

How to access a singleton class?

There should be static method which gives the instance of the singleton class. Call that static method which gives you the instance .Once you have instance you can call the methods in that class. The static method which is giving object is take care of single instance of the object.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

In Java collections HashMap or HashSet, to use as a key, will you prefer a mutable object or immutable object? and why do you prefer?

Hash value is used in identifying objects in Hash collections, to be 100% accurate all the time the hash value should not change. So immutable objects are a perfect solution for this.

Is there any advantage in extending Thread class rather than implementing Runnable interface?

when there is a need to run multiple threads with their own instance variables extending threads makes sensible. Wherein implementing runnable makes sense in single execution models.

what are the differences between UDP and TCP?

UDP (user datagram protocol), is a connectionless protocol.
each time you send datagrams, you also need to send the local socket descriptor and the receiving socket’s addressTCP is a connection-oriented protocol. a connection must first be established between the pair of sockets.

While one of the sockets listens for a connection request (server), the other asks for a connection (client).

Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

Int vs Integer which one is mutable and which is immutable?

int is mutable Integer is immutable

Can an interface be declared final? If yes how and if no why?

1. Interfaces cannot be declared final.

2. Interfaces are meant to be implemented,they dont have any code implemented within them.

3. They cannot be instantiated.

In java thread creation models Runnable and Thread, Which one is better why?

By implementing Runnable interface we are free to extend any other class and implement any other interfaces. This gives a strong advantage incase of Runnable interface.

What are the differences between Vector and ArrayList? Which is best to use? ArrayList is faster and also it occupies less memory space whereas vector takes more memory space.

Vector is a synchronized object, while ArrayList is not iterator that are returned by both classes are fail-fast, but the Enumeration returned by Vector are not .

Can you tell some immutable classes in java?

1. The main immutable class is String.

2. Basic numeric classes like Integer, Long, Float, BigInteger and BigDecimal are immutable classes.

Difference between interface and abstract class?

If you know the generic method which you are going to use in all subclasses then implement it in abstract class and leave remaining unknown implementation methods as just declare in the abstract class so the sub classes are going to implement based on their business logic.

More clearly :

Let’s discuss what Interfaces and Abstract Classes are all about to understand the differences between the two more clearly and completely.

Interface: Java Interfaces are equivalent to protocols. They basically represent an agreed-upon behavior to facilitate interaction between unrelated objects. For example, the buttons on a Remote Controller form the interface for outside world to interact with TV. How this interface is implemented by different vendors is not specified and you’re hardly aware of or bothered about how these buttons have been implemented to work internally. Interface is plainly a contract between the producer and the consumer. How the producer implements the exposed behavior is normally not cared by the consumer.

In Java, an Interface is normally a group of methods with empty bodies. You can have constant declarations in a Java Interface as well. A class that implements the interface agrees to the exposed behavior by implementing all the methods of the interface.

interface TVRemoteController{
void power();
void setChannel(int channelNumber);
void upChannel();
void downChannel();
void upVolume();
void downVolume();
……
}

A sample implementation of this interface by a vendor, say Sony:

public class SonyTVRemoteController implements TVRemoteController{
/*…this class can have other methods, properties as well …*/
……
void power(){
//implementation of power() method of the interface
}
void setChannel(int channelNumber){
//implementation of setChannel(int) method of the interface
}
//similarly, implementation of other methods of the interface
……
}

Implementing an interface means the class will support at least the exposed behavior. It can definitely add any number of extra behaviors/properties for its clients. That’s why few Remote Controllers have hell lot of buttons :-)

Abstract Class: In Java, abstract class is a class which has been declared ‘abstract’. By declaring ‘abstract’ we ensure that the class can’t be instantiated. Why to have such a class then? Because, you would not be having implementation of all the methods in that class and you need to leave it to the subclass to decide how to implement them. In this case, there is no point instantiating an incomplete class.

An abstract method is a method which doesn’t have any implementation. If a class has even a single abstract method, then you got to declare the class ‘abstract’. Though, you don’t need to have at least one abstract method to declare a class abstract. You can declare a complete class as ‘abstract’ as well. This practice is seldom used. One possible reason may be that you never want your clients to instantiate your class directly even though you’ve already provided default implementation of all the methods. Strange! Yeah… it is. The designer of such a class may like to provide the default implementation of at least one method just to serve as a template (and not the actual implementation) for the client and thus making the class incomplete. So, a client first needs to subclass and implement the method(s) by overriding them. Now the subclass will be a concrete/complete class. Does it make some sense? Okay… Let me try to give another example. Think of a hypothetical situation, where you need to design a class, which will have ‘n’ methods and ‘n’ clients, where every single client wants default implementation of ‘n-1’ methods and it needs to implement only one (unique to every client) of the methods. In such a situation, you may not like to declare any of the methods ‘abstract’ as it’ll be required to be a non-complete method only for one of the clients and a complete implementation for other ‘n-1’ clients. If you declare it ‘abstract’ then every client will need to implement it and you’ll end up getting ‘n-1’ same piece of code. On the other hand, if you don’t declare ‘abstract’ then you simply need to override this method in corresponding sub class. Since, the base class is incomplete in all the ‘n’ cases. Assuming that this class will have only these many forms of usage, you’ll never require having an instance of it. That’s why you would declare it ‘abstract’. Confused? Read this paragraph once more [:-)]

public abstract class SampleAbstractClass{
//…fields
……
//…non-abstract methods, if any
……
//…abstract method, if any J
abstract void sampleAbstractMethod(); //… ends with ‘;’
}

public class SubClassOfSampleAbstractClass extends SampleAbstractClass{
//… fields, and non-abstract methods (if any)
……
//…implementation of the abstract method
void sampleAbstractMethod(){
……
}
}

Difference between Interfaces and Abstract Classes: From the language perspective, there are several differences, few of them are:-

* An abstract class may contain fields, which are not ‘static’ and ‘final’ as is the case with interfaces.
* It may have few (or all) implemented methods as well, whereas Interfaces can’t have any implementation code. All the methods of an interface are by default ‘abstract’. Methods/Members of an abstract class may have any visibility: public, protected, private, none (package). But, those of an interface can have only one type of visibility: public.
* An abstract class automatically inherits the Object class and thereby includes methods like clone(), equals(), etc. There is no such thing with an interface. Likewise, an abstract class can have a constructor, but an interface can’t have one…
* Another very famous difference is that Interfaces are used to implement multiple inheritance in Java as a class in Java can explicitly have only one super class, but it can implement any number of interfaces… blah blah… :-)

From the performance perspective, the different is that Interfaces may be little slower as they require extra indirection to find the corresponding method in the actual class. Though, modern JVMs have already made that difference very little.

If you want to add a new method to an interface, then you either need to track all the classes implementing that interface or you’ll extend that interface to make a new interface having that extra method(s). In case of an abstract class, you’ll simply add the default implementation of that method and all the code will continue to work.

Many differences are listed already, but the main difference lies in the usage of the two. They are not rivals, but in most of the cases they are complimentary. We need to understand when to use what.

When to use an Interface: it asks you to start everything from scratch. You need to provide implementation of all the methods. So, you should use it to define the contract, which you’re unsure of how the different vendors/producers will implement. So, you can say that Interfaces can be used to enforce certain standards.

When to use an Abstract Class: it is used mostly when you’ve partial implementation ready with you, but not the complete. So, you may declare the incomplete methods as ‘abstract’ and leave it to the clients to implement it the way they actually want. Not all the details can be concrete at the base class level or different clients may like to implement the method differently.

When to use both: if you want to implement multiple inheritance where you have the luxury of providing partial implementation as well. You’ll then put all that code in an abstract class (this can be a concrete class as well… but here we assume that the class is also only partially implemented and hence an abstract class), extend that class, and implement as may interfaces as you want.

If you don’t know any method implementation at that time declaration then go for interface.

*

Abstract class may contain some fully implemented methods, but in interface one has to implement every method.
*

A class gets the ability to implement multiple interfaces but only one abstract class.

What are the differences between HashMap and Hashtable?

Both provide key-value access to data Access to the Hashtable is synchronized on the table while access to the HashMap isn’t.

Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.

If you change the map while iterating, you’ll know.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn’t. Also Map allows you to iterate over keys, values, or key-value pairs; Hashtable did not provide the third option.

http://ajai.wordpress.com/2006/07/08/some-java-interview-questions/

November 20, 2009

Very Good Java Interview Questions

What if the main method is declared as private?

The program compiles properly but at runtime it will give “Main method not public.” message.

What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

If you’re overriding the method equals() of an object, which other method you might also consider?

hashCode()

What is Byte Code?

Or

What gives java it’s “write once and run anywhere” nature?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Expain the reason for each keyword of public static void main(String args[])?

public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

What are the differences between == and .equals() ?

Or

what is difference between == and equals

Or

Difference between == and equals method

Or

What would you use to compare two String variables - the operator == or the method equals()?

Or

How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

public class EqualsTest {

public static void main(String[] args) {

String s1 = “abc”;
String s2 = s1;
String s5 = “abc”;
String s3 = new String(”abc”);
String s4 = new String(”abc”);
System.out.println(”== comparison : ” + (s1 == s5));
System.out.println(”== comparison : ” + (s1 == s2));
System.out.println(”Using equals method : ” + s1.equals(s2));
System.out.println(”== comparison : ” + s3 == s4);
System.out.println(”Using equals method : ” + s3.equals(s4));
}
}

Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

What if the static modifier is removed from the signature of the main method?

Or

What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error “NoSuchMethodError”.

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:

* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

What is the difference between a while statement and a do statement?

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

What is the Locale class?

The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places

What is implicit casting?

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting

Is sizeof a keyword in java?

The sizeof operator is not a keyword.

What is a native method?

A native method is a method that is implemented in a language other than Java.

In System.out.println(), what is System, out and println?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

What are Encapsulation, Inheritance and Polymorphism

Or

Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.

Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine is software that can be ported onto various hardware-based platforms

What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy

What are Java Access Specifiers?

Or

What is the difference between public, private, protected and default Access Specifiers?

Or

What are different types of access modifiers?

Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same package

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 static and non-static variables?

Or

What are class variables?

Or

What is static in java?

Or

What is a static method?

A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

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.

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What if I write static public void instead of public static void?

Program compiles and runs properly.

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.

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

What do you understand by a variable?

Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program.

What do you understand by numeric promotion?

The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

What do you understand by casting in java language? What are the types of casting?

The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.

What is the first argument of the String array in main method?

The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.

How can one prove that the array is not null but empty?

Print array.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print array.length.

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.

How can I swap two variables without using a third variable?

Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:

int a=5,b=10;a=a+b; b=a-b; a=a-b;

An other approach to the same question

You use an XOR swap.

for example:

int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;

What is data encapsulation?

Encapsulation may be used by creating ‘get’ and ’set’ methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.

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.

Can a method be static and synchronized?

A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:

synchronized(XYZ.class) {

}

What is difference between String and StringTokenizer?

A StringTokenizer is utility class used to break up string.

Example:

StringTokenizer st = new StringTokenizer(”Hello World”);

while (st.hasMoreTokens()) {

System.out.println(st.nextToken());

}

Output:

Hello

World

November 19, 2009

SQL questions

How do you implement one-to-one, one-to-many and many-to-many
relationships while designing tables?

One-to-One relationship can be implemented as a single table and
rarely as two tables with primary and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into
two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with
the keys from both the tables forming the composite primary key of the
junction table.

SQL Interview Ques

Define candidate key, alternate key, composite key.

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can't be bound?
A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFUALT in books online.

Whar is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach?

Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:
UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END



Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing,

What is a join and explain different types of joins?

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

What is a Stored Procedure?

Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements.

What is the basic difference between clustered and a non-clustered index?

The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.

What are cursors?

Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values.

Which TCP/IP port does SQL Server run on?

SQL Server runs on port 1433 but we can also change it for better security.

Can we use Truncate command on a table which is referenced by FOREIGN KEY?

No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.

What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

What is a Linked Server?

Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements.

Can you link only other SQL Servers or any database servers such as Oracle?

We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group.

What is BCP? When do we use it?

BulkCopy is a tool used to copy huge amount of data from tables and views. But it won’t copy the structures of the same.

SQL Interview Questions

What is ON DELETE CASCADE?

When ON DELETE CASCADE is specified Oracle maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed

What is the difference between TRUNCATE and DELETE commands?

Both will result in deleting all the rows in the table .TRUNCATE call cannot be rolled back as it is a DDL command and all memory space for that table is released back to the server. TRUNCATE is much faster.Whereas DELETE call is an DML command and can be rolled back.

What the difference between UNION and UNIONALL?

Union will remove the duplicate rows from the result set while Union all does'nt.

Which system table contains information on constraints on all the tables created ?
USER_CONSTRAINTS,
system table contains information on constraints on all the tables created

What is the difference between oracle,sql and sql server ?

* Oracle is based on RDBMS.
* SQL is Structured Query Language.
* SQL Server is another tool for RDBMS provided by MicroSoft.

What is the difference between SQL and SQL Server ?

SQLServer is an RDBMS just like oracle,DB2 from Microsoft
whereas
Structured Query Language (SQL), pronounced "sequel", is a language that provides an interface to relational database systems. It was developed by IBM in the 1970s for use in System R. SQL is a de facto standard, as well as an ISO and ANSI standard. SQL is used to perform various operations on RDBMS.

What is diffrence between Co-related sub query and nested sub query?

Correlated subquery runs once for each row selected by the outer query. It contains a reference to a value from the row selected by the outer query.

Nested subquery runs only once for the entire nesting (outer) query. It does not contain any reference to the outer query row.

For example,

Correlated Subquery:

select e1.empname, e1.basicsal, e1.deptno from emp e1 where e1.basicsal = (select max(basicsal) from emp e2 where e2.deptno = e1.deptno)

Nested Subquery:

select empname, basicsal, deptno from emp where (deptno, basicsal) in (select deptno, max(basicsal) from emp group by deptno)

What is database?
A database is a collection of data that is organized so that itscontents can easily be accessed, managed and updated. open this url : http://www.webopedia.com/TERM/d/database.html

How can i hide a particular table name of our schema?
you can hide the table name by creating synonyms.

e.g) you can create a synonym y for table x

create synonym y for x;

What is difference between DBMS and RDBMS?
The main difference of DBMS & RDBMS is

RDBMS have Normalization. Normalization means to refining the redundant and maintain the stablization.
the DBMS hasn't normalization concept.

What are the advantages and disadvantages of primary key and foreign key in SQL?

Primary key

Advantages

1) It is a unique key on which all the other candidate keys are functionally dependent

Disadvantage

1) There can be more than one keys on which all the other attributes are dependent on.

Foreign Key

Advantage

1)It allows refrencing another table using the primary key for the other table

Which date function is used to find the difference between two dates?
datediff

for Eg: select datediff (dd,'2-06-2007','7-06-2007')

output is 5


What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

November 14, 2009

Depth First Polymorphism

Consider the following class:

public class Polyseme {
public static class Top {
public void f(Object o) {
System.out.println("Top.f(Object)");
}
public void f(String s) {
System.out.println("Top.f(String)");
}
}
public static void main(String[] args) {
Top top = new Top();
top.f(new java.util.Vector());
top.f("hello");
top.f((Object)"bye");
}
}

Java looks for the method with the "narrowest" matching class for the parameter objects. Therefore, the output from running this class is:

Top.f(Object)
Top.f(String)
Top.f(Object)

In Java, the virtual machine tries to find a matching method for your parameters, starting at the top of the hierarchy and moving down. Say we have the following classes:

public class BreadthFirst {
public static class Top {
public void f(Object o) {
System.out.println("Top.f(Object)");
}
}
public static class Middle extends Top {
public void f(String s) {
System.out.println("Middle.f(String)");
}
}
public static void main(String[] args) {
Top top = new Middle();
top.f(new java.util.Vector());
top.f("hello");
top.f((Object)"bye");
}
}

The virtual machine will thus start at Top and check if there are any methods which would accept String.class or Object.class, and indeed, Top.f(Object) would handle all those parameters. The output is therefore the following:

Top.f(Object)
Top.f(Object)
Top.f(Object)

We could "fix" this by overriding f(Object) and using instanceof to call the correct f() method (brrr - I'd rather get stuck on the N2 than do that [for those not living in Cape Town, the N2 is notoriously dangerous, you either get shot at or in or with if your car breaks down])

public class BreadthFirstFix {
public static class Top {
public void f(Object o) {
System.out.println("Top.f(Object)");
}
}
public static class Middle extends Top {
public void f(Object o) {
if (o instanceof String)
f((String)o);
else
super.f(o);
}
public void f(String s) {
System.out.println("Middle.f(String)");
}
}
public static void main(String[] args) {
Top top = new Middle();
top.f(new java.util.Vector());
top.f("hello");
top.f((Object)"bye");
}
}

The output would now look as we would expect:

Top.f(Object)
Middle.f(String)
Middle.f(String)

This might have the correct effect, but it does mean that we have to have such a silly "instanceof" in all the subclasses. If we are designing a OO framework we want to have our clients subclass our classes without having to do acrobatics to achieve this.

Christoph Jung mentioned this problem with Java to me a few weeks ago and we thought of some code you could put at the highest level class that uses reflection to start at the lowest class and then tries to match the method to the type before moving up the hierarchy. I call this "depth-first-polymorphism".

import java.lang.reflect.*;
public class DepthFirst {
public static class Top {
private Method getPolymorphicMethod(Object param) {
try {
Class cl = getClass(); // the bottom-most class
// we start at the bottom and work our way up
Class[] paramTypes = {param.getClass()};
while(!cl.equals(Top.class)) {
try {
// this way we find the actual method
return cl.getDeclaredMethod("f", paramTypes);
} catch(NoSuchMethodException ex) {}
cl = cl.getSuperclass();
}
return null;
}
catch(RuntimeException ex) { throw ex; }
catch(Exception ex) { return null; }
}
public void f(Object object) {
Method downPolymorphic = getPolymorphicMethod(object);
if (downPolymorphic == null) {
System.out.println("Top.f(Object)");
} else {
try {
downPolymorphic.invoke(this, new Object[] {object});
}
catch(RuntimeException ex) { throw ex; }
catch(Exception ex) {
throw new RuntimeException(ex.toString());
}
}
}
}
public static class Middle extends Top {
public void f(String s) {
System.out.println("Middle.f(String)");
}
}
public static class Bottom extends Middle {
public void f(Integer i) {
System.out.println("Bottom.f(Integer)");
}
}
public static class RockBottom extends Bottom {
public void f(String s) {
System.out.println("RockBottom.f(String)");
}
}
public static void main(String[] args) {
Top top = new RockBottom();
top.f(new java.util.Vector());
top.f("hello");
top.f(new Integer(42));
top = new Bottom();
top.f(new java.util.Vector());
top.f("hello");
top.f(new Integer(42));
}
}

The answer is this time:

Top.f(Object)
RockBottom.f(String
Bottom.f(Integer)
Top.f(Object)
Middle.f(String)
Bottom.f(Integer)

When should you use this technique? Only if you have a lot of specific type handlers as subclasses of a common superclass where it would make sense to add such a depth-first invoker. You can probably extract this functionality and put it in a separate class. If you use this commercially please do the exception handling correctly, I didn't bother in my example, in preparation for when I change my logo to "The C# Specialists"

November 13, 2009

Fail fast and fail safe iterator

Fail Fast :
When we iterate over a collection, if during iteration, we modify the collection , then the iteration halts and we get "ConcurrentModificationException" (e.g Hashtable)

Fail Safe :
During iteration, a separate copy of the colleciton object is created and iteration occurs on that. So if we modify it during the iteration process, it wont throw an exception.(e.g HashMap)

Best Explanation (with example) : http://www.certpal.com/blogs/2009/09/iterators-fail-fast-vs-fail-safe/

How to Make a Java Class Immutable

Making a class immutable

Immutability must be familiar to every one when we talk about String & StringBuffer classes in java. Strings are considered immutable because the values contained in the reference variable cannot be changed. Whereas String Buffer is considered mutable because the value in a string buffer can be changed (i.e. mutable).

However I always thought how to make our user defined classes as immutable though I am unaware as to why any one would need this.

The reason perhaps might be clear once we have a look at the code.

Now in order to make a class immutable we must restrict changing the state of the class object by any means. This in turn means avoiding an assignment to a variable. We can achieve this through a final modifier. To further restrict the access we can use a private access modifier. Above do not provide any method where we modify the instance variables.

Still done? No. How if some body creates a sub class from our up till now immutable class? Yes here lies the problem. The new subclass can contain methods, which over ride our base class (immutable class) methods. Here he can change the variable values.

Hence make the methods in the class also final. Or a better approach. Make the immutable class itself final. Hence cannot make any sub classes, so no question of over ridding.

The following code gives a way to make the class immutable.

/*
This code demonstrates the way to make a class immutable
*/

// The immutable class which is made final
final class MyImmutableClass
{
// instance var are made private & final to restrict the access

private final int count;
private final double value;

// Constructor where we can provide the constant value
public MyImmutableClass(int paramCount,double paramValue)
{
count = paramCount;
value = paramValue;
}

// provide only methods which return the instance var
// & not change the values

public int getCount()
{
return count;
}

public double getValue()
{
return value;
}
}

// class TestImmutable
public class TestImmutable
{
public static void main(String[] args)
{
MyImmutableClass obj1 = new MyImmutableClass(3,5);

System.out.println(obj1.getCount());
System.out.println(obj1.getValue());

// there is no way to change the values of count & value-
// no method to call besides getXX, no subclassing, no public access to var -> Immutable
}
}

The possible use of immutable classes would be a class containing a price list represented for a set of products.
Otherwise also this represents a good design.

http://www.sap-img.com/java/how-to-make-a-java-class-immutable.htm

What is ant

What is Ant? A simple definition might state that Ant is a Java-based build tool. Of course that definition may just raise the question in your mind "What is a build tool?". To answer that question, consider what is required to build a software system. Typically, there is much more to building software than just typing in and then compiling the source code. There is a number of steps required to transform the source into a deployable and useable software solution. The following is a hypothetical build process you might use with a simple software system

1. Get the source. You may need to download or fetch the source from a source code repository. For this, you might need to know the tag or version of the source code you want to build.
2. Prepare a build area. You will probably want to create a set of directories, perhaps according to some standardized directory layout.
3. Configure the build. In this step, you will determine what optional components can be built based on the current environment. You might want to set build numbers and version numbers to be included in the build.
4. Validate the source code. You may have a standard style guide and you wish to ensure all code conforms to this before you build a release.
5. Compile the source code
6. Build the compiled code into libraries potentially including non-code resources such as properties, images and sound files.
7. Run the system's tests to validate the build.
8. Build the documentation for the software. This may range from something as simple as collecting text files up to processing content through some form of publishing system to produce the documentation in its final form
9. Package up all of the components of the software – code, resources, images, documentation, etc. – into a deployable package. You might need to produce several packages in different formats for different target users
10. Deploy the software to some standard location for use or distribution

This is a high-level view of a software build process. A real-life build process may of course require many more and varied steps. Each of these steps may involve many individual operations.

If you try to use a manual process for building your software you would find it to be tedious, error prone and, in general, not very repeatable. You might forget to set the version number or to provide a tar file for Unix users. You might change the directory structure, confusing users who upgrade from the previous version of the software. Even worse, you may forget to test the software and ship a version that may not even work. Such ad-hoc build processes are always a source of problems and the best solution is to automate the build process. The tools you use to automate the build process are known, unsurprisingly, as build tools. Ant is such a tool.

In general, a build tool allows developers and build managers to describe the build process. In a build, some steps may need to be executed before others or they may be independent of others. In the example above, while the steps are laid out as a linear sequence, there are certain dependencies evident. Obviously, the source cannot be compiled until it has been fetched and the directory structure has been built. The directory structure, however, can be created before, or even while the source is being fetched. Fetching the source may be an expensive operation – perhaps accessing a remote server – and you may not want to do that every time you build the software. A build tool helps by only performing the operations that are required.

In summary, a build tool provides a mechanism to describe the operations and structure of the build process. When the build tool is invoked it uses this description, examines the current state of affairs to determine the steps that need to be executed and in which order, and then manages the execution of those steps.

Often developers will start the automation of their build process with scripting tools supplied by the operating system. Depending on your platform that might be a shell script, a batch file, a Perl script or, indeed, whatever scripting language is your particular preference. These scripts can be quite sophisticated but they usually fail to capture the structure of the build process and can often become a maintenance headache. Each time your code is changed, say adding a new source directory, you will need to update the build script. Since the build scripts are ad-hoc, new developers on your team may not understand them. Further, in many instances, such scripts perform all of the steps of a build even when only some are required. That is OK for build managers who will want clean builds but quickly becomes difficult for developers who may do many builds in a development session and need fast, incremental builds.
Java-Based

Those of you who are familiar with make will realize that the above description of a build tool is also satisfied by make. That isn't surprising since make is also a build tool. Makefiles provide the build description and make then organizes the execution of shell commands to build the software. One major difference between Ant and make is that Ant executes tasks implemented as Java classes. Make executes commands from the operating system's shell.

Being Java-based means a few different things for Ant. Ant largely inherits Java's platform independence. This means that Ant's build files can be easily moved from one platform to another. If you can ensure a homogenous build, development and deployment environment for the life of your project, platform independence may not seem important. For many softwre developments, however, development and deployment environments may be quite different. Open source Java projects, for example, have to support a number of target platforms. An Ant build file allows such projects to have and maintain a single build description. Even in closed source developments, the development and deployment platforms may be different. It is not uncommon for the development environments to be PC-based while production may use a Sun or IBM high-end Unix server. If these environments were to use different build descriptions, there is always the possibility, even the inevitability, of these descriptions getting out of sync. You tend to encounter these problems when production deployment fails, perhaps subtly, and it is usually an unpleasant discovery. Using the same build description throughout the project reduces the opportunity for such problems to occur.

Platform independence can sometimes be limiting, so some Ant tasks give access to the facilities of the underlying operating system. That puts the choice in the hands of the build file developers. Even when this is necessary, Ant will allow you to manage the bulk of the build process in a platform independent way, augmented with platform dependent sections.

Another aspect of Ant that is Java-Based is that the primitive build steps, known as tasks in Ant, are built in Java. These tasks can be loaded at runtime, so developers may extend Ant by writing new Tasks. You will also find many of the tasks that come with Ant are written to deal with the typical structure of Java projects. For example, the Java compilation task understands the directory structures involved in the Java package concept. It is able to compile all code in a source tree in a single operation.

@ Annotations

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

Annotations have a number of uses, among them:

* Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.

* Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.

* Runtime processing — Some annotations are available to be examined at runtime.

Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements.

The annotation appears first, often (by convention) on its own line, and may include elements with named or unnamed values:

@Author(
name = "Pragya Rawal",
date = "3/3/2003"
)
class MyClass() { }

or

@SuppressWarnings(value = "unchecked")
void myMethod() { }

If there is just one element named "value," then the name may be omitted, as in:

@SuppressWarnings("unchecked")
void myMethod() { }

Also, if an annotation has no elements, the parentheses may be omitted, as in:

@Override
void mySuperMethod() { }

Documentation
Many annotations replace what would otherwise have been comments in code.

Suppose that a software group has traditionally begun the body of every class with comments providing important information:

public class Generation3List extends Generation2List {

// Author: Pragya Rawal
// Date: 3/17/2012
// Current revision: 6
// Last modified: 4/12/2010
// By: Pragya

// class code goes here

}

To add this same metadata with an annotation, you must first define the annotation type. The syntax for doing this is:

@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
String[] reviewers(); // Note use of array
}

The annotation type definition looks somewhat like an interface definition where the keyword interface is preceded by the @ character (@ = "AT" as in Annotation Type). Annotation types are, in fact, a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces.

The body of the annotation definition above contains annotation type element declarations, which look a lot like methods. Note that they may define optional default values.

Once the annotation type has been defined, you can use annotations of that type, with the values filled in, like this:

@ClassPreamble (
author = "Pragya Rawal",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Pragya Rawal",
reviewers = {"A", "B", "C"} // Note array notation
)
public class Generation3List extends Generation2List {

// class code goes here

}

Note: To make the information in @ClassPreamble appear in Javadoc-generated documentation, you must annotate the @ClassPreamble definition itself with the @Documented annotation:

import java.lang.annotation.*; // import this to use @Documented

@Documented
@interface ClassPreamble {

// Annotation element definitions

}

Annotations Used by the Compiler
There are three annotation types that are predefined by the language specification itself: @Deprecated, @Override, and @SuppressWarnings.

@Deprecated—the @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag, as shown in the following example. The use of the "@" symbol in both Javadoc comments and in annotations is not coincidental—they are related conceptually. Also, note that the Javadoc tag starts with a lowercase "d" and the annotation starts with an uppercase "D".

// Javadoc comment follows
/**
* @deprecated
* explanation of why it was deprecated
*/
@Deprecated
static void deprecatedMethod() { }
}

@Override—the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass (overriding methods will be discussed in the the lesson titled "Interfaces and Inheritance").

// mark method as a superclass method
// that has been overridden
@Override
int overriddenMethod() { }

While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

@SuppressWarnings—the @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. In the example below, a deprecated method is used and the compiler would normally generate a warning. In this case, however, the annotation causes the warning to be suppressed.

// use a deprecated method and tell
// compiler not to generate a warning
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
objectOne.deprecatedMethod(); //deprecation warning - suppressed
}

Every compiler warning belongs to a category. The Java Language Specification lists two categories: "deprecation" and "unchecked." The "unchecked" warning can occur when interfacing with legacy code written before the advent of generics (discussed in the lesson titled "Generics"). To suppress more than one category of warnings, use the following syntax:

@SuppressWarnings({"unchecked", "deprecation"})

Annotation Processing
The more advanced uses of annotations include writing an annotation processor that can read a Java program and take actions based on its annotations. It might, for example, generate auxiliary source code, relieving the programmer of having to create boilerplate code that always follows predictable patterns. To facilitate this task, release 5.0 of the JDK includes an annotation processing tool, called apt. In release 6 of the JDK, the functionality of apt is a standard part of the Java compiler.

To make annotation information available at runtime, the annotation type itself must be annotated with @Retention(RetentionPolicy.RUNTIME), as follows:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface AnnotationForRuntime {

// Elements that give information
// for runtime processing

}

Question 1: What is wrong with the following interface:

public interface House {
@Deprecated
public void open();
public void openFrontDoor();
public void openBackDoor();
}

Answer 1:The documentation should reflect why open is deprecated and what to use instead. For example:

public interface House {
/**
* @deprecated use of open is discouraged, use
* openFrontDoor or openBackDoor instead.
*/
@Deprecated
public void open();
public void openFrontDoor();
public void openBackDoor();
}

Question 2: Consider this implementation of the House interface, shown in Question 1.

public class MyHouse implements House {
public void open() {}
public void openFrontDoor() {}
public void openBackDoor() {}
}

If you compile this program, the compiler complains that open has been deprecated (in the interface). What can you do to get rid of that warning?

Answer 2: You can deprecate the implementation of open:

public class MyHouse implements House {
//The documentation is inherited from the interface.
@Deprecated
public void open() {}
public void openFrontDoor() {}
public void openBackDoor() {}
}

Alternatively, you can suppress the warning:

public class MyHouse implements House {
@SuppressWarnings("deprecation")
public void open() {}
public void openFrontDoor() {}
public void openBackDoor() {}
}

http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/annotations-answers.html

Overriding and Hiding Methods (Form SUN java tutorials)

Instance Methods
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information on @Override, see Annotations.

Class Methods
If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. Let's look at an example that contains two classes. The first is Animal, which contains one instance method and one class method:

public class Animal {
public static void testClassMethod() {
System.out.println("The class method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal.");
}
}

The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat.");
}

public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}

The Cat class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Cat and calls testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:

The class method in Animal.
The instance method in Cat.

As promised, the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.
Modifiers
The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.

http://java.sun.com/docs/books/tutorial/java/IandI/override.html

November 12, 2009

Struts :)

1.What is MVC?

Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.

* Model : The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

* View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

* Controller:The controller reacts to the user input. It creates and sets the model.


2.What is a framework?

A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

3.What is Struts framework?

Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

4.What are the components of Struts?

Struts components can be categorize into Model, View and Controller:

* Model: Components like business logic /business processes and data are the part of model.
* View: HTML, JSP are the view components.
* Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

5.What are the core classes of the Struts Framework?

Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.

* JavaBeans components for managing application state and behavior.
* Event-driven development (via listeners as in traditional GUI development).
* Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

6.What is ActionServlet?

ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request.

7.What is role of ActionServlet?

ActionServlet performs the role of Controller:

* Process user requests
* Determine what the user is trying to achieve according to the request
* Pull data from the model (if necessary) to be given to the appropriate view,
* Select the proper view to respond to the user
* Delegates most of this grunt work to Action classes
* Is responsible for initialization and clean-up of resources


8.What is the ActionForm?

ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

9.What are the important methods of ActionForm?

The important methods of ActionForm are : validate() & reset().

10.Describe validate() and reset() methods ?

validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)


reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.

public void reset() {}


11.What is ActionMapping?

Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.

12.How is the Action Mapping specified ?

We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from configuration element of struts-config.xml file


type="submit.SubmitAction"
name="submitForm"
input="/submit.jsp"
scope="request"
validate="true">






13.What is role of Action Class?

An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

14.In which method of Action class the business logic is executed ?

In the execute() method of Action class the business logic is executed.

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;


execute() method of Action class:

* Perform the processing required to deal with this request
* Update the server-side objects (Scope variables) that will be used to create the next page of the user interface
* Return an appropriate ActionForward object


Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.

* Service to Worker
* Dispatcher View
* Composite View (Struts Tiles)
* Front Controller
* View Helper
* Synchronizer Token