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/