Interview stuff



Java 5

See http://www.leepoint.net/notes-java/index.html for loads of excellent Java stuff.

Remember that when you declare

List<String> fred;

that fred is a reference, not an object.

Strings

In the following, how many objects are created?

String a, b, c;   (none; all are references)
a = "1; (creates 1)
b = a;  (creates none)
a = "2"; (creates another 1; strings are fixed).

Remember that objects of these types can't be changed.  If they appear to be, in fact new objects are created and the reference reassigned.  Two String references which have the same content point to the same String instance.

Doing clever stuff, appending, reversing, substrings, etc, with String is best done with StringBuffer (synchronized) or StringBuilder (not synchronized and added in java 5).

String comparison

Arrays

Arrays.asList() to convert to a list.

Difference between (old) enumeration and iterators

Enumeration does not have remove method but iteration has.......  

Difference between Vector and ArrayList

Vector is synchronized.

Synchronized

If applied to a method, means that only one instance of that method will execute at any time, thereby guaranteeing that it is threadsafe. 

public synchronized void increment() { 
    c++; 
}

Generics

Type-safe collections:  List<String> = new ArrayList<String>();

For/In (Enhanced for)

Mainly about ditching iterators.  Works on arrays [] and collections implementing iterable.

for (String x : mylist) {
     System.out.println(x);
}

You can't determine where you are in the list, tho.  Nor can you delete while doing this; use remove in an iterator.

Java IO

... add here...

Threading

... they were interested in this...

Static imports

import static java.lang.System.out;

This would allow you to import static classes and just use the class methods (such as sysout) rather than fully qualifying them.

Static anonymous blocks in classes

These are executed first, even before a static main method.

LinkedHashMap

Ordered in insertion order.

Questions off the web

Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow it). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized. 

Q: What is the difference between an Interface and an Abstract class? 
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 

Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. 

Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.

Q: What is static in java?
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

Q: What is final?
A: A final class can't be extended i.e., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).


JDBC

...


JSF

We used a Tomahawk component in eRoute.  Examples: http://www.irian.at/myfacesexamples/home.jsf  and the t:datatable.  See also http://www.irian.at/myfaces 

Project contained an index.jsp which did a jsp:forward to Login.jsf.

Faces-config.xml

Contains a list of the JSF's and Navigation rules between them, plus a list of Managed beans.

Navigation rules specify from-view-id, and then  navigation-cases: from-outcome this means to-view-id xxx.jsf (outcomes are strings, e.g. 'success' and 'system-failure').

The managed beans specify the name used in the jsp, the full class name, and the scope (creation/destruction).  Scopes include application, session, or request.

The JSF files

jsf is a jsp, but everything is inside an <f:view>.  Inside that is an <h:form>

Import at least 2 tag libs, <%@ taglib uri=... prefix="h"%>, for jsf/core and jsf/html.

<f:loadBundle> to pull in the messages.  <h:outputText value="#{msg.loginIntro}" /> to display them.

tags: <h:selectOneListBox>, <h:outputLink>, <h:commandButton ... action="#{custodianBean.updateCustodian}"> (this last one uses an action method in the bean, which returns a String).  <t:commandLink>, <f:verbatim>

The Backing beans

These are normal java beans.  They are declared as 'Managed beans' in the faces-config.xml.

Other code

MailSender using Java Mail API to send emails.

JPA to access db's, HSQLDB to do in memory tests.  DAO pattern to wrap JPA beans.  Get entity managers from persistence.xml?

Testing

Shale to mimic some of the environment; requests.  Not very good as yet.

Selenium exported as JUnit.


Javascript

function clearCustodian(formName) {
       var theForm = document.forms[formName];
       theForm.custodianFullNameReadOnly.value = "";
       theForm.custodianFullName.value = "";
       theForm.custodianText.value = "";
}
function openUserGuide() {
      var props = "location=0, menubar=0, toolbar=0, scrollbars=1, statusbar=0, resizable=1, width=600, height=5000";
      window.open("http://mdritwiki.gsk.com/tw/bin/view/MDRIT/Portfolio/ERouteUserGuide?skin=print%REVARG%", "UserGuide", props);
}

Use a semi-transparent div the size of the page and animate it.

/**
* Set focus on the surname on load
*/
function setSurname() {
document.forms["userLookupForm"].elements["surname"].focus();
}

Servlets

Extend HttpServlet.  Persist in memory so faster than CGI.

 


Enterprise Architecture

The request comes in

Everything is a servlet.  The HTTP request comes in as an ASCII string to the web server, which then passes it to the servlet container which creates an instance of the servlet and passes in the request.  This processes it, and pushes back an ASCII string -- the response -- down the wire.  Inside the servlet, you have classes which contain the request/response.

EJB's

Stateless session beans

If the web server is an application server, it has an EJB container.  The servlet then passes the request to a stateless session bean using it's remote interface, which is created by the EJB container, one per session.  Being stateless it contains no data -- just code, so can be instantiated and destroyed by the container quickly.  Persisting data is expensive.   @Stateless is the EJB3 annotation, which creates the bean interface automatically.

Stateful session beans

You can also use stateful session beans, to persist information in the session; however these do not scale as well, since they require more resources to persist their state and activate/deactivate them.

Entity beans (inc. JPA beans)

To persist data, we use Entity beans (annotated with the @Entity descriptor).  These wrap around the JDBC stuff.  They persist -- we use hibernate to persist them.  They have no remote or local interface; they are just POJO's.  Instance fields are saved to the database, unless annotated as @Transient.  The bean contents are saved using persist(); removed using remove().  

Session beans create entity beans using query methods on the EntityManager.  (Factory pattern...?)

Entity beans contain getters and setters for all persistent fields.  They may contain other logic.  They must have a field which is the primary key of the table (@Id).  They implement Serializable.

Container managed persistence is the name for the automatic population and update of stuff put into these beans and saved using persist, with all the wiring in persistence.xml.  The other alternative is 'bean managed persistence' where the bean itself contains all the JDBC code required to deal with the database.  It's not supported in EJB3; you have to use EJB 2.1.

@PersistenceContext

Insert an EMF using an annotation (more error prone than just injecting an EntityManager as the programmer has to remember more things).  EJB3 p.74-5.

@PersistenceUnit(unitName="CUSTDB")
private EntityManagerFactory emf;

Insert an entity manager, which is container managed:

@PersistenceContext(unitName="CUSTDB")
private EntityManager custDb;

You must never use close() on an injected entity manager.

How to find a bean (JNDI)

How do we find out entity beans from inside a stateless session bean?  Or another session bean from inside the first one?

Use JNDI to look it up.  (For entity beans we use an entity manager to create or query them, and we get the entity manager from the persistence.xml).

We can use annotation, as in MDB's

@Resource(mappedName = "java:/ConnectionFactory")
private TopicConnectionFactory connectionFactory;

eRoute method of retrieving entityManager

We had a filter which ran at the start EntityManagerFilter.java which created an entitymanager and stored it in the request:

/**
* Allocate a new EntityManager for each request and makes
* sure it is destroyed at the end of the request processing.
*/
public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
EntityManager em = this.routingEmf.createEntityManager();
HttpServletRequest request = (HttpServletRequest) req;
request.setAttribute(GlobalConstants.ESUBMISSION_ENTITY_MANAGER, em);

from where it was picked up in the ListProjectCodesBean.java:

    private ProjectP3IManagerService getProjectP3IManagerService() {
	// return always a new instance as EM is recreated between requests
	Context context = new Context(FacesContext.getCurrentInstance());
	return new ProjectP3IManagerServiceImpl(context, context.getProjectEntityManager(), 
                    context.getTmaEntityManager(),context.getESubmissionEntityManager());
     }

using the context class:

public EntityManager getTmaEntityManager() {
    return (EntityManager) getRequest().getAttribute(GlobalConstants.TMA_ENTITY_MANAGER);
}

What does @Local mean?

The business interface on an EJB is a local interface (accessible from within the same JVM only), rather than remote (accessible from other deployments).  Local interfaces pass by reference; remote ones by value.  (See EJB3 book p.216-7)  Local is therefore more efficient.


Portlets (JSR 168)

People are now selling portal servers.  These provide lots of stuff to run web sites.  In order to fit inside these, you write portlets rather than servlets, which populate one small bit of the screen.  They have no access to the HTTP headers (so no cookies); otherwise they are like servlets.

They are used to integrate disparate data sources into a web site in a cleanly-separated way.

Portlets form a design pattern where a Portal servlet combines one or more component Portlets into a web page. Because the portlets are written as components, they can be cleanly written and tested. Applications which currently use many servlet includes might be more cleanly written as portlet applications.

The Portal part of the pattern is a servlet which manages the portlets. In the Hello World example, the servlet is a simple "invoker" which calls a single portlet to render the page.

I identified following articles that can be useful in click start learning of JSR 168 portlets -

Understanding the Java Portlet Specification

Developing to the Java Portlet Specification

Introducing the Portlet Specification, Part 1

Introducing the Portlet Specification, Part 2

Seeing such a slack of portlet development articles, I have started working on "hands-on" type tutorial on portlet development that I'll post here soon. Till the time the second article i.e. "Developing to the Java Portlet Specification" can be the good starting point.

JSR 168 portlets

http://developers.sun.com/portalserver/reference/techart/portlets.html 

doView().  doEdit().  init().  processAction().

Depends what mode the portlet is called in.  If in view mode, calls doView(); if in edit mode, doEdit().  These display the portlet.  The user then hits a button, which runs processAction().  You can get the portletSession (like httpSession) from request:

PortletSession session = request.getPortletSession(true);

In processAction, you can test the mode:

if(request.getPortletMode().equals(PortletMode.EDIT))

Then store whatever and then

if (isValid) { response.setPortletMode(PortletMode.VIEW); }

And the portlet returns to VIEW mode.

The Java Portlet Specification allows a portlet or portlets to be packaged as a .war file for deployment to a J2EE application server. Just like a .war file used to deploy a typical J2EE web application, it contains a WEB-INF/web.xml file to configure the application context. However, with a portlet application, the WEB-INF folder must also contain a portlet.xml file. The portlet.xml file is a descriptor file, containing configuration details about all bundled portlets in the .war file.

Resin stuff (Looks as if this is JSR168 compliant)

http://www.caucho.com/resin-3.0/portlet/index.xtp 

http://www.caucho.com/resin-3.0/portlet/tutorial/basic-hello/index.xtp - resin portlets tutorial, sample, web.xml.

WEB-INF/classes/example/HelloWorldPortlet.java
package example;

import java.io.PrintWriter;
import java.io.IOException;

import javax.portlet.GenericPortlet;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.PortletException;

public class HelloWorldPortlet extends GenericPortlet {
  /**
   * The portlet's main view prints "Hello, World"
   */
  public void doView(RenderRequest request, RenderResponse response)
    throws PortletException, IOException
  {
    PrintWriter out = response.getWriter();

    out.println("Hello, World");
  }
}
  
WEB-INF/web.xml
<web-app xmlns="http://caucho.com/ns/resin"
         xmlns:resin="http://caucho.com/ns/resin/core">

  <servlet servlet-name="hello" 
           servlet-class="com.caucho.portal.generic.PortletServlet">
    <init>
      <portlet resin:type="example.HelloWorldPortlet"/>
    </init>
  </servlet>

  <servlet-mapping url-pattern="/hello" servlet-name="hello"/>
</web-app>

A Portlet is a class that implements class javax.portlet.Portlet . It is similar to a servlet.

The HelloWorldPortlet in this tutorial sends a Hello, World message to the browser.

And http://www.caucho.com/resin-3.0/portlet/tutorial/basic-jsp/index.xtp 

hello.jsp
<%@ page session="false" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>

<portlet:defineObjects/>

<c:choose>
<c:when test="${'edit' eq renderRequest.portletMode}">

<portlet:actionUrl var="submitUrl" portletMode="edit"/>

<form method='POST' action='${submitUrl}'>
        Name: <input type='text' name='identity' value='${identity}'/>
        <br/>
        Color: <input type='text' name='color' value='${color}'/>
        <br/>
        <input type='submit'/>
</form>

</c:when>
<c:otherwise>

<portlet:renderUrl var="editUrl" portletMode="edit"/>

Hello, ${identity}.
Your favorite color is ${color}
<p>
<a href='${editUrl}'>Edit</a>

</c:otherwise>
</c:choose>

UML

http://www.agilemodeling.com/artifacts/useCaseDiagram.htm - use case diagrams.  "use case diagrams overview the usage requirements for a system.  They are useful for presentations to management".


http://www.agilemodeling.com/artifacts/classDiagram.htm - class diagram.  "UML 2 class diagrams show the classes of the system, their interrelationships (including inheritance, aggregation, and association), and the operations and attributes of the classes."

Classes are depicted as boxes with three sections, the top one indicates the name of the class, the middle one lists the attributes of the class, and the third one lists the methods.  


This page has been accessed by  ****** people since 15th April 2008.


Return to Roger Pearse's Pages