Sunday, August 21, 2011

Top 20 Core Java Interview Questions for Investment Banks

Top 20 Core Java Interview questions in Finance domain
This is a new series of sharing core Java interview question on Finance domain and mostly on Big Investment bank. Anybody who is preparing for any Java developer Interview on any Investment bank can be benefited from these set of core Java Interview questions. I have collected these questions from my friends and I thought to share with you all.  I hope this will be helpful for both of us. Please share answers for unanswered question and let us know how good these interview questions are.


Recently I was looking at comments made on java interview questions given in this post and I found some of them quite useful to include into main post to benefit all.

1. What is immutable object? Can you write immutable object?
You need to make class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

2. Does all property of immutable object needs to be final?
Not necessary as stated above you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

3. What is the difference between creating String as new () and literal?
When we create string with new () it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.


String s = new String("Test");
will put the object in String pool , it it does then why do one need String.intern() method which is used to put Strings into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" it put the String in pool.


4. How does substring () inside String works?
Another good question, I think answer is not sufficient but here it is “Substring creates new object out of string by taking a portion of original string”.


suggested by Anand and Anonymous


The substring() method is used to return a part (or substring) of the String used to invoke the method. The first argument represents the starting location (zero-based) of the substring. If the call has only one argument, the substring returned will include the characters to the end of the original String. If the call has two arguments, the substring returned will end with the character located in the nth position of the original String where n is the second argument. Unfortunately, the ending argument is not zero-based, so if the second argument is 7, the last character in the returned String will be in the original String’s 7 position, which is index 6. Let’s look at an example:
String x = "0123456789";

System.out.println( x.substring(5) ); // output is "56789"
System.out.println( x.substring(5, 8)); // output is "567"

The first example should be easy: start at index 5 and return the rest of the String. The second example should be read as follows: start at index 5 and return the characters up to and including the 8th position (index 7).



and @Anonymous pointed out some interesting fact:
omething important about String.substring() method, its implementation calls the following String(...) constructor :

// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}

That means the new String() object returned by substring(...) shares the same backing array (this.value) as the original string object.

Thus if your original string object is 1GB long, the substring object will always be 1GB long too!

You will probably want to trim the new array size to the substring range, this should do the job:

String veryLongString = readFromFile(file);
String tinyString = new String(veryLongString.substring(1,10));

The String(String) constructor is implemented that way:

public String(String original) {
...
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
}
...
}



5. Which two method you need to implement for key in hashMap ?
(equals and hashcode) read How HashMap works in Java for detailed explanation.

6. Where does these  two method comes in picture during get operation?
See here  How HashMap works in Java for detailed explanation.

7. How do you handle error condition while writing stored procedure or accessing stored procedure from java?
Open for all, my friend didn't know the answer so he didn't mind telling me.

8. What is difference between Executor.submit() and Executer.execute() method ?
(Former returns an object of Future which can be used to find result from worker thread)


@vinit Saini suggesed a very good point related to this core java interview question


There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will rethrow this exception, wrapped in an ExecutionException.

9. What is the difference between factory and abstract factory pattern?
Open for all, he explains about factory pattern and how factory pattern saves maintenance time by encapsulating logic of object creation but didn't know exact answer


@Raj suggested
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.


10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
see my article 10 Interview questions on Singleton Pattern in Java

11. Can you write Critical section code for singleton?
check here  10 Interview questions on Singleton Pattern in Java

12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.

13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java

14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here  How HashMap works in Java for detailed explanation.

15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.


19. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @Mohit
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code…

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println (“Time taken for execution is ” + (end – start));

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing
 
Source: here
 

Facebook /Mircosoft interview question - Analysis + several solutions in C++/Java

Given an array A, output another array B such that B[k] is the product of all elements in A but A[k]. Division is not allowed, More specifically,

Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i.
Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
      = [120, 60, 40, 30, 24]
You must do this in O(N) without using division.

Full analysis:


An explanation of the method is: The trick is to construct the arrays (in the case for 4 elements)
{              1,         a[0],    a[0]*a[1],    a[0]*a[1]*a[2],  }
{ a[1]*a[2]*a[3],    a[2]*a[3],         a[3],                 1,  }
Both of which can be done in O(n) by starting at the left and right edges respectively.
Then multiplying the two arrays element by element gives the required result
My code would look something like this:
int a[N] // This is the input
int products_below[N];
p=1;
for(int i=0;i<N;++i)
{
  products_below[i]=p;
  p*=a[i];
}

int products_above[N];
p=1;
for(int i=N-1;i>=0;--i)
{
  products_above[i]=p;
  p*=a[i];
}

int products[N]; // This is the result
for(int i=0;i<N;++i)
{
  products[i]=products_below[i]*products_above[i];
}
If you need to be O(1) in space too you can do this (which is less clear IMHO)
int a[N] // This is the input
int products[N];

// Get the products below the curent index
p=1;
for(int i=0;i<N;++i)
{
  products[i]=p;
  p*=a[i];
}

// Get the products above the curent index
p=1;
for(int i=N-1;i>=0;--i)
{
  products[i]*=p;
  p*=a[i];
}
 
Here is a small recursive function in C++ to do the modification in place. It requires O(n) extra space (on stack) though. Assuming the array is in a and N holds the array length, we have
int multiply(int *a, int fwdProduct, int indx) {
    int revProduct = 1;
    if (indx < N) {
       revProduct = multiply(a, fwdProduct*a[indx], indx+1);
       int cur = a[indx];
       a[indx] = fwdProduct * revProduct;
       revProduct *= cur;
    }
    return revProduct;
}


//Here is a small recursive function in Java

static int multiply(int[] nums, int p, int n) {
    return (n == nums.length) ? 1
      : nums[n] * (p = multiply(nums, nums[n] * (nums[n] = p), n + 1))
          + 0*(nums[n] *= p);
}

int[] arr = {1,2,3,4,5};
multiply(arr, 1, 0);
System.out.println(Arrays.toString(arr));
// prints "[120, 60, 40, 30, 24]" 
 
Here's another method to solve it in Java. Apologies for the non-standard formatting, but the code has a lot of duplication, and this is the best I can do to make it readable.

import java.util.Arrays;

public class Products {
    static int[] products(int... nums) {
        final int N = nums.length;
        int[] prods = new int[N];
        Arrays.fill(prods, 1);
        for (int
           i = 0, pi = 1    ,  j = N-1, pj = 1  ;
           (i < N)         && (j >= 0)          ;
           pi *= nums[i++]  ,  pj *= nums[j--]  )
        {
           prods[i] *= pi   ;  prods[j] *= pj   ;
        }
        return prods;
    }
    public static void main(String[] args) {
        System.out.println(
            Arrays.toString(products(1, 2, 3, 4, 5))
        ); // prints "[120, 60, 40, 30, 24]"
    }
}
 
//Source: here 


Wednesday, August 17, 2011

Morgan Stanley Interview Question


Suppose you have a large file with lots of words. How would you find the unique words and their count?
What kind of data structure u will use? What will be the time complexity and space complexity?

/* Algorithm to count words in a file. Please dont reply opinions on the code, comments on complexity analysis is appreciated
For each word check if the word exists in the hash, if it doesnt then insert the word with a count 1
if it does then increment the value
For each word in the hashmap, print word and its count
Complexity: Linear insertion and space
NOTE:The code only compiles with newer C++ use the switch -std=c++0x in your Makefile*/
#include <iostream>
#include <vector>
#include <unordered_map>
typedef std::unordered_map<std::string, int> MyHashMap;
void printMyHashMap(MyHashMap::const_iterator itr,MyHashMap::const_iterator enditr){
while(itr!=enditr){
std::cout<<(*itr).first<<" : "<<(*itr).second<<std::endl;
++itr;
}
}
int main(){
MyHashMap wordsMap; //declare unordered map
//vector of strings
std::vector<std::string> strings {"count","words","in","a","file",
"and","print","words","with","their","count",
".","more","words","file"};
int len = strings.size();
std::vector<std::string>::const_iterator wordsItr;
wordsItr = strings.begin();
MyHashMap::iterator mapItr = wordsMap.begin();
for ( wordsItr=strings.begin(); wordsItr!=strings.end(); wordsItr++ ){
mapItr = wordsMap.find(*wordsItr);
if(mapItr==wordsMap.end()){ //if word not found then
wordsMap.insert(MyHashMap::value_type(*wordsItr, 1));
}else{
(*mapItr).second = ++(*mapItr).second; }
}
std::cout<<"words and their count :"<<std::endl;
printMyHashMap(wordsMap.begin(),wordsMap.end());
return (0);
}



///2
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <map>
#include <iterator>
using namespace std;
int main() {
string str;
ifstream in("input.txt");
map<string, int> m;
if (in.is_open()) {
while(in >> str) {
m[str]++;
}
}
for(map<string, int>::iterator it = m.begin(); it != m.end(); it++) {
cout << (*it).first <<"\t" << (*it).second << endl;
}
}
input.txt
abc abc abc abc abc abc abc abcdef abc abcd
abc abc abc abc abc abc abc abcdef abc abcd
abc abc abc abc abc abc abc abcdef abc abcd
abc abc abc abc abc abc abc abcdef abc abcd
count words in a file and print words with their count more words file
output
ajay@ubuntu:~/workspace$ ./a.out
a 1
abc 32
abcd 4
abcdef 4
and 1
count 2
file 2
in 1
more 1
print 1
their 1
with 1
words 3


//Java method


import java.util.HashMap;
public class TestTest {
public static void main(String[] args){
String inputString = "abc abc abc abc abc abc abc abcdef abc abcd abc abc abc abc abc abc abc abcdef abc abcd" +
" abc abc abc abc abc abc abc abcdef abc abcd abc abc abc abc abc abc abc abcdef abc abcd" +
" count words in a file and print words with their count more words file";
HashMap<Object, Integer> myMap = new HashMap<Object, Integer>(){
@Override
public Integer put(Object arg0, Integer arg1) {
Integer i = super.get(arg0);
arg1 = i==null?1:i+1;
return super.put(arg0, arg1);
}
};

String[] splits = inputString.split(" ");
for(String s : splits){
myMap.put(s,1);
}

System.out.println(myMap);
}
}


Source: Here


Interview Questions: wap to print "hello world" without reaching the main function in C++

There are several ways to do this:

1.
#include<stdio.h>
#include<conio.h>
#define uttam main
uttam()
{
printf("hello world");
getch();
return 0;
}
 
2. 
#include<stdio.h>
#define(s,t,u,m,p,e,d)m##s##u##t
#define begin decode(a,n,i,m,a,t,e)
int begin()
{
printf("Hello World");
}
 
3.
#include<stdio.h>
#include<iostream>

class World
{
 public:
 World()
 {
  printf("Hello world\n");
 }
};

World w1;

int main()
{
	printf("Hello world again!!\n");
	return 0;
}
 
source, click here.   

UNIX command Questions Answers asked in Interview

UNIX command Questions Answers asked in Interview

UNIX or Linux operating system has become default Server operating system and for whichever programming job you give interview you find some UNIX command interview questions there. These UNIX command interview questions are mostly asked during Java development and Support role interviews on various investment banks mostly because most of electronic trading systems or stock trading system works on Unix servers. As we know that high volume low latency systems which wants to take advantage of little bit of volatility in market for Equity , Futures and options or Foreign exchange trading need a stable server side operating system and Redhat Linux is doing great job there. with the advent of Algorithmic trading this speed factor becomes more important so getting someone who has good knowledge of operating system and commands on which these trading system runs is definitely required. but these UNIX command interview questions are equally applicable for any job interview which requires some work on Unix Operating System. With the growing use of Linux in form of RedHat, Solaris and IBM AIX its must to keep you familiar with essential Linux commands available on various platforms. 

Long back I had once asked one of my friend why are you preparing Unix Command interview questions if you going for a Java Interview and he told me that this job doesn't only require knowledge of Java but also knowledge of Unix, Linux, SQL and other scripting language , which is quite true. After that I thought to collect various UNIX command interview questions asked to Java developers or trading system support interviews and this is the result of that compilation. This list of UNIX command interview questions are by means complete and would be great if you guys contribute some genuine and good Unix Command Interview questions and answers asked during interviews. I have divided the questions on three categories for sake of managing and keeping this list of Unix Interview questions up to date.

Beginners UNIX Interview Questions Answers

1. Write command to list all the links from a directory?
In this UNIX command interview questions interviewer is generally checking whether user knows basic use of "ls" "grep" and regular expression etc
You can write command like:
ls -lrt | grep "^l"


2. Create a read-only file in your home directory?
This is a simple UNIX command interview questions where you need to create a file and change its parameter to read-only by using chmod command you can also change your umask to create read only file.
touch file
chmod 400 file

3. How will you find which operating system your system is running on in UNIX?
By using command "uname -a" in UNIX

4. How will you run a process in background? How will you bring that into foreground and how will you kill that process?
For running a process in background use "&" in command line. For bringing it back in foreground use command "fg jobid" and for getting job id you use command "jobs", for killing that process find PID and use kill -9 PID command. This is indeed a good Unix Command interview questions because many of programmer not familiar with background process in UNIX.

5. How do you know if a remote host is alive or not?
You can check these by using either ping or telnet command in UNIX. This question is most asked in various Unix command Interview because its most basic networking test anybody wants to do it.


6. How do you see command line history in UNIX?
Very useful indeed, use history command along with grep command in unix to find any relevant command you have already executed. Purpose of this Unix Command Interview Questions is probably to check how familiar candidate is from available tools in UNIX operation system.

7. How do you copy file from one host to other?
Many options but you can say by using "scp" command. You can also use rsync command to answer this UNIX interview question or even sftp would be ok.

8. How do you find which process is taking how much CPU?
By using "top" command in UNIX, there could be multiple follow-up UNIX command interview questions based upon response of this because “TOP” command has various interactive options to sort result based upon various parameter.

9. How do you check how much space left in current drive ?
By using "df" command in UNIX. For example "df -h ." will list how full your current drive is. This is part of anyone day to day activity so I think this Unix Interview question will be to check anyone who claims to working in UNIX but not really working on it.

10. What is the difference between Swapping and Paging?
Swapping:
Whole process is moved from the swap device to the main memory for execution. Process size must be less than or equal to the available main memory. It is easier to implementation and overhead to the system. Swapping systems does not handle the memory more flexibly as compared to the paging systems.
Paging:
Only the required memory pages are moved to main memory from the swap device for execution. Process size does not matter. Gives the concept of the virtual memory. It provides greater flexibility in mapping the virtual address space into the physical memory of the machine. Allows more number of processes to fit in the main memory simultaneously. Allows the greater process size than the available physical memory. Demand paging systems handle the memory more flexibly.


Intermediate UNIX Interview Questions Answers

1. What is difference between ps -ef and ps -auxwww?
This is indeed a good Unix Interview Command Question and I have faced this issue while ago where one culprit process was not visible by execute ps –ef command and we are wondering which process is holding the file.
ps -ef will omit process with very long command line while ps -auxwww will list those process as well.

2. How do you find how many cpu are in your system and there details?
By looking into file /etc/cpuinfo for example you can use below command:
cat /proc/cpuinfo

3. What is difference between HardLink and SoftLink in UNIX?
I have discussed this Unix Command Interview questions  in my blog post difference between Soft link and Hard link in Unix

4. What is Zombie process in UNIX? How do you find Zombie process in UNIX?
When a program forks and the child finishes before the parent, the kernel still keeps some of its information about the child in case the parent might need it - for example, the parent may need to check the child's exit status. To be able to get this information, the parent calls 'wait()'; In the interval between the child terminating and the parent calling 'wait()', the child is said to be a 'zombie' (If you do 'ps', the child will have a 'Z' in its status field to indicate this.)
Zombie : The process is dead but have not been removed from the process table.

5. What is "chmod" command? What do you understand by this line “r-- -w- --x?

6. There is a file some where in your system which contains word "UnixCommandInterviewQuestions” How will find that file in Unix?
By using find command in UNIX for details see here 10 example of using find command in Unix

7. In a file word UNIX is appearing many times? How will you count number?
grep -c "Unix" filename

8. How do you set environment variable which will be accessible form sub shell?
By using export   for example export count=1 will be available on all sub shell.

9. How do you check if a particular process is listening on a particular port on remote host?
By using telnet command for example “telnet hostname port”, if it able to successfully connect then some process is listening on that port. To read more about telnet read networking command in UNIX

10. How do you find whether your system is 32 bit or 64 bit ?
Either by using "uname -a" command or by using "arch" command.


Advanced UNIX Interview Questions and Answers

1. How do you find which processes are using a particular file?
By using lsof command in UNIX. It wills list down PID of all the process which is using a particular file.

2. How do you find which remote hosts are connecting to your host on a particular port say 10123?
By using netstat command execute netstat -a | grep "port" and it will list the entire host which is connected to this host on port 10123.

3. What is nohup in UNIX?

4. What is ephemeral port in UNIX?
Ephemeral ports are port used by Operating system for client sockets. There is a specific range on which OS can open any port specified by ephemeral port range.

5. If one process is inserting data into your MySQL database? How will you check how many rows inserted into every second?
Purpose of this Unix Command Interview is asking about "watch" command in UNIX which is repeatedly execute command provided with specified delay.

6. There is a file Unix_Test.txt which contains words Unix, how will you replace all Unix to UNIX?
You can answer this Unix Command Interview question by using SED command in UNIX for example you can execute sed s/Unix/UNIX/g fileName.

7. You have a tab separated file which contains Name, Address and Phone Number, list down all Phone Number without there name and Addresses?
To answer this Unix Command Interview question you can either you AWK or CUT command here. CUT use tab as default separator so you can use
cut -f3 filename.

8. Your application home directory is full? How will you find which directory is taking how much space?
By using disk usage (DU) command in Unix for example du –sh . | grep G  will list down all the directory which has GIGS in Size.

9. How do you find for how many days your Server is up?
By using uptime command in UNIX

10. You have an IP address in your network how will you find hostname and vice versa?
This is a standard UNIX command interview question asked by everybody and I guess everybody knows its answer as well.
By using nslookup command in UNIX, you can read more about networking command in UNIX here.

Source: click here.