Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, July 1, 2013

Dynamic Binding in Java

Dynamic Binding

class Father{
a(){ ... }
b(){a();}
}
class Son extends Father{
a(){ ..... }} //override

Saturday, June 8, 2013

Reflection in Java (and a little Python)

toString(), iterates through every attributes in a Class


public class Formatter {
    public static String toString(Object aObject) {
        StringBuilder result = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        
        result.append( aObject.getClass().getName() );
        result.append( " Object {" );
        result.append(newLine);
        
        //determine fields declared in aObject class only (no fields of superclass)
        Field[] fields = aObject.getClass().getDeclaredFields();
        
        //print field names paired with their values
        for ( Field field : fields  ) {
            result.append("  ");
            try {
                field.setAccessible(true);
                result.append( field.getName() );
                result.append(": ");
                //requires access to private field:
                result.append( field.get(aObject) );
            } catch ( IllegalAccessException ex ) {
                System.out.println(ex);
            }
            result.append(newLine);
        }
        result.append("}");
        
        return result.toString();
    }

}

Friday, June 7, 2013

Java Serialization Tutorial

source: http://www.tutorialspoint.com/java/java_serialization.htm

like pickle in Python:
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

Thursday, June 6, 2013

Permutation in Java and C++

C++

from #include<algorithm>
int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
  // print a's elements
} while(std::next_permutation(a, a+size));

JAVA

public class Permute{
    static void permute(java.util.List<Integer> arr, int k){
        for(int i = k; i < arr.size(); i++){
            java.util.Collections.swap(arr, i, k);
            permute(arr, k+1);
            java.util.Collections.swap(arr, k, i);
        }
        if (k == arr.size() -1){
            System.out.println(java.util.Arrays.toString(arr.toArray()));
        }
    }
    public static void main(String[] args){
        Permute.permute(java.util.Arrays.asList(3,4,6,2,1), 0);
    }
}
You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element. The tricky part is that after recursive call you must swap i-th element with first element back, otherwise you could get repeated values at the first spot. By swapping it back we restore order of elements (basically you do backtracking).
done

Wednesday, June 5, 2013

File IO in Java

Write: close the BufferWriter as well as FileWriter
Code:
//TODO

Monday, June 3, 2013

Thinking in Java

Cleanup: finalization (finialize()) and garbage collection 

  1. Your object might not get garbage collected 
  2. Garbage collection is not destruction 
  3. Garbage collection is only about memory
Force garbage collection:
System.gc();

use of finalize:
protected void finalize(){
  if(some conditions)
      errorMessage;
}

Array 

int[] a; 
Random rand = new Random(47); 
a = new int[rand.nextInt(20)]; 

Inner Class

inner class and surrounding class 
public class Parcel1 { class Contents { //protected, also can be + -; private int attribute; public int method() { return 0; } }









OuterClassName.InnerClassName

Out.Inner inner = out.getInner(); 


In addition, inner classes have access rights (link) to all the elements in the enclosing class. (different from C++ which does not have links) 
done

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

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