Wednesday, May 29, 2013

20 core java interview questions

Top 20 Core Java Interview questions answers asked in Investment Bank

 JP MorganMorgan StanleyBarclays or Goldman Sachs
Banks mostly asked core Java interview questions from multi-threading, collectionserialization, coding and OOPS design principles.  

@TODO programming interview questions  30 Java C/C++

@TODO How HashMap works in Java  (HashMap vs. Hash table) 
  • (Diamond Problem) 
  • (multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity.)
Why String is immutable in Java 
1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal
2)String has been widely used as parameter for many Java classes. In case, if String is not immutable, this would lead serious security threat
3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java
4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String,
5)The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.

Security and String pool being primary reason of making String immutable

Core Java Interview Questions Answers in Finance domain 
@TODO 
1. What is immutable object? Can you write immutable object?
top core java interview questions
Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. 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() Operator, 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 PermGen area of heap.

String s = new String("Test");
 

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.

4. How does substring () inside String works?
Another good Java interview question, I think answer is not sufficient but here it is “Substring creates new object out of source string by taking a portion of original string”. see my post How SubString works in Java for detailed answer of this Java question.


5. Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.

6. Where does these  two method comes in picture during get operation?
This core Java interview question is follow-up of previous Java question and candidate should know that once you mention hashCode, people are most likely ask How its used in HashMap. See 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?
This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

8. What is difference between Executor.submit() and Executer.execute() method ?
This Java interview question is from my list of Top 15 Java multi-threading question answers, Its getting popular day by day because of huge demand of Java developer with good concurrency skill. Answer of this Java interview question is that former returns an object of Futurewhich can be used to find result from worker thread)

By the way @vinit Saini suggested 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 exception 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 re-throw this exception, wrapped in an ExecutionException.


9. What is the difference between factory and abstract factory pattern?
This Java interview question is from my list of 20 Java design pattern interview question and its open for all of you to 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 byAutomobileFactoryUserFactoryRoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
You can also refer What is Factory method design pattern in Java to know more details.

10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double checked locking which is purpose of this Java interview question.


11. Can you write critical section code for singleton?
This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe. check 10 Interview questions on Singleton Pattern in Java for more details and questions answers

12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
core java interview questions and answers beginners
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


Read more: http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html#ixzz2Uf9xE7zL

C++ String Tokenizer

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
    token = s.substr(0, pos);
    std::cout << token << std::endl;
    s.erase(0, pos + delimiter.length());
}

std::string::npos

static const size_t npos = -1;
Maximum value for size_t
npos is a static member constant value with the greatest possible value for an element of type size_t. This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string". As a return value, it is usually used to indicate no matches. This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.
input: 1 2 3 4
vector<int> a; string line; getline(cin, line); size_t pos = 0; string token; string delimiter = " "; while ((pos = line.find(delimiter))!=std::string::npos) { token = line.substr(0, pos); a.push_back(atoi(token.c_str())); line.erase(0, pos + delimiter.length()); } a.push_back(atoi(line.c_str()));

Java Template

import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import java.util.ArrayList;
public class XXXXXX{
   
    /**
     * @param args the command line arguments
     */
    public static void main (String [] args) throws IOException {
       
       
        Scanner in = new Scanner(new File("./src/input.txt"));        // file input
        Formatter out = new Formatter(new File("./src/output.txt"));  // file output
       
        ArrayList<Integer> a = new ArrayList<Integer>();
        while(in.hasNext()){
            a.add(in.nextInt());
        }
        out.format("%s\n", a.toString());  // format() has the same syntax as printf()
       
        out.close();    // flush the output and close the output file
        System.exit(0); // likely needed in USACO
    }
}

Tuesday, May 28, 2013

JPA Examples

https://glassfish.java.net/javaee5/persistence/persistence-example.html
CUSTOMER
ID
NAME


ORDER_TABLE
ORDER_ID
SHIPPING_ADDRESS
CUSTOMER_ID
@Entity
public class Customer {

    private int id;
    private String name;
    private Collection
<Order> orders;

    @Id
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public 
String getName() {
        return name;
    }

    public void setName(String 
name) {
        this.
name = name;
    }


    @OneToMany(cascade=ALL, mappedBy="customer")
    public Collection<Order> getOrders() {
        return orders;
    }

    public void setOrders(Collection<Order> newValue) {
        this.orders = newValue;
    }

}


@Entity
@Table(name="ORDER_TABLE")

public class Order {

    private int id;
    private String address;
    private Customer customer;

    @Id
    
@Column(name="ORDER_ID")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    
@Column(name="SHIPPING_ADDRESS")
    public String getAddress() {
        return 
address;
    }

    public void set
Address(String address) {
        this.
address = address;
    }


    @ManyToOne()
    @JoinColumn(name="CUSTOMER_ID")

    public Customer getCustomer
() {
        return 
customer;
    }

    public void setCustomer
(Customer customer) {
        this.
customer = customer;
    }

}

Persisting POJO Entities

Now, let's create new instances, set up the relationships and persist all of them together using the CASCADE option that we set on the Customer entity. This code must be executed in a context of an active transaction.

    // Create new customer
    Customer customer0 = new Customer();
    customer0.setId(1);
    customer0.setName("Joe Smith");

    // Persist the customer
    em.persist(customer0);

    // Create 2 orders
    Order order1 = new Order();
    order1.setId(100);
    order1.setAddress("123 Main St. Anytown, USA");

    Order order2 = new Order();
    order2.setId(200);
    order2.setAddress("567 1st St. Random City, USA");

    // Associate orders with the customer.

Note that the association must be set on both sides of the relationship: on the customer side for the orders to be persisted when transaction commits, and on the order side because it is the owning side:

    customer0.getOrders().add(order1);
    order1.setCustomer(customer0);
 
    customer0.getOrders().add(order2);
    order2.setCustomer(customer0);
When this transaction commits, all three entities will be persisted in the database.

Query and Navigation

We'll use a new EntityManager to do the query, but will execute the query without an active transaction:

    // Create new EntityManager
    em = emf.createEntityManager();

    Query q = em.createQuery("select c from Customer c where c.name = :name");
    q.setParameter("name", "Joe Smith");
    
Our query is supposed to return a single customer, so we will use the Query method getSingleResult() to execute the query. This method would throw an exception if there is no or more than one matching customers.

    Customer c = (Customer)q.getSingleResult();


Now let's verify that the orders were also created by navigating from the Customer. 
You can print the orders, but we'll just check the size:
    
      Collection<Order> orders = c.getOrders();
    if (orders == null || orders.size() != 2) {
        throw new RuntimeException("Unexpected number of orders: "
                + ((orders == null)? "null" : "" + orders.size()));
    }

Merge and Removal of Persistent Instances

To remove an instance, it must be managed by this EntityManager. The code below uses a customer 'c' that had been detached from its persistence context. Removal of the Customer also removes related orders because of the CASCADE option set on the corresponding relationship. This code must be executed in a context of an active transaction.

    // Merge the customer to the new persistence context
    Customer c0 = em.merge(c); //step1

Note that merge() is not a void operation. It returns back a managed copy of the argument (and its related objects). Only this copy can be used for EntityManager operations.

    // Delete all records
    em.remove(c0); //step2


The rest of the configuration of the database and the persistence is on the webpage (NetBeans, GlassFish)
done

Part 2
https://schuchert.wikispaces.com/JPA+Tutorial+1+-+Getting+Started
package entity;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class PersonTest {
    private EntityManagerFactory emf;
 
    private EntityManager em;
 
    @Before
    public void initEmfAndEm() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ERROR);
 
        emf = Persistence.createEntityManagerFactory("examplePersistenceUnit");
        em = emf.createEntityManager();
    }
 
    @After
    public void cleanup() {
        em.close();
    }
 
    @Test
    public void emptyTest() {
    }
}
Person.java
package entity;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
 
@Entity
public class Person {
    @Id
    @GeneratedValue
    private int id;
    private String firstName;
    private char middleInitial;
    private String lastName;
    private String streetAddress1;
    private String streetAddress2;
    private String city;
    private String state;
    private String zip;
 
    public Person() {
    }
 
    public Person(final String fn, final char mi, final String ln,
            final String sa1, final String sa2, final String city,
            final String state, final String zip) {
        setFirstName(fn);
        setMiddleInitial(mi);
        setLastName(ln);
        setStreetAddress1(sa1);
        setStreetAddress2(sa2);
        setCity(city);
        setState(state);
        setZip(zip);
    }
then getters and setters
}

Update persistence.xml

Inserting and Querying

Add an Embedded Entity

When we created Person we directly included address information into them. This is alright, but what if we want to use Address in another class? Let's introduce a new entity, Address, and make it embedded. This means its fields will end up as columns in the table of the entity that contains it.

Add an Entity with a One to Many Relationship

    @OneToMany
    private Collection<Person> employees;

Make a Relationship Bi-Directional

@ManyToOne(optional = true)
    private Company job;
 
    public Company getJob() {
        return job;
    }
 
    public void setJob(Company job) {
        this.job = job;
    }
 
    // ...
@OneToMany(mappedBy = "job")
    private Collection<Person> employees;
   // update this method //Referential Integrity 
    public void hire(final Person p) {
        getEmployees().add(p);
        p.setJob(this);
    }
 
    // update this method
    public void fire(final Person p) {
        getEmployees().remove(p);
        p.setJob(null);
    }
done

Monday, May 27, 2013

UNIX: Terminal, File System, Users and Editors


1.  Command-line "Terminal"

You can provide additional options to a command; you can pipe the output of one command into another command; you can put a set of commands in a script to automate a task.
bash (Bourne Again Shell)
$ pwd  //print working dir 
.......

2.  Unix File System

Root Directory
Everything in Unix is a file - data files. Files are organized in directories (aka folders). The directories are organized in a hierarchical tree structure, starting from the root directory. 
"/usr/lib/jvm/jdk1.7.0_07/bin/javac". The leading "/" (forward slash) denotes the root directory. The sub-directories are also separated by a "/".
There is only one root directory for the entire Unix's file system.
Notes: Windows use "\" (back slash) as the directory separator, and may contain multiple root directories - one for each drive (e.g., c:\d:\).
one root dir in UNIX
multiple root dir in Windows, 
Home Directory
Unix is a multi-user operating system. home directory (for each user). The users' home directories are allocated under /home for Ubuntu.  The home directory of the current login user is denoted as "~". It contains sub-directories such as ~/Desktop~/Downloads~/Documents~/Movies,~/Music, and etc.
Pathname and Filename
To reference a file, you need to provide the pathname (directory and sub-directories names) and the filename. For example, in "/usr/lib/jvm/jdk1.7.0_07/bin/javac", the pathname is "/usr/lib/jvm/jdk1.7.0_07/bin/" and the filename is "javac".
The pathname can be specified in two ways:
  1. Absolute Pathname: An absolute path begins from the root directory (starts with "/"), and contains all the sub-directories (separated with "/") leading to the file, e.g., "/usr/lib/jvm/jdk1.7.0_07/bin/" (starting with root). An absolute path can also begin with the current user's home directory (starts with "~"), e.g., "~/Downloads/jdk" (starting with home dir). Suppose the current user is "peter", it maps to "/home/peter/Downloads/jdk" (in Linux).
  2. Relative Pathname: A relative path is relative to the so-called current working directory (pwd). A relative path does not begin with "/" or "~". For example, if the current working directory is "/usr/lib/jvm", then the relative pathname "jdk1.7.0_07/bin" refer to "/usr/lib/jvm/jdk1.7.0_07/bin".
Unix system is case sensitive, a rose is NOT a Rose, and is NOT a ROSE.

3.  Basic Commands

3.1  pwd (Print Current Working Directory)

3.2  cd (Change Working Directory)

To change current working directory, issue command "cd new-pathname" (change directory). You can specify new pathname in two ways: absolute or relative. An absolute path begins with a "/" (root directory) or "~" (home directory). A relative path is relative to the current working directory and does NOT begin with "/" or "~". For example,

3.3  ls (List Directory's Contents)

You can use command ls to list the contents of the current working directory, e.g.,
// List contents of current working directory in short format
$ ls
Desktop    Downloads         Music     Public     Videos
Documents  examples.desktop  Pictures  Templates
 
// List in long format
$ ls -l
total xx
drwxr-xr-x 2 myuser myuser 1024 Mar 22 21:32 Desktop
drwxr-xr-x 2 myuser myuser 1024 Mar 22 21:32 Documents
drwxr-xr-x 2 myuser myuser 1024 Mar 22 21:32 Downloads
-rw-r--r-- 1 myuser myuser 8445 Mar 22 17:30 examples.desktop
......
 
// Append file indicator (e.g., trailing / indicates a directory)
$ ls -F
Desktop/    Downloads/        Music/     Public/     Videos/
Documents/  examples.desktop  Pictures/  Templates/
Wildcard *
You can list selected files using wildcard *, which matches 0 or more (any) characters. For example,
$ ls *.java     // List files ending with ".java" in short format (default)
$ ls -l *.java  // List files ending with ".java" in long format
$ ls -ld my*     // List files and directories beginning with "my" in long format


3.4  catless (Viewing File Contents)

You can use commands catless or more to display contents of a text file on console. cat shows the entire file, which can be inconvenient for long file. less shows one page of the file. For example,
$ cat /proc/cpuinfo
  // Display the entire file
  // Use window's scroll-bar to scroll
 
$ less /proc/cpuinfo
  // Display one page of the file
  // Use Up|Down|PgUp|PgDown key to scroll, and press "q" to quit


3.5  Shortcut Keys - IMPORTANT

Previous Commands: You can use the up/down arrow keys to retrieve the previous/next command in the command history.
Copy/Paste:
  • Copy: shift+ctrl+c
  • Copy: shift+ctrl+v
  • middle-button: copy, paste, highlight
  • interrupt signial: ctrl+c
  • end of text input: ctrl+d
  • suspending current process: ctrl+z 

3.6  Other Frequently-used Commands

$ clear                // Clear Screen
$ who                  // List all login users
$ whoami               // Show the current login user
$ which program-name   // Show the location of the program, e.g., "which javac"

3.7  Getting Helps

$ help                // Show all the available commands
$ help command-name   // Show help for a specific command, e.g., "help cd"
$ man command-name    // Show the manual page for a specific command, e.g., "man cd"

4.  If you need to Install Software or Perform System tasks...

4.1  Regular Users vs. Superuser


To enable a user to sudo:
  • In Ubuntu: System Settings ⇒ User Accounts ⇒ Select the user ⇒ Unlock ⇒ Set the account type to "Administrator" (instead of "Standard User"), which adds the user to "sudo" group.

4.2  Processes

Unix is a multi-process, multi-user operating system. It can run many processes concurrently.
You can use GUI applications to view all running processes and terminate a particular process (similar to "Task Manager" in Windows).
  • In Mac OS X: launch "Activity Monitor" (Under /Applications/Utilities) and select "All Processes".
On command-line, you can use command ps to list all the processes and kill to terminate a particular process:
$ ps            // Print processes of current user
$ ps -e         // Print all processes
$ ps -ef        // Print all processes in full-listing
$ ps -ef | grep "mysql"  // Print processes containing mysql
$ ps aux | grep "mysql"  // same as above
$ top           // Display resource usage and top processes
 
$ kill pid      // Kill a particular possess with the given processID
$ kill -9 pid   // Force kill
in Windows: taskkill

5.2  Display Text files in Command-line - catlesshead and tail

If possible, use a graphical text editor to display a text file. Nonetheless, you can use the following commands to display a text file in command-line:
  • cat filename: Concantenate file or print the file to console.
  • less filename: Display the file in pages. You can scroll the display with up, down, pageup, pagedown keys. less replaces the legacy more.
  • head|tail filename: Display the first|last part of the file.
For example, let's display the /proc/cpuinfo file with these commands:
$ cat /proc/cpuinfo
   // Show entire file
   // Use the window's scroll-bar to scroll
 
$ less /proc/cpuinfo
   // Show one page
   // Use the Up|Down|PgUp|PgDown key to scroll
 
$ head /proc/cpuinfo
   // Show first page of the file
 
$ tail /proc/cpuinfo
   // Show last page of the file
More on cat
The command cat has many usages. You can use cat to concatenate (join) a few files. For example,
$ cat file1 file2 file3
   // display file1, file2 and file3 on the console
 
$ cat file1 file2 file3 > file4
   // Concatenate file1, file2 and file3 as file4
You can also use cat command to create a small text file. cat without argument uses standard input as its input. You could use ctrl+D to signal EOF. For example:
$ cat > out.txt
The quick brown fox jumps over the lazy dog[ctrl+D]
$ cat out.txt
The quick brown fox jumps over the lazy dog

done