Thursday, 19 November 2015

core java

1. static initialize block

class person {
    private static final date boom_start;

    static {
        Calendar gmtcal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        gmtcal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
        boom_start = gmtcal.getTime();
    }
}
  • the static initializer for a class gets run when the class is first accessed, either to create an instance, or to access a static method or field.

2. object instance initialize sequence
  • super()
  • static initilizer
  • instance field initialzer
  • constructor

3. wildcard
 
List<? extends Number>
matches a list of type Number or any of its subclasses
<? super A>
matches a list of type A or any of its superclasses


4. java collection interface
  • set -  no duplicated element, at most one null
  • list
  • queue - usually FIFO, exception priority queue
  • deque - 'deck', double ended queue
      map
  • treemap - sort in natural order
  • linkedhashmap - sort in insertion order

5. java collection implementation (sorted vs unsorted)
  • set - hashset, treeset, linkedhashset
  • list - arraylist, linkedlist
  • map - hashmap, treemap, linkedhashmap
  • queue - linkedlist, priorityqueue
  • deque - linkedlist, arraydeque

6. java thread-safe collection (java.util.concurrent)
  • collection in java.util is not safe, except hashtable and vector
  • always safe to use concurrent collection than 'synchronized wrapper'
  • java.util.concurrent example - concurrenthashmap


7. java hash map
  • record are stored in bucket
  • hash function calculate hash code based on record
  • hash code is indexing to the bucket
  • if an object is used as "key" in hash map, you need to implement hashcode() and equals() for the object
  • hashcode() is used to calculate store location, equals() is used when there is a collision

8. stringbuffer vs stringbuilder
  • stringbuffer is synchronized, stringbuilder is not

9. vector vs arraylist
  • vector is synchronized, arraylist is not

10.  hashtable vs hashmap
  • hashtable is synchronized, hashmap is not

11. primitive vs object
  • primitives: byte, short, int, long, float, double, boolean, char
  • object: the rest

12. equals() vs ==
  • equals() is comparison of value
  • == is comparison of reference
  • if no parent class override equals(), then finally it goes to 'Object' equals(), which is ==
  • if you override equals(), you need to override hashcode(),  so that if two objects equal(), they have the same hashcode(). it is required by java
  • reversal of the above is not necessarily true
  • in eclipse, Source --> Generate equals() and hashCode()

13. generics
  • user 'type' as parameters when defining class, interface, methods 
  • do you need to add to the List? Do you care what is in the list? 
      yes yes - use List<Foo>
      yes no - use List<? super Foo>
      no yes - use <? extends Foo> --- most common
      no no - use <?>

14. how to overide equals() for assertEquals(obj1, obj2)

@Override
    public boolean equals(Object other){
        boolean equal = false;
        if (other instanceof Money){
            Money otherMoney = (Money)other;
            equal = (this.dollars() == otherMoney.dollars()
                       && this.cents() == otherMoney.cents());
        }
        return equal;
    }


15. comparable vs comparator
      public interface Comparable<T> {
          public int compareTo(T o);
      }
      public interface Comparator<T> {
          int compare(T o1, T o2);
      }
  • comparable is used to define natural order of object, and is implemented by the class itself
  • comparator is used to define external ordering of object, and is implemented by an external comparator class
  • multiple comparator class are implemented when multiple ways are needed to compare two instance

16. jdbc related

      transaction
  • a set of one or more SQL statements
  • transaction ends with either a commit or a rollback
      stored procedures
  • a group of SQL statements that can be called by name

17. final, finally, finalize
      private final String name = "foo";
      public final String toString() {  return "NULL"; }

      try {
        //do stuff
      } catch (SomeException se) {
        //handle se
      } finally {
        lock.unlock(); //always executed, even if Exception or Error or se
      }

      protected void finalize()
       //is called when an object is garbage collected
       //rarely need to override
      { //free resources (e.g. unallocate memory) super.finalize(); }


18. java IO
  • byte based is called 'stream' (InputStream, OutputStream)
  • character based is called 'reader/writer' ()
  • stringreader turns a string into a reader, so that it can be passed to component that accept reader

19. xml
  • xml schema describes the structure of an xml document

20. jaxb
  • marshalling: convert java object to xml file
  • annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object/xml conversion

21. system.getenv() vs. system.getproperty()
  • system.getenv() is for operating system environment variables
  • system.getproperty() is for jvm arguments which are passed as '-DpropName=value' to java application launcher

22. handle exceptions
  • checked exception
  • run-time exception

23. concurrency and coordination
  • 'synchronized' keyword lock on current object
  • 'wait()', 'notify()', 'notifyall()' must be called in 'synchronized' context 
  • 'wait()' suspend current thread until 'notify(), notifyall()'
  • 'notify(), notifyall()' wake up other thread(s)
  • 'join' wait for other thread to die

24. thread
  • implement runnable interface vs extend thread class

25. prefer interface to abstract class
  • interface is more flexible, avoid class hierarchy constraint (abstract class has to use inheritance)
  • interface is a blueprint that need full implementation, abstract class need partial design
  • interface can have 'default' method that has implementation

26. object serialization
  • what gets serialized is the "value" of the object, or the contents
  • methods are not serialized

27. java 8 stream
  • any type that implement 'Iterable' interface can be converted to stream using .stream()
  • intermediate operation returns a new modified stream
  • we can only use one terminal operation per stream
  • execute a terminal operation makes stream inaccessible
  • intermediate operations are lazy
  • in both reduce and collect, there're 3 params, identity (initial value), accumulator (how elements are added up), combiner (how result of multiple streams are added)
List<Customer> customersWithMoreThan100Points = customers         //filter objects
  .stream()
  .filter(c -> c.getPoints() > 100)
  .collect(Collectors.toList());

List<StaffPublic> result = staff.stream().map(temp -> {                       //convert objects
    StaffPublic obj = new StaffPublic();
    obj.setName(temp.getName());
    obj.setAge(temp.getAge());
    if ("mkyong".equals(temp.getName())) {
        obj.setExtra("this field is for mkyong only!");
    }
    return obj;
}).collect(Collectors.toList());


References:
1. top 25 java interview questions
2. java == vs equals() confusion
3. java collection class
4. java generics 
5. understanding collections and thread safety in java
6. java 8 map, filter and collect

No comments:

Post a Comment