Ebeworld’s Weblog

Trying to create

Very common questions

Tell me about yourself or about some of the recent projects you have worked with? What do you consider your most significant achievement? Why do you think you are qualified for this position? Why should we hire you and what kind of contributions will you make?

Â

􀂃 Design concepts and design patterns: How you understand and applied them.

􀂃 Performance and memory issues: How you identified and fixed them.

􀂃 Exception handling and best practices: How you understand and applied them.

􀂃 Multi-threading and concurrent access: How you identified and fixed them.

Â

Why are you leaving your current position?

􀂃 Do not criticize your previous employer or coworkers or sound too opportunistic.

􀂃 It is fine to mention a major problem like a buy out, budget constraints, merger or liquidation.

􀂃 You may also say that your chance to make a contribution is very low due to company wide changes or looking for a more challenging senior or designer role.

October 14, 2008 Posted by ebeworld | Interview Questions, Java | | No Comments Yet

memory leaks

In Java, typically memory leak occurs when an object of a longer lifecycle has a reference to objects of a short life cycle.This prevents the objects with short life cycle being garbage collected. The developer must remember to remove the references to the short-lived objects from the long-lived objects. Objects with the same life cycle do not cause any issues because the garbage collector is smart enough to deal with the circular references

October 14, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet

How would you improve performance of a Java application?

Pool valuable system resources like threads, database connections, socket connections etc. Emphasise on reuse of threads from a pool of threads. Creating new threads and discarding them after use can adversely affect performance. Also consider using multi-threading in your single-threaded applications where possible to enhance performance. Optimze the pool sizes based on system and application specifications and requirements.

􀂃 Optimize your I/O operations: use buffering (Refer Q21 in Java section) when writing to and reading from files and/or streams. Avoid writers/readers if you are dealing with only ASCII characters. You can use treams instead, which are faster. Avoid premature flushing of buffers. Also make use of the performance and scalability enhancing features such as non-blocking and asynchronous I/O, mapping of file to memory etc offered by the NIO (New I/O).

􀂃 Minimize network overheads by retrieving several related items simultaneously in one remote invocation if possible. Remote method invocations involve a network round-trip, marshalling and unmarshalling of parameters, which can cause huge performance problems if the remote interface is poorly designed.

ô€‚ƒ Establish whether you have a potential memory problem and manage your objects efficiently: remove references to the short-lived objects from long-lived objects like Java collections etc to minimise any potential memory leaks. Also reuse objects where possible. It is cheaper to recycle objects than creating new objects each time. Avoid creating extra objects unnecessarily. For example use mutable StringBuffer/StringBuilder classes instead of immutable String objects in computation expensive loops as discussed in Q17 in Java section. Automatic garbage collection is one of the most highly touted conveniences of Java. However, it comes at a price. Creating and destroying objects occupies a significant chunk of the JVM’s time. Wherever possible, you should look for ways to minimise the number of objects created in your code:

ô€‚ƒ If repeating code within a loop, avoid creating new objects for each iteration. Create objects before entering the loop (i.e. outside the loop) and reuse them if possible.Â

􀂃 For complex objects that are used frequently, consider creating a pool of recyclable objects rather than always instantiating new objects. This adds additional burden on the programmer to manage the pool, but in select cases can represent an order of magnitude performance gain.

􀂃 Use lazy initialization when you want to distribute the load of creating large amounts of objects. Use lazy initialization only when there is merit in the design.

􀂃 Where applicable apply the following performance tips in your code:

􀂃 Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc where possible. This is because the methods in ArrayList, HashMap etc are not synchronized (Refer Q13 in Java Section). Even better is to use just arrays where possible.

􀂃 Set the initial capacity of a collection (e.g. ArrayList, HashMap etc) and StringBuffer/StringBuilder appropriately. This is because these classes must grow periodically to accommodate new elements.

So, if you have a very large ArrayList or a StringBuffer, and you know the size in advance then you can

speed things up by setting the initial size appropriately. (Refer Q15, Q17 in Java Section).

Minimise the use of casting or runtime type checking like instanceof in frequently executed methods

or in loops. The “casting” and “instanceof” checks for a class marked as final will be faster. Using

“instanceof” construct is not only ugly but also unmaintainable. Look at using visitor pattern (Refer

Q11 in How would you go about…? section) to avoid “instanceof” construct.

􀂃 Do not compute constants inside a large loop. Compute them outside the loop. For applets compute it

in the init() method.

􀂃 Exception creation can be expensive because it has to create the full stack trace. The stack trace is

obviously useful if you are planning to log or display the exception to the user. But if you are using your

exception to just control the flow, which is not recommended, then throw an exception, which is precreated.

An efficient way to do this is to declare a public static final Exception in your exception class

itself.

􀂃 Avoid using System.out.println and use logging frameworks like Log4J etc, which uses I/O buffers

(Refer Q21 in Java section).

􀂃 Minimise calls to Date, Calendar, etc related classes.

􀂃 Minimise JNI calls in your code.

October 14, 2008 Posted by ebeworld | Interview Questions, Java | | No Comments Yet

Benefit of using Swing over AWT

What is the difference between AWT and Swing? LF DC

 Swing provides a richer set of components than AWT. They are 100% Java-based. There are a few other advantages to Swing over AWT:

• Swing provides both additional components like JTable, JTree etc and added functionality to AWT-replacement components.

• Swing components can change their appearance based on the current “look and feel” library that’s being used.

• Swing components follow the Model-View-Controller (MVC) paradigm, and thus can provide a much more

flexible UI.

• Swing provides “extras” for components, such as: icons on many components, decorative borders for

components, tool tips for components etc.

• Swing components are lightweight (less resource intensive than AWT).

Swing provides built-in double buffering (which means an off-screen buffer [image] is used during drawing

and then the resulting bits are copied onto the screen. The resulting image is smoother, less flicker and quicker than drawing directly on the screen).

• Swing provides paint debugging support for when you build your own component i.e.-slow motion rendering.

Swing also has a few disadvantages:

• If you’re not very careful when programming, it can be slower than AWT (all components are drawn).

• Swing components that look like native components might not behave exactly like native components.

October 14, 2008 Posted by ebeworld | Java, TopCoder | , | No Comments Yet

Swing Layouts

Explain layout managers?

Layout managers are used for arranging GUI components in windows. The standard layout managers are:

• FlowLayout: Default layout for Applet and Panel. Lays out components from left to right, starting new rows if necessary.

• BorderLayout: Default layout for Frame and Dialog. Lays out components in north, south, east, west and

center. All extra space is placed on the center.

• CardLayout: stack of same size components arranged inside each other. Only one is visible at any time. Used in TABs.

• GridLayout: Makes a bunch of components equal in size and displays them in the requested number of rows

and columns.

• GridBagLayout: Most complicated but the most flexible. It aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The rows in the grid aren’t necessarily all the same height, similarly, grid columns can have different widths as well.

BoxLayout: is a full-featured version of FlowLayout. It stacks the components on top of each other or places  them in a row.

October 14, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet

Applet event sequence

What is the order of method invocation in an applet? LF

The Applet’s life cycle methods are as follows:

• public void init() : Initialization method called only once by the browser.

• public void start() : Method called after init() and contains code to start processing. If the user leaves the

page and returns without killing the current browser session, the start () method is called without being

preceded by init ().

• public void stop() : Stops all processing started by start (). Done if user moves off page.

• public void destroy() : Called if current browser session is being terminated. Frees all resources used by the

applet.

October 14, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet

Socket for interprocess communication

Sockets are communication channels, which facilitate inter-process communication. Never thought in this way, i always thought socket is for network related stuffs only.

October 14, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet

Java Synchronized collection

Returns a synchronized (thread-safe) collection backed by the specified collection. In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collection.It is imperative that the user manually synchronize on the returned collection when iterating over it:

  Collection c = Collections.synchronizedCollection(myCollection);
     ...
  synchronized(c) {
      Iterator i = c.iterator(); // Must be in the synchronized block
      while (i.hasNext())
         foo(i.next());
  }

October 14, 2008 Posted by ebeworld | Interview Questions, Java | | No Comments Yet

Java checked and unchecked exceptions

exceptFig4

October 14, 2008 Posted by ebeworld | Interview Questions, Java | | No Comments Yet

Java Reference Types

  1. The JVM holds onto regular Objects until they are no longer reachable by either clients or any container. In other words Objects are garbage collected when there are no more live references to them. Dead references don’t count.
  2. Soft references can be deleted from a container if the clients are no longer referencing them and memory is tight.
  3. Weak references are automatically deleted from a container as soon clients stop referencing them.
  4. Phantom references point to objects that are already dead and have been finalised.

 

 

 

Soft vs Weak vs Phantom References
Type Purpose Use When GCed Implementing Class
Strong Reference An ordinary reference. Keeps objects alive as long as they are referenced. normal reference. Any object not pointed to can be reclaimed. default
Soft Reference Keeps objects alive provided there’s enough memory. to keep objects alive even after clients have removed their references (memory-sensitive caches), in case clients start asking for them again by key. After a first gc pass, the JVM decides it still needs to reclaim more space. java.lang.ref.SoftReference
Weak Reference Keeps objects alive only while they’re in use (reachable) by clients. Containers that automatically delete objects no longer in use. After gc determines the object is only weakly reachable java.lang.ref.WeakReference
java.util.WeakHashMap
Phantom Reference Lets you clean up after finalization but before the space is reclaimed (replaces or augments the use of finalize()) Special clean up processing After finalization. java.lang.ref.PhantomReference

October 13, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet