Google

Jan 30, 2014

Are you finding it hard to get good Java jobs? Are you putting yourself in hiring employers' shoes?

Are you finding hard to get good Java jobs?

Are you just offering what you have for your prospective employers or putting  yourself in hiring employers' shoes?

Here are some examples as to why employers favor experience to just academic qualifications.
  • We work in an agile development environment and all tasks are time boxed, hence we need an experienced developer. A burn down chart is generally used to measure progress.
  • We have a very tight deadline and need an experienced Java resource to help us meet the dates.
  • We lack Drools experience in our current team, hence we need a Java developer with Drools experience.
  • We need a junior developer with some exposure to Spring, Hibernate, and web development so that he or she can start contributing from day 1. We are happy to provide some basic training.
In real life situation things are not as black and white as academic situation. You won't work in isolation, but in a multi-disciplinary and multi-cultural teams with varying personalities. You will be faced with both technical and non-technical challenges.  You need to have the right balance of technical and soft skills to get things done.

Putting yourself in hiring employers' shoes

Employers are in general looking for the following qualities, which you can acquire from gaining some experience.
  • Implementing a solution for the given requirements by asking the right questions. You need to have the ability to translate the functional requirements into technical details and then implement them. For example, an online order placement system that has a web interface to gather user input and then persist this data to a database.
  • Problem solving and critical analysis skills to identify and fix problems that arise relating to the 16 key areas like performance issues, memory leaks, security holes, etc. Critically review your work and others' to improve the quality of the software you build. Tactfully convey your critical analytical thinking to others when you perform code reviews or synchronize others' changes to your local development environment. It is a good practice to review others' work to identify any potential issues, but also you can learn a lot from others' quality craftsmanship. This is what open source contribution and participation will help you achieve. Review carefully all the working code in this blog posts. Read the code first and then try writing the code yourself.
  • Effectively communicating your thoughts to wider audiences both technical and non technical. Don't use technical jargon with the business. Focus on both verbal and written communication skills. Active listening is a key part of effective communication. Use visual tools like screen shots,  conceptual diagrams, UML diagrams, entity relationships (i.e ER) diagrams and power point presentations to communicate your ideas and convince others.
  • Emotional intelligence to work as a team. You need to control your emotions and understand others' too. You want others to be delighted to have you on their teams. Handle criticisms well and treat others with respect as how you would like to be treated. Have empathy to put yourself in others' shoes. 
  • Quick learner and passionate about the chosen field. Learning is an ongoing process. Take on new challenges by being open to learn new technologies, frameworks, and tools.
  • Analytical thinking and researching skills to meet the business objectives  and deadlines by being creative, researching, learning from your own and others' mistakes and picking yours' and others' brains. Many things are not black and white in the real world and you need to make trade offs -- for example, between tactical versus strategic solutions, build new versus enhance existing system, overnight batch run versus web based interface, etc. Understand the various conceptual architectures and often you need to provide hybrid solutions that suits your environment. Analyze when to use what.
  • Coding skills --  iteration versus recursion, understanding of the data structures and algorithms, applying the best practices and design patterns, understanding of the potential pitfalls, writing testable and readable code, good diagnostic skills, etc.
  • Leadership and mentoring skills by taking initiatives  to get the business requirements clarified and properly documented, filling in for your manager when he or she is away, and helping your fellow team members and new starters.
  • Right attitudes: No "I know it all or I can't be wrong" attitude. Motivation to say "I can do it". Courage to accept your mistakes -- "it was my bad or mistake". Being positive to say "It can be done".



Q. What questions do employers ask to see if you have the above skills?
A. This was covered in detail in my book entitled "How to open more doors as a software engineer"

Even if you don't get any specific questions, you can show off the above qualities when asked open-ended questions like

Q. Tell me about yourself?
Q. Can you give a 100 feet overview of the last application you worked in?
Q. Do you have role models? Where do you get your daily technical doses?
Q. Why do you like software engineering?
Q. What are your short term and long term goals?
Q. How will you critically review your fellow developers' work?
Q. What challenges did you face in your last assignment and how did you go about solving them?

You need to seize the opportunity to sell yourself without over-doing or bragging without any substance or evidence. Provide real life examples where appropriate, and be prepared for follow-up technical questions. So, don't lie.

If you say the following in your resume or at the job interview
  • Redesigned and rewrote the data-packager with 300% performance improvement along with ability to extend, reuse, and maintain the application through proper OO design with patterns.
you need to back it up in the job interviews as to how you accomplished such a significant performance gain.

The competition is getting more fiercer every year, so it really pays to regularly invest on your career by acquiring the sought-after skills. This becomes even more vital for the freelancers and contractors who change jobs more frequently. Even though you are a techie, you need to acquire the right skills to market yourself. This is the main driver for my book "How to open more doors as a software engineer", which is a 30% technical, 30% marketing know hows, and 40% motivational to take your career to the next level.

Tip: The above skills will be under scrutiny in your resume and at the job interviews. So, carefully craft your resume to bring out both your technical and non-technical skills. Don't just list the tasks you performed, but emphasize on your accomplishments and the difference you made. Before attending job interviews review your resume and reflect back on your experiences to convince your prospective employer that you are not just a techie, but possess the above qualities to get things done  in a real environment, which is full of unexpected challenges and dealings with people with emotions. You need to thrive in a team environment by working independently and as a part of a team.

If you need more insights, our "Java/JEE resume companion" and "How to open More Doors as Software Engineer?" will provide that in more detail with examples.

Labels:

Exposing a Java class as a MXBean

This Java tutorial extends Java ExecutorService for multi-threading -- coding question and tutorial by exposing it as an MXBean so that MXBean properties can be viewed and set via JConsole as demonstrated below.

Step 1:  The changes from the previous tutorial are

1. It implements SumEngineMXBean interface  with the naming convention suffix MXBean and the methods that needs to be exposed must be defined.
2. The thread pool size is managed via threadPoolSize variable and it needs to have getThreadPoolSize( ) and setThreadPoolSize(int threadPoolSize) methods to view and modify this variable JConsole, which is a JMX console to monitor your JVM.
3. The getRequestsCount( ) is also managed via JMX to view the requests counts via JConsole.

package com.mycompany.metrics;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class SumEngine implements SumEngineMXBean{

private final AtomicInteger requestsCount = new AtomicInteger();

 private ExecutorService executionService = null;
 private int threadPoolSize = 1;

 //executes requests to sum
 public void execute(SumRequest... request) {
  executionService = Executors.newFixedThreadPool(threadPoolSize); //create a thread pool
  List<Callable<SumResponse>> tasks = createExecuteTasks(request);
  List<Future<SumResponse>> results = execute(tasks);
  for (Future<SumResponse> result : results) {

   try {
    System.out.println(Thread.currentThread().getName() + ": Response = " + result.get());
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }
  }
  
  //initiates an orderly shutdown of thread pool
  executionService.shutdown();
 }

 //create tasks
 private List<Callable<SumResponse>> createExecuteTasks(SumRequest[] requests) {
  List<Callable<SumResponse>> tasks = new LinkedList<Callable<SumResponse>>();
  executingRequests(requests.length);
  for (SumRequest req : requests) {
   Callable<SumResponse> task = createTask(req);
   tasks.add(task);
  }

  return tasks;
 }

 //increment the requests counter
 private void executingRequests(int count) {
  requestsCount.addAndGet(count);
 }

 //creates callable (i.e executable or runnable tasks) 
 private Callable<SumResponse> createTask(final SumRequest request) {
  // anonymous implementation of Callable.
  // Pre Java 8's way of creating closures
  Callable<SumResponse> task = new Callable<SumResponse>() {

   @Override
   public SumResponse call() throws Exception {
    System.out.println(Thread.currentThread().getName() + ": Request = " + request);
    SumProcessor<SumRequest, SumResponse> processor = new SumProcessorImpl<>();
    SumResponse result = processor.sum(request);
    return result;
   }

  };

  return task;
 }

 //executes the tasks
 private <T> List<Future<T>> execute(List<Callable<T>> tasks) {

  List<Future<T>> result = null;
  try {
   //invokes the sum(sumRequest) method by executing the closure call() inside createTask
   result = executionService.invokeAll(tasks);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }

  return result;

 }
 
 
 public int getRequestsCount(){
  return requestsCount.get();
 }
 
 

 public int getThreadPoolSize() {
  return threadPoolSize;
 }

 @Override
 public void setThreadPoolSize(int threadPoolSize) {
  this.threadPoolSize = threadPoolSize;
 } 
}


Step 2: The test class SumEngineTest that runs forever in an endless while loop. This allows you to monitor your app via JConsole as it runs. For example, change the threadPoolSize and view both the threadPoolSize  and  requestsCount. THe MBean server lines are also added to register the MXBean.

package com.mycompany.metrics;

import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.management.MBeanServer;
import javax.management.ObjectName;

public class SumEngineTest {

 public static void main(String[] args) throws Exception {

  SumEngine se = new SumEngine();
  
  //Register with MBeanServer
  MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  ObjectName name = new ObjectName("com.mycompany.metrics:type=SumEngine");
  mbs.registerMBean(se, name);

  List<SumRequest> list = new ArrayList<>();

  //run for ever
  while (true) {

   // sums 1+2, 2+3, 3+4, etc
   for (int i = 1; i <= 5; i++) {
    SumRequest req = new SumRequest();
    req.setOperand1(i);
    req.setOperand2(i + 1);
    list.add(req);
   }

   SumRequest[] req = new SumRequest[list.size()];
   se.execute((SumRequest[]) list.toArray(req));
   
   // sleep for 5 seconds
   TimeUnit.SECONDS.sleep(5); 
   list.clear();
  }

 }

}

Step 3: Run the SumEngineTest, and  wherever the engine is running,   go to the DOS command prompt and type jconsole. This pops up the jconsole GUI. Connect to com.mycompany.metrics.SumEngineTest.





You can try increase the threadPoolSize and check the output to see if more threads are used.  Also, look at the other tabs memory, threads, overview, etc.

Labels:

Jan 23, 2014

Setting up Java and Maven with environment variables

This is an extension post to Java Tutorial: Setting up Java, Maven, and eclipse. Setting up Java and Maven is the first step any beginner has to do. So, understanding this will save so much pain.

Q. What are environment variables?
A. An environment variable defines some aspect of a user's or a program's environment. After you have installed the Java Runtime Environment (JRE) in Windows, you must set the JAVA_HOME environment variable to point to the JRE installation directory. Same applies for other applications like Maven. These variables are then used to set the "PATH" variable so that when you type "java" or "mvn" on a dos command line, the application can be found.

In a Windows platform, you can write a batch file to set up your environment variables as shown below:

@echo off
REM This is sample to set up your Java and Maven environment variables
SET TOOLS_HOME=C:\tools
SET USERPROFILE=%TOOLS_HOME%\home
SET JAVA_HOME=%TOOLS_HOME%\java\jdk1.6.0_45
SET M3_HOME=%TOOLS_HOME%\maven\apache-maven-3.1.0
SET MAVEN_OPTS=-Xmx512m -Duser.home=%USERPROFILE%

SET PATH=%PATH%;%M3_HOME%\bin;%JAVA_HOME%\bin


echo ******** Java Toolkit setup ****************
echo USERPROFILE = %USERPROFILE%
echo JAVA_HOME   = %JAVA_HOME%
echo M3_HOME     = %M3_HOME%
echo PATH        = %PATH%
echo ********************************************


Q. How do you list the environment variables on DOS command prompt?
A. by typing the "set" command.

Q. How do echo a particular variable?
A. by typing the "echo %M3_HOME%" command display M3_HOME variable. In Unix use echo $M3_HOME. You can also do "set path" to display the program path or "set M3_HOME" to display maven env variable.

Q. How will you set your environment variables on an account or System level on Windows 8 or later?
A. On Windows 8, search for "Edit environment variables".



Then, you can set it via the pop up GUI



Q. Maven needs a settings.xml file. How do you find out which settings.xml file is used by Maven?
A. With the debug option mvn -X command.

[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from C:\TOOLS\maven\apache-maven-3.1.0\bin\..\conf\settings.xml
[DEBUG] Reading user settings from C:\Users\akumaras\.m2\settings.xml
[DEBUG] Using local repository at c:\tools\home\.m2\repository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10.0 for c:\tools\home\.m2\repository

You can get both the settings.xml file and the repository location "c:\tools\home\.m2\repository" where the artefacts will be downloaded to.




Maven uses the user.home property set via MAVEN_OPTS

SET MAVEN_OPTS=-Xmx512m -Duser.home=%USERPROFILE%

Q. How do you know that your Java and Maven are set up correctly?
A.Typing Java or MVN on a command prompt should recognize the command and give you an appropriate display with its version numbers, etc.

Q. How does maven know where to download the jar files from? in other words, how do you specify the Maven repository location?
A. Following snippets in the settings. xml file. The repo location is http://search.maven.org/

<profiles>
    <profile>
      <id>JDK</id>
      <activation>
        <property>
          <name>JDK</name>
        </property>
      </activation>
      <properties>
        <JDK_1_5>c:\tools\java\jdk-1.5.0_06</JDK_1_5>
        <JDK_1_6>c:\tools\java\jdk-1.6.0_11</JDK_1_6>
      </properties>

    </profile>
    
 <profile>
  <id>nexus</id>
  <activation>
   <activeByDefault>true</activeByDefault>
  </activation>
  <!--Enable snapshots for the built in central repo to direct -->
  <!--all requests to nexus via the mirror -->
  <repositories>
   <repository>
    <id>central</id>
    <url>http://search.maven.org/</url>
    <releases><enabled>true</enabled></releases>
    <snapshots><enabled>true</enabled></snapshots>
   </repository>
  </repositories>
  <pluginRepositories>
   <pluginRepository>
    <id>central</id>
    <url>http://search.maven.org/</url>
    <releases><enabled>true</enabled></releases>
    <snapshots><enabled>false</enabled></snapshots>
   </pluginRepository>
  </pluginRepositories>
 </profile>
</profiles>

Q. If I already have the jar file, can I manually install into my Maven repository pointed by user.home property as demonstrated above?
A. Yes, use the following command

mvn install:install-file \
  -DgroupId=org.springframework \
  -DartifactId=spring-core \
  -Dpackaging=jar \
  -Dversion=3.1.0.RELEASE \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true
 
Q. How do you search for artifacts on the central repository?
A. Go to central repository website http://search.maven.org/ and search. Prefix with g: for groupid, a: for artifactid, and v: for version number.

g:org.springframework a:spring-core  v:3.1.0.RELEASE


You may also like



Labels: ,

Java ExecutorService for multi-threading -- coding question and tutorial

Q. Can you code in Java for the following scenario?

Write a multi-threaded SumEngine, which takes  SumRequest with 2 operands (or input numbers to add) as shown below:

package com.mycompany.metrics;

import java.util.UUID;

public class SumRequest {
 
 private String id = UUID.randomUUID().toString();
 private int operand1;
 private int operand2;
 
 protected int getOperand1() {
  return operand1;
 }
 protected void setOperand1(int operand1) {
  this.operand1 = operand1;
 }
 protected int getOperand2() {
  return operand2;
 }
 protected void setOperand2(int operand2) {
  this.operand2 = operand2;
 }
 protected String getId() {
  return id;
 }
 
 @Override
 public String toString() {
  return "SumRequest [id=" + id + ", operand1=" + operand1 + ", operand2=" + operand2 + "]";
 } 
}

and returns a  SumResponse with a result.

package com.mycompany.metrics;

public class SumResponse {
 
 private String requestId;
 private int result;
 
 protected String getRequestId() {
  return requestId;
 }
 protected void setRequestId(String requestId) {
  this.requestId = requestId;
 }
 protected int getResult() {
  return result;
 }
 protected void setResult(int result) {
  this.result = result;
 }
 
 @Override
 public String toString() {
  return "SumResponse [requestId=" + requestId + ", result=" + result + "]";
 }
}

A. Processing a request and returning a response is a very common programming task. Here is a basic sample code to get started.This interface can take any type of object as request and response.

package com.mycompany.metrics;

/**
 * R -- Generic request type, S -- Generic response type 
 */
public interface SumProcessor<R,S> {
 
    abstract S sum(R request);
}

Step 1: Define the interface that performs the sum operation. Take note that generics is used .

package com.mycompany.metrics;

/**
 * R -- Generic request type, S -- Generic response type 
 */
public interface SumProcessor<R,S> {
 
    abstract S sum(R request);
}

Step 2: Define the implementation for the above interface. Takes SumRequest and returns SumResponse. 

package com.mycompany.metrics;

public class SumProcessorImpl<R,S> implements SumProcessor<SumRequest, SumResponse> {

 @Override
 public SumResponse sum(SumRequest request) {
  System.out.println(Thread.currentThread().getName() + " processing request .... " + request);
  SumResponse resp= new SumResponse();
  resp.setRequestId(request.getId());
  resp.setResult(request.getOperand1() + request.getOperand2());
  return resp;
 }
}

Step 3: Write the multi-threaded  SumEngine. The entry point is the public method execute(SumRequest... request ) that takes 1 or more SumRequest as input via varargs. ExecutorService is the thread pool and closure of Callable interface is the executable task that can be submitted to the pool to be executed by the available thread.


package com.mycompany.metrics;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class SumEngine {

private final AtomicInteger requestsCount = new AtomicInteger();

 ExecutorService executionService = null;

 //executes requests to sum
 public void execute(SumRequest... request) {
  executionService = Executors.newFixedThreadPool(5); //create a thread pool
  List<Callable<SumResponse>> tasks = createExecuteTasks(request);
  List<Future<SumResponse>> results = execute(tasks);
  for (Future<SumResponse> result : results) {

   try {
    System.out.println(Thread.currentThread().getName() + ": Response = " + result.get());
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }
  }
                 
   //initiates an orderly shutdown of thread pool
   executionService.shutdown();
 }

 //create tasks
 private List<Callable<SumResponse>> createExecuteTasks(SumRequest[] requests) {
  List<Callable<SumResponse>> tasks = new LinkedList<Callable<SumResponse>>();
  executingRequests(requests.length);
  for (SumRequest req : requests) {
   Callable<SumResponse> task = createTask(req);
   tasks.add(task);
  }

  return tasks;
 }

 //increment the requests counter
 private void executingRequests(int count) {
  requestsCount.addAndGet(count);
 }

 //creates callable (i.e executable or runnable tasks) 
 private Callable<SumResponse> createTask(final SumRequest request) {
  // anonymous implementation of Callable.
  // Pre Java 8's way of creating closures
  Callable<SumResponse> task = new Callable<SumResponse>() {

   @Override
   public SumResponse call() throws Exception {
    System.out.println(Thread.currentThread().getName() + ": Request = " + request);
    SumProcessor<SumRequest, SumResponse> processor = new SumProcessorImpl<>();
    SumResponse result = processor.sum(request);
    return result;
   }

  };

  return task;
 }

 //executes the tasks
 private <T> List<Future<T>> execute(List<Callable<T>> tasks) {

  List<Future<T>> result = null;
  try {
   //invokes the sum(sumRequest) method by executing the closure call() inside createTask
   result = executionService.invokeAll(tasks);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }

  return result;

 }
 
 public int getRequestsCount(){
  return requestsCount.get();
 }
}

Step 4: Write the SumEngineTest to run the engine with the main method. Loops through numbers 1 to 5 and adds each consecutive numbers like 1+2=3, 2+3=5, 3+4=7, 4+5=9, and 5+6 = 11.

package com.mycompany.metrics;

import java.util.ArrayList;
import java.util.List;

public class SumEngineTest {

 public static void main(String[] args) throws Exception {

  SumEngine se = new SumEngine();
  
  List<SumRequest> list = new ArrayList<>();

  // sums 1+2, 2+3, 3+4, etc
  for (int i = 1; i <= 5; i++) {
   SumRequest req = new SumRequest();
   req.setOperand1(i);
   req.setOperand2(i + 1);
   list.add(req);
  }

  SumRequest[] req = new SumRequest[list.size()];
  se.execute((SumRequest[]) list.toArray(req));

 }
}

The output is:

pool-1-thread-2: Request = SumRequest [id=bca23e97-3a6f-4e42-aff4-5ed5f7de2783, operand1=2, operand2=3]
pool-1-thread-4: Request = SumRequest [id=36d95b35-09f0-4e93-99e4-715ea7cb33c9, operand1=4, operand2=5]
pool-1-thread-3: Request = SumRequest [id=31ccd137-349a-4b7a-93b1-e51f62c11ba9, operand1=3, operand2=4]
pool-1-thread-1: Request = SumRequest [id=4bfa782a-c695-4de6-9593-cbfd357c3535, operand1=1, operand2=2]
pool-1-thread-5: Request = SumRequest [id=c653f469-6a6f-45b6-99f2-ed58620fd144, operand1=5, operand2=6]
pool-1-thread-4 processing request .... SumRequest [id=36d95b35-09f0-4e93-99e4-715ea7cb33c9, operand1=4, operand2=5]
pool-1-thread-2 processing request .... SumRequest [id=bca23e97-3a6f-4e42-aff4-5ed5f7de2783, operand1=2, operand2=3]
pool-1-thread-1 processing request .... SumRequest [id=4bfa782a-c695-4de6-9593-cbfd357c3535, operand1=1, operand2=2]
pool-1-thread-3 processing request .... SumRequest [id=31ccd137-349a-4b7a-93b1-e51f62c11ba9, operand1=3, operand2=4]
pool-1-thread-5 processing request .... SumRequest [id=c653f469-6a6f-45b6-99f2-ed58620fd144, operand1=5, operand2=6]
main: Response = SumResponse [requestId=4bfa782a-c695-4de6-9593-cbfd357c3535, result=3]
main: Response = SumResponse [requestId=bca23e97-3a6f-4e42-aff4-5ed5f7de2783, result=5]
main: Response = SumResponse [requestId=31ccd137-349a-4b7a-93b1-e51f62c11ba9, result=7]
main: Response = SumResponse [requestId=36d95b35-09f0-4e93-99e4-715ea7cb33c9, result=9]
main: Response = SumResponse [requestId=c653f469-6a6f-45b6-99f2-ed58620fd144, result=11]

Labels: ,

Jan 20, 2014

JAXB Interview Questions and Answers -- power of MOXy

This is an extension to JAXB Interview Questions and Answers - Unmarshalling.

Q. Why would be the motivating factor to use MOXy implementation of JAXB as opposed to the default implementation provided by the JDK6 implementation?

AUsing the @XmlPath annotation and other extensions provided by MOXy will make your implementation cleaner. For example. if we were to implement the previous example with some dependency class like Department, you need to define the Department POJO as follows to work with 

Default JDK implementation

package com.mycompany.app12;
 
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee
{
    private Integer id;
    private String name;
    
    @XmlElement(name="faculty")
    Department department;
     
    public Integer getId()
    {
        return id;
    }
     
    public void setId(Integer id)
    {
        this.id = id;
    }
     
    public String getName()
    {
        return name;
    }
     
    public void setName(String name)
    {
        this.name = name;
    }
    
    protected Department getDepartment() {
  return department;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + ", department=" + department + "]";
 } 
}


package com.mycompany.app12;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;


@XmlAccessorType(XmlAccessType.FIELD)
public class Department {
 
 private String name;

 protected String getName() {
  return name;
 }

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

 @Override
 public String toString() {
  return "Department [name=" + name + "]";
 }
}


package com.mycompany.app12;
 
public class Test
{
     
    private static final String XML_STRING = "<employee>\r\n" +
            "    <id>123</id>\r\n" +
            "    <name>Peter</name>\r\n" +
            "     <faculty><name>finance</name></faculty> " +
            "</employee>";
     
    public static void main(String[] args)
    {
        JAXBUnMarshaller unmashaller = new JAXBUnMarshaller();
        Employee unmarshalObject = (Employee) unmashaller.unmarshalObject(Employee.class, XML_STRING);
        System.out.println(unmarshalObject);
    }
}


Output is:
jaxbContext is=jar:file:/C:/TOOLS/java/jdk1.7.0_40/jre/lib/rt.jar!/com/sun/xml/internal/bind/v2/runtime/JAXBContextImpl.class Build-Id: 1.7.0_40......
Employee [id=123, name=Peter, department=Department [name=finance]]


MOXy implementation

Step 1:  You need to bring in the MOXy implementation.

<dependency>
    <groupid>org.eclipse.persistence</groupId>
    <artifactid>eclipselink</artifactId>
    <version>2.3.2</version>
</dependency>

Step 2: Tell JAXB to use MOXy via jaxb.properties file and place it on where the POJOs like Employee is packaged.

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory


Step 3: You will only need Employee.java and Department.java will no longer required. Thanks to the power of annotation @XmlPath("faculty/name/text( )"). Here is the revised Employee.java unmarshalling the same XML file with within employee.

package com.mycompany.app12;
 
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import org.eclipse.persistence.oxm.annotations.XmlPath;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee
{
     
    private Integer id;
    private String name;
    
    @XmlPath("faculty/name/text()")
    private String departmentName;
     
    public Integer getId()
    {
        return id;
    }
     
    public void setId(Integer id)
    {
        this.id = id;
    }
     
    public String getName()
    {
        return name;
    }
     
    public void setName(String name)
    {
        this.name = name;
    }
    
 protected String getDepartmentName() {
  return departmentName;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + ", departmentName=" + departmentName + "]";
 } 
}


MOXy Output:


jaxbContext is=org.eclipse.persistence.jaxb.JAXBContext@757869d9
Employee [id=123, name=Peter, departmentName=finance]


You may also like:

Labels: ,

Jan 16, 2014

How to create datasources with Spring and why favor JNDI?

Datasource is a name given to the connection set up to a database from a server. There are two ways to create datasources in Spring. Datasources are required to create JDBC templates. All non trivial applications need to connect to the databases. Datasources are also supplied to the hibernate session factories.

Method 1:Using Apache commons-dbcp package that has the org.apache.commons.dbcp.BasicDataSource class. The pom.xml file for maven should declare the dependency.


  <properties>
  <commons-dbcp.version>1.4</commons-dbcp.version>
 </properties>
 
    <dependencies>
  <dependency>
   <groupId>commons-dbcp</groupId>
   <artifactId>commons-dbcp</artifactId>
   <version>${commons-dbcp.version}</version>
  </dependency>
 </dependencies>


Next, is the Spring configuration file that uses the Apache datasource.

 <bean id="dataSource_sybase" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="com.sybase.jdbc3.jdbc.SybDriver" />
  <property name="url" value="jdbc:sybase:Tds:my_server:20215/my_schema" />
  <property name="username" value="user" />
  <property name="password" value="password" />
 </bean>


Method 2:  Using the JNDI to connect via the application servers' data source configuration. For example, in JBoss, you configure the data source via say my-ds.xml file and copy that to the deploy folder.

<?xml version="1.0" encoding="UTF-8"?>
<datasources>
 <local-tx-datasource> 
        <jndi-name>jdbc.dataSource.my_jndi</jndi-name>
        <use-java-context>false</use-java-context>
  <connection-url>jdbc:sybase:Tds:my-server:20345/my_schema</connection-url>
  <driver-class>com.sybase.jdbc3.jdbc.SybDriver</driver-class>
  <user-name>user</user-name>
  <password>password</password>
  <max-pool-size>50</max-pool-size>
  <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.SybaseExceptionSorter</exception-sorter-class-name>
  <new-connection-sql>select count(1) from my_table</new-connection-sql>
        <check-valid-connection-sql>select count(1) from my_table</check-valid-connection-sql> 
 </local-tx-datasource> 
 
</datasources>

Now the Spring configuration to use the JNDI name

    <bean id="datasource_abc" class="org.springframework.jndi.JndiObjectFactoryBean"
  scope="singleton">
  <property name="jndiName">
   <value>jdbc.dataSource.my_jndi</value>
  </property>
 </bean>

   <bean id="jdbcTemplate_abc" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource" ref="datasource_abc" />
 </bean>


Q. Which approach would you favor and why?
A. JNDI based datasource creation because you have to move an application between environments like development to UAT and then to integration and finally to production. If you configure each app server to use the same JNDI name, you can have different databases in each environment and not required to change your code. You just pick up the same environment free WAR file and drop it in any environment. In other words, the environment details are externalized.

JDBC, Spring, and Hibernate tutorials

Labels:

Jan 15, 2014

Java Developer Career Success Training

50+ Java Developer Job Interview Questions and Answers

with lots of diagrams, examples, code snippets, and cross references. Brush-up prior to your Java job interviews to stand out from your competition or as a quick reference to get a task done like writing a spring-batch job. Preparation will breed confidence and success







Note: Most examples are industrial strength and not just "Hello World", which has its purpose.These posts are used as my quick reference to get the job done.

Labels: , , , , , , ,

Jan 9, 2014

Java Tree structure interview questions and coding questions -- Part 4

This is an extension to Java Tree structure interview questions and coding questions -- Part 3 where recursion was used for FlattenTree interface. Let's use iteration here.



Step 1: The FlattenTree  interface.


package com.mycompany.flatten;

public interface FlattenTree<T>
{
    void flatten(Tree<T> tree);
}

Step 2: The iterative implementation IterativeFlattenTree. This uses a LIFO stack to push and pop Tree elements.


package com.mycompany.flatten;

import java.util.ArrayDeque;
import java.util.Deque;

public class IterativeFlattenTree<T> implements FlattenTree<T>
{
    
    public void flatten(Tree<T> tree)
    {
        
        if (tree == null)
        {
            return;
        }
        
        //use a double ended queue as a stack i.e. LIFO
        Deque<Tree<T>> q = new ArrayDeque<Tree<T>>();
        q.push(tree);
        
        while (!q.isEmpty())
        {
            tree = q.pop();
            Either<T, Triple<Tree<T>>> either = tree.get();
            
            if (!either.isLeft())
            {
                either.ifRight(new NodePrint<Triple<Tree<T>>>());
                Triple<Tree<T>> trippleTree = ((Node<T>) tree).getBranches();
                
                q.push(trippleTree.right());
                q.push(trippleTree.middle());
                q.push(trippleTree.left());
                
            }
            else
            {
                either.ifLeft(new LeafPrint<T>());
            }
            
        }
        
    }
}






Step 3: Finally, the test class with a main method.

package com.mycompany.flatten;

public class SpecialTreeTest
{
    
    public static void main(String[] args)
    {
        
        Tree<String> leafB21 = Leaf.leaf("B21");
        Tree<String> leafB22 = Leaf.leaf("B22");
        Tree<String> leafB23 = Leaf.leaf("B23");
        
        //takes all 3 args as "Leaf<String>" and returns "Tree<Leaf<String>>"
        Tree<Tree<String>> level3 = Node.tree(leafB21, leafB22, leafB23);
        
        Tree<String> leafB1 = Leaf.leaf("B1");
        Tree<String> leafB3 = Leaf.leaf("B3");
        
        //takes  3 args as "Leaf<String>", "Tree<Leaf<String>>", and  "Leaf<String>" 
        Tree<Tree<String>> level2 = new Node(leafB1, level3, leafB3);
        
        Tree<Tree<String>> level1 = new Node(Leaf.leaf("A"), level2, Leaf.leaf("C"));
        
        
        FlattenTree<Tree<String>> flatTree = new IterativeFlattenTree<Tree<String>>();
        flatTree.flatten(level1);
        
    }
    
}

The output is:

left ==>  Leaf [data=A] || middle ==> Node {branches=Triple [l=Leaf [data=B1], m=Node {branches=Triple [l=Leaf [data=Leaf [data=B21]], m=Leaf [data=Leaf [data=B22]], r=Leaf [data=Leaf [data=B23]]]}, r=Leaf [data=B3]]} || right ==> Leaf [data=C]
--> Leaf:A
left ==>  Leaf [data=B1] || middle ==> Node {branches=Triple [l=Leaf [data=Leaf [data=B21]], m=Leaf [data=Leaf [data=B22]], r=Leaf [data=Leaf [data=B23]]]} || right ==> Leaf [data=B3]
--> Leaf:B1
left ==>  Leaf [data=Leaf [data=B21]] || middle ==> Leaf [data=Leaf [data=B22]] || right ==> Leaf [data=Leaf [data=B23]]
--> Leaf:Leaf [data=B21]
--> Leaf:Leaf [data=B22]
--> Leaf:Leaf [data=B23]
--> Leaf:B3
--> Leaf:C

You may also like:

Labels: ,

Java Tree structure interview questions and coding questions -- Part 3

This is an extension to Java Tree structure interview questions and coding questions -- Part 2, and adds functional programming and recursion.


Step 1: The Tree interface with get( ) method that returns either a Triple tree or Leaf data.

package com.mycompany.flatten;

public interface Tree<T>
{
    abstract Either<T, Triple<Tree<T>>> get();
}

Step 2: The Leaf that implements the Tree interface.

package com.mycompany.flatten;

public class Leaf<T> implements Tree<T>
{
    
    private final T data;
    
    public static <T> Tree<T> leaf(T value)
    {
        return new Leaf<T>(value);
    }
    
    public Leaf(T t)
    {
        this.data = t;
    }
    
    public T getData()
    {
        return data;
    }
    
    @SuppressWarnings("unchecked")
    public Either<T, Triple<Tree<T>>> get()
    {
        return Either.left(data);
    }
    
    @Override
    public String toString()
    {
        return "Leaf [data=" + data + "]";
    }  
}

Step 3: The Node with Triple tree that implements the Tree interface.

package com.mycompany.flatten;

public class Node<T> implements Tree<T>
{
    
    private final Triple<Tree<T>> branches;
    
    public static <T> Tree<T> tree(T left, T middle, T right)
    {
        return new Node<T>(Leaf.leaf(left), Leaf.leaf(middle), Leaf.leaf(right));
    }
    
    public Node(Tree<T> left, Tree<T> middle, Tree<T> right)
    {
        this.branches = new Triple<Tree<T>>(left, middle, right);
    }
    
    public Either<T, Triple<Tree<T>>> get()
    {
        return Either.right(branches);
    }
    
    public Triple<Tree<T>> getBranches()
    {
        return branches;
    }
    
    @Override
    public String toString()
    {
        return "Node {branches=" + branches + "}";
    }
    
}

Step 4: The Triple class used by the Node.




package com.mycompany.flatten;

/**
 * A type that stores three values of the same type.
 */
public class Triple<T>
{
    
    private final T left, middle, right;
    
    public Triple(T l, T m, T r)
    {
        this.left = l;
        this.middle = m;
        this.right = r;
    }
    
    public T left()
    {
        return left;
    }
    
    public T middle()
    {
        return middle;
    }
    
    public T right()
    {
        return right;
    }
    
    @Override
    public String toString()
    {
        return "Triple [l=" + left + ", m=" + middle + ", r=" + right + "]";
    }
    
}

Step 5: As you can see that the Node and Leaf are using the class Either to handle Node and Leaf differently. The Either stores left or right values but not both. The Leaf uses the left and the Node uses the right. You can pass in a Function to be executed for the leaf and node.

package com.mycompany.flatten;

/**
 * X type which stores one of either of two types of value, but not both.
 */
public class Either<X, Y>
{
    private final X x;
    private final Y y;
    
    private Either(X x, Y y)
    {
        this.x = x;
        this.y = y;
    }
    
    /**
     * Constructs x left-type Either
     */
    public static <X> Either left(X x)
    {
        if (x == null)
            throw new IllegalArgumentException();
        return new Either(x, null);
    }
    
    /**
     * Constructs x right-type Either
     */
    public static <Y> Either right(Y y)
    {
        if (y == null)
            throw new IllegalArgumentException();
        return new Either(null, y);
    }
    
    /**
     * Applies function f to the contained value if it is x left-type and
     * returns the result.
     */
    public void ifLeft(Function<X> f)
    {
        if (!this.isLeft())
        {
            throw new IllegalStateException();
        }
        
        f.apply(x);
        
    }
    
    /**
     * Applies function f to the contained value if it is x right-type and
     * returns the result.
     */
    public void ifRight(Function<Y> f)
    {
        if (this.isLeft())
        {
            throw new IllegalStateException();
        }
        
        f.apply(y);
        
    }
    
    /**
     * @return true if this is x left, false if it is x right
     */
    public boolean isLeft()
    {
        return y == null;
    }
    
    @Override
    public String toString()
    {
        return "Either [x=" + x + ", y=" + y + "]";
    }
    
}

Step 6: Define the Function interface

package com.mycompany.flatten;

public interface Function<P>
{
    
    void apply(P p);
}

Step 7: Define two different implementations for the FunctionLeafPrint and NodePrint for printing Leaf and Node respectively.

package com.mycompany.flatten;

public class LeafPrint<P> implements Function<P>
{
    
    public void apply(P p)
    {
        System.out.println("--> Leaf:" + p);
    }
    
}


package com.mycompany.flatten;

public class NodePrint<P> implements Function<P>
{
    
    public void apply(P p)
    {
        Triple t = (Triple<P>) p;
        System.out.println("left ==>  " + t.left() + " || middle ==> " + t.middle() + " || right ==> " + t.right());
    }
    
}

Step 8: The FlattenTree interface that works on the Tree.

package com.mycompany.flatten;

public interface FlattenTree<T>
{
    void flatten(Tree<T> tree);
}

Step 9: Implementation of FlattenTree interface RecursiveFlattenTree.


package com.mycompany.flatten;

public class RecursiveFlattenTree<T> implements FlattenTree<T>
{
    
    public void flatten(Tree<T> tree)
    {
        if (tree == null)
        {
            return;
        }
        
        Either<T, Triple<Tree<T>>> either = tree.get();
        
        if (either.isLeft())
        {
            either.ifLeft(new LeafPrint<T>());
        }
        
        else
        {
            either.ifRight(new NodePrint<Triple<Tree<T>>>());
            Triple<Tree<T>> trippleTree = ((Node<T>) tree).getBranches();
            flatten(trippleTree.left());   // recursion
            flatten(trippleTree.middle()); // recursion
            flatten(trippleTree.right());  // recursion
        }
        
    }
}

Step 10: Finally, the SpecialTreeTest test class with main method.

package com.mycompany.flatten;

public class SpecialTreeTest
{
    
    public static void main(String[] args)
    {
        
        Tree<String> leafB21 = Leaf.leaf("B21");
        Tree<String> leafB22 = Leaf.leaf("B22");
        Tree<String> leafB23 = Leaf.leaf("B23");
        
        //takes all 3 args as "Leaf<String>" and returns "Tree<Leaf<String>>"
        Tree<Tree<String>> level3 = Node.tree(leafB21, leafB22, leafB23);
        
        Tree<String> leafB1 = Leaf.leaf("B1");
        Tree<String> leafB3 = Leaf.leaf("B3");
        
        //takes  3 args as "Leaf<String>", "Tree<Leaf<String>>", and  "Leaf<String>" 
        Tree<Tree<String>> level2 = new Node(leafB1, level3, leafB3);
        
        Tree<Tree<String>> level1 = new Node(Leaf.leaf("A"), level2, Leaf.leaf("C"));
        
        //System.out.println(level1); //level1 is the root
        
        FlattenTree<Tree<String>> flatTree = new RecursiveFlattenTree<Tree<String>>();
        flatTree.flatten(level1);
        
    }
    
}

The ouput

left ==>  Leaf [data=A] || middle ==> Node {branches=Triple [l=Leaf [data=B1], m=Node {branches=Triple [l=Leaf [data=Leaf [data=B21]], m=Leaf [data=Leaf [data=B22]], r=Leaf [data=Leaf [data=B23]]]}, r=Leaf [data=B3]]} || right ==> Leaf [data=C]
--> Leaf:A
left ==>  Leaf [data=B1] || middle ==> Node {branches=Triple [l=Leaf [data=Leaf [data=B21]], m=Leaf [data=Leaf [data=B22]], r=Leaf [data=Leaf [data=B23]]]} || right ==> Leaf [data=B3]
--> Leaf:B1
left ==>  Leaf [data=Leaf [data=B21]] || middle ==> Leaf [data=Leaf [data=B22]] || right ==> Leaf [data=Leaf [data=B23]]
--> Leaf:Leaf [data=B21]
--> Leaf:Leaf [data=B22]
--> Leaf:Leaf [data=B23]
--> Leaf:B3
--> Leaf:C


You may also like:

Labels: , ,

When and How to use Java ThreadLocal class?

Q. What is a ThreadLocal class?
A. ThreadLocal is a handy class for simplifying development of thread-safe concurrent programs by making the object stored in this class not sharable between threads. ThreadLocal class encapsulates non-thread-safe classes to be safely used in a multi-threaded environment and also allows you to create per-thread-singleton.


Q. Are there any alternatives to using an object or resource pool to conserve memory in Java?
A. Yes, you can use a ThreadLocal object to create an object per thread. This approach is useful when creation of a particular object is not trivial and the objects cannot be shared between threads. For example, java.util.Calendar and java.text.SimpleDateFormat. Because these are heavy objects that often need to be set up with a format or locale, it’s very tempting to create it with a static initializer and stick the instance in a static field. Both of these classes use internal mutable state when doing date calculations or formatting/parsing dates. If they are called from multiple threads at the same time, the internal mutable state will most likely do unexpected things and  give you wrong answers. In simple terms, this will cause thread-safety issues that can be very hard to debug.

Q. Are SimpleDateFormat and DecimalFormat classes thread-safe in Java?
A. No.

Q. How will you you use them in a thread-safe manner?
A. Declare it either as a local variable or use the anonymous ThreadLocal  inner class if you want to use it across a number of different methods within the class as shown below.



package test.example;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class InvestmentBalance {

 private static final ThreadLocal<NumberFormat> PERCENT_FORMAT = new ThreadLocal<NumberFormat>() {
  @Override
  protected NumberFormat initialValue() {
   return new DecimalFormat("###.##");
  }
 };

 private static final ThreadLocal<NumberFormat> DOLLAR_FORMAT = new ThreadLocal<NumberFormat>() {
  @Override
  protected NumberFormat initialValue() {
   return new DecimalFormat("$#,###.####");
  }
 };
 
 private static final ThreadLocal<DateFormat> DATE_FORMAT = new ThreadLocal<DateFormat>() {
  @Override
  protected DateFormat initialValue() {
   return new SimpleDateFormat("dd/MMM/yyyy");
  }
 };
 
 
 public String getPercentageOfInvAmount(BigDecimal amount) {
  return PERCENT_FORMAT.get().format(amount.doubleValue()) + "%";
 }

 public String getDollarInvAmount(BigDecimal amount) {
  return DOLLAR_FORMAT.get().format(amount.doubleValue());
 }
 
 public String getFormattedExpiryDate(Date date) {
  return DATE_FORMAT.get().format(date);
 }

}

The class with the main method





package test.example;

import java.math.BigDecimal;

import org.joda.time.DateTime;

import static java.lang.System.out;

public class InvestmentBalanceTest {
 
 private static final DateTime dt;
 
 static {
   dt = new DateTime(2005, 3, 26, 12, 0, 0, 0);
 }
 
 public static void main(String[] args) {
  InvestmentBalance ib = new InvestmentBalance();
  
  BigDecimal percent = new BigDecimal(35.479);
  percent.setScale(2, BigDecimal.ROUND_HALF_EVEN);
  
  BigDecimal amount = new BigDecimal(3525.49423);
  amount.setScale(4, BigDecimal.ROUND_HALF_EVEN);
  
  out.println(ib.getPercentageOfInvAmount(percent));
  out.println(ib.getDollarInvAmount(amount));
  out.println(ib.getFormattedExpiryDate(dt.toDate()));
 }

}

Output:


35.48%
$3,525.4942
26/Mar/2005

Labels: ,

Jan 7, 2014

Working with Date and Time in Java


Q. What is the difference between java.sql.Date and java.util.Date?
A. java.util.Date supports both date and time. java.sql.Date supports only date, java.sql.Time supports only time, and java.sql.TimeStamp supports both date and time.


Q. Why should you favor using the joda-time library for date time operations?
A. The Java Date and Calendar classes are badly designed. The Joda Time library is less verbose and more intuitive. Here are a few examples to prove it.

Example 1: You may think it is midnight 1st of Jan 2009

Calendar cal = Calendar.getInstance();
cal.set(2009, 1, 1, 0, 0, 0);

But the above one represents 1st of Jan 2009 because months are zero based. There is no consistency. Some indexes start with zero and others start with 1. Better approach is to use

Calendar cal = Calendar.getInstance();
cal.set(2009, Calendar.JANUARY, 1, 0, 0, 0);

Joda is even better

DateTime dateTime = new DateTime(2009, 1, 1, 0, 0, 0, 0);

Example 2: To add 60 days to the above date, in Java Date

cal.add(Calendar.DAY_OF_MONTH, 60);

In Joda, it is more intuitive

dateTime.plusDays(60);

Example 3: To format the above in Java Date

final String FORMAT = "yyyy/MMM/dd HH:mm:ss";
// define it locally as this class is not thread-safe
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
System.out.println(sdf.format(cal.getTime( )));  

In Joda

final String FORMAT = "yyyy/MMM/dd HH:mm:ss";
System.out.println(dateTime.plusDays(60).toString(FORMAT));

No wonder why this library will be included in Jav 8. Till include the Joda jar to your project.

Q. In Joda, can you explain the concepts of Instant, Duration, Partial, and Period?
A.

Instant: is the most commonly used concept in Joda. It is a point in time in nanoseconds from January 1st 1970. It is an immutable class. If you want to mutate, then use MutableDateTime class.

DateTime dt = new DateTime();  // current time
int month = dt.getMonth();     // gets the current month
int month = dt.month().get();  // alternative way to get value

Duration: is the amount of time measured in nanoseconds.

instant + duration = instant

DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0);

// duration in ms between two instants
Duration dur = new Duration(start, end);

// calc will be the same as end
DateTime calc = start.plus(dur);

Partial: is a partial date and time representation. All implementations represent local dates and times, and do not reference a time zone. E.g. LOcalDate, LocalDateTime, LocalTime, etc.

partial + missing fields + time zone = instant

LocalDate date = new LocalDate(2004, 12, 25);
LocalTime time = new LocalTime(12, 20);

// merge, resulting in 2004-25-12T12:20 (default time zone)
DateTime dt = date.toDateTime(time);




Period: is a period of time defined in terms of fields, for example, 2 years 3 months 5 days and 7 hours. This differs from a duration in that it is inexact in terms of milliseconds.

LocalTime time = LocalTime.now();
LocalTime newTime;
Period p = Period.of(5, HOURS);
//add 5 hours to current time
newTime = time.plus(p);


Q. How will you round the time to a minute?
A.

 Instant date = new Instant(); // immutable
 MutableDateTime dt = new MutableDateTime(date); //mutable
 dt.minuteOfDay().roundFloor(); // rounds time to a minute

Labels:

Jan 1, 2014

50+ Core Java and Java EE developer Job Interview Questions and Answers

Java Job Interview Questions and answers on multi-threading

Q. What is the difference between intrinsic and explicit locks in Java? Why is synchronization important? 

Q. How do Java threads communicate with each other? 


A very common Java job interview question to determine your ability to code and write multi-threaded program is: Printing odd and even numbers with two threads
More multi-thread coding and thread pools


    Java Job Interview Questions and answers on Data structures

    Java Collections Framework (i.e. Data structures) contains most commonly asked Java interview questions. A good understanding of the Java collection framework is required to leverage many powerful features of Java technology. Here are a few important practical questions which can be asked in a Core Java interview.

    Java Job Interview Questions and answers on coding

    Some Java coding questions are very popular and frequently asked in Java job interviews.


    Java Job Interview Questions and answers on OO concepts

    Java is an Object Oriented language. If you don't tackle these questions well enough with good examples, your chances of getting through an interview will be very slim.

    QWhy favor composition over inheritance in Java OOP? is a very popular interview question.

    Q. How to create a well designed Java application?

    Q. When to use an abstract class over an interface? 




    Why do many Java developer resumes fail to make an impression?
    Tip #1 Resumes are scanned and not read. When you write a resume, put yourself in prospective recruiter's shoes.
    Tip #2 If first page of your resume is not attractive enough, most likely that your resume will not be read further.


    Spring Job Interview Questions and Answers

    Spring is a very popular framework, and you will be quizzed on -- What do you understand by the terms Dependency Inversion Principle (DIP), Dependency Injection (DI) and Inversion of Control (IoC) container?, etc.

    Hibernate Job Interview Questions and answers

    Hibernate is a poplar ORM framework and very poplar with the interviewers -- How will you configure Hibernate?, What is a Session? Can you share a session object between different threads?, Explain hibernate object states? Explain hibernate objects life cycle?, etc

    Java Web Services Job Interview Questions and answers

    What are the different integration styles? What are the differences between SOAP WS and RESTFul Web Service? Which one would you choose? Why would you favor Web Services over RMI/CORBA/DCOM, etc?




    Java Job Interview Questions on Software architectures 

    Good calibre candidates have the ability to look at the big picture and drill down into details. The line between software development and software architecture is a tricky one. Regardless of you are an architect, developer, or both, one needs to have a good understanding of the overall software architecture.




    How to choose from multiple Java job offers?

    In Java/J2EE career forums, interview candidates often ask how to choose from multiple job offers? This is not an easy decision to make and often this dilemma is made worse due to not asking the right questions about the position or role at the interview.

    How to become a software architect?

    In industry specific forums, I often see questions like “what certification do I need to do to become an architect?”. The simple answer is that you don't need a certification to become an architect. It may help, but there is a lot more to it to become an architect.




    Java, JEE, JSF, Spring, and Hibernate Tutorial

    Hands-on experience matters a lot, and here are a few Java tutorials that will get you started with Java, JSF, Spring, Hibernate, Web Services, eclipse, maven, and HSQLDB. These tutorials can also give you the much needed confidence at the Java job interviews.


    How to prepare for your Java developer job interviews?
    Tip #1 Know your resume. Many questions will be sparked from your resume.
    Tip #2 Revise the core concepts. Language/Specification fundamentals and coding.
    Tip #3 Revise the key areas. How to detect thread safety issues?, analyze performance bottlenecks?, etc