Mar 27, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 5

Q14: What will be the output for the following code snippet?

package com.writtentest8;

public class PersonMain {

 public static void main(String[] args) {
   Person p1 = new  Person("John");
   System.out.println("After changing reference:"  + p1.getName());
   System.out.println("After changing name:"  + p1.getName());

 static void changReference(Person person) {
   Person p2 = new Person("Peter");
   person = p2;

 static void changName(Person person) {

 //inner class
 static class Person {
   private String name;

  public Person(String name) {
    super(); = name;

  public String getName() {
    return name;

  public void setName(String name) { = name;

a) After changing reference:Peter
After changing name:Sam

b) After changing reference:John
After changing name:Sam

c) After changing reference:John
After changing name:John

d) After changing reference:Peter
After changing name:Peter

A14: The answer is b. Java uses pass by vlaue. When a reference is passed to a method, its reference is copied, but the original reference and the copied refrence will be pointing to the same object. When a primitive value is passed, its value is copied.

In the above example,

Step 1: reference p1 in the stack points to a new Person object created in the heap. When changReference(p1) is invoked, a copy of reference p1 is passed to the method changReference(Person person). Both references p1 and person will be pointing to the same "John" person object.

Step 2: Reference p2 will be referencing a new Person object named "Peter".

Step 3: When person = p2;, the person will be referencing "Peter", but reference p1 is still pointing to "John".

Step 4: When method changName(Person person) is invoked, p1 reference is again copied and reference person will be pointing to "John". Inside the method, the name is changed to "Sam" via the person refrence. Remmeber that p1 is also pointing to the same object, but its value has now changed to "Sam" via the copied reference person.

Step 5: So, p1 is pointing to "Sam" now.

Similar  Java coding written test question and answer with diagram 

Q15: What is the output of the following code snippet?

package com.writtentest9;

public class Xyz {

 public static void main(String[] args) {
   String s1 = "Hello";
   String s2 = new String(s1);
   String s3 = "Hello";
   System.out.println("s1 equals() s2 "   + s1.equals(s2)); 

   System.out.println("s1 == s2 "  + (s1 == s2)); 
   System.out.println("s1  == s3 " + (s1 == s3)); 

a) s1 equals() s2 true
s1 == s2 false
s1 == s3 true

b) s1 equals() s2 true
s1 == s2 true
s1 == s3 true

c) s1 equals() s2 true
s1 == s2 false
s1 == s3 false

d) s1 equals() s2 false
s1 == s2 true
s1 == s3 false

A15: The answer is a. s1 and s2 are 2 different objects, but have the same value "Hello". So s1.equals(s2) is always true. But s1 == s2 is not true because those references are not pointing to the same "Hello" object, but 2 different objects happen to have same value.

Why is then s1 == s3 is true? 

This is the tricky bit. This is a special condition for String objects only. Not for any other objects. You know that String objects are immutable, and for performance reason Java stores Strings created without the new operator in a String pool. So, String s1 = "Hello"; will be stored in the String pool. When you create String s3 = "Hello";, the JVM first checks the String pool to see if the value "Hello" exists in the String pool. If it does, it will not create a new String object but, s3 will be pointing to the same object in the pool. This means, s1 and s3 will be pointing to the same String object. In other words, reference s1 == s3 is true.

You may also like

Labels: ,

Mar 25, 2014

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know -- part 2

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know - part1 covered the frequently used CTRL+ key. This will cover CTRL+SHIFT+key. If you can remember only 1 short-cut key, this post will show you which one to remember.

8. CTRL+g and CTRL+SHIFT+g

Often you need to find where a particular type or method is referenced so that you can analyze the impact of changing the referenced class or method. You also often need to find where a particular type or method is declared. Impact analysis vital in enhancing existing code base.

CTRL+G is to find declarations in workspace

Ctrl+Shift+G is to find references in workspace


Often you need to search for Java types like classes and interfaces or Java resources like spring context XML file, properties files, sql files, data files, etc. CTRL+SHIFT+t and CTRL+SHIFT+r allow you to search for types and resources respectively with wild card character like * and ?. If you do CTRL+SHIFT+r it gives you options at the bottom as to which editor you want to use to open the selected resource. You can also use these two short cuts contextually by highlighting type (E.g. class name like EclipseShortCutKeys) and then pressing the shortcut keys.




Refactoring code is a key aspect of writing quality code. For example, you might name a variable "currentTimeMillis" and use it in a number of places. But, later on decide that a better variable name would be "startCurrentTimeMillis". If you change at one spot, you want it to be propagated to all occurences of "currentTimeMillis". This works for changing method and class names as well. If you change a name of a declared method, you want all the classes that refrencing this method to change its values in the method invocations. This is achived by highligting a class, method, or a variable, and then pressing CTRL+SHIFT+R, and then change the name at the highlighted spot, and it will propagated to other locations and resources where it is used.

Do I have to remember these 10 eclipse shortcut keys? 

With practice and experience, you will remember these frequently used shortcut keys. Until then, if you have to just remember 1 shortcut key, then it is CTRL+SHIFT+L, which lists all the short-cut keys in a popup.

If you press CTRL+SHIFT+L once

If you press CTRL+SHIFT+L twice

Labels: ,

Mar 20, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 4

Q10: When is an object needs to implement the Comparable interface?

a) When adding it to a HashSet.
b) When adding it to a TreeSet.
c) When adding it to a LinkedHashSet.
d) When adding it to any Java Collection class

A10: The answer is b.

1. HashSet is implemented using a HashMap, hence the elements are not ordered.

2. TreeSet is implemented using a tree structure(red-black tree algorithm). The elements in a set are sorted. It offers several methods to deal with the ordered set like first( ), last( ), headSet( ), tailSet( ), etc. Any object you add to it must implement the Comparable interface, otherwise it throws a runtime exception

Exception in thread "main" java.lang.ClassCastException: com.writtentest6.Employee cannot be cast to java.lang.Comparable
at java.util.TreeMap.put(
at java.util.TreeSet.add(

TreeSet maintains the elements in the order in which the public int compareTo(String o) method is implemented. Any object that implements the Comparable interface must provide the public int compareTo(String o) method implementation.

3. LinkedHashSet is between a HashSet and TreeSet. It is implemented as a HashMap with a linked list running through it. So, it maintains the elements in the order in which they are added.

Q11: Given the following code

List plainList = new ArrayList();
List<String> specList = new ArrayList<String> ();

a) adding a non String object to specList will throw a compile-time error
b) adding a non String object to specList will throw a runtime error
c) adding a non String object to specList will be slower than adding it to a plainList
d) adding a non String object to specList will throw a checked exception
e) you can add any objects to a plainList

A11: Answer is a & e.

Java generics check happens at compile-time. Learn more at Java Interview Questions & Answers: Compile-time versus runtime. Generics is a bit tricky subject to master, and a must know topic to do well in coding and written tests, hence I have dedicated a whole chapter in my book "Core Java Career Essentials"

Q12: Which of the following are right way to run a thread in the JVM?

a) A class MyThreadClass that extends the Thread class, and

MyThreadClass myT = new MyThreadClass();

b) A class MyThreadClass that extends the Thread class, and

MyThreadClass myT = new MyThreadClass();;

c) A class MyThreadClass that implements the Runnable interface, and

MyThreadClass myT = new MyThreadClass();
Thread t = new Thread(myT);

d) A class MyThreadClass that implements the Runnable interface, and

MyThreadClass myT = new MyThreadClass();
Thread t = new Thread(myT);;

A12: Answer is a and c.

You need to invoke the start( ) method and not the run( ) method. Invoking the start( ) method will invoke the run( ) method indirectly.

Q. Why can't you invoke the run( ) method directly?
A. The start method makes sure the code runs in a new thread context. If you called run directly, then it would be like an ordinary method call and it would run in the context of the current thread instead of the new one. Invoking the start( ) method will invoke the run( ) method indirectly with its special code.

Q13: What value will the following method return?

public static int getSomeNumber( ){ 
  return 2; 
 } finally { 
  return 1; 

a) 1 is returned
b) 2 is returned
c) Compile error "unreachable code is returned"
d) Runtime error "ambiguous return statement"

A13: The answer is a. 1 is returned because 'finally' has the right to override any exception/returned value by the try..catch block. It is a bad practice to return from a finally block as it can suppress any exceptions thrown from a try..catch block.

You may also like

Labels: ,

Mar 19, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 3

Q8: What will be the statement you add so that you invoke Abc's process( ) method?

package com.writtentest5;

public class Abc {

 public void process(){
    System.out.println("Processing Abc");


package com.writtentest5;

public class Def extends Abc {
 public void process(){
    System.out.println("Processing Def");
    ___________________________________ //how will you invoke Abc's process method here?

 public static void main(String[] args) {
    Abc myApp = new Def();


A8: super.process( ) will invoke parent class's process( ) method.

Q9: Which of the following interfaces will you be concerned about when adding an object to a HashSet?

a) Collection
b) Set
c) SortedSet
d) List
e) All the above

A9: Answer is a and b.

The Set interface extends the Collection interface, and HashSet implements the  Set  interface. Hence a and b are correct. You can write either

Collection<String> col = new HashSet<String>();


Set<String> col = new HashSet<String>();

Coding to an interface is a best practice.

c) is wrong because the SortedSet is implemented by ConcurrentSkipListSet and TreeSet. if you write

SortedSet<String> col = new HashSet<String>();

you will get a compile time error "Type mismatch"

If you write as

SortedSet<String> col = (SortedSet)new HashSet<String>();

you will get a Runtime exception

Exception in thread "main" java.lang.ClassCastException: java.util.HashSet cannot be cast to java.util.SortedSet
at com.writtentest5.Def.main(

Note: There are a number of Set implementations listed below, but their behaviors are quite different.

  • java.util.EnumSet
  • java.util.HashSet
  • java.util.LinkedHashSet
  • java.util.TreeSet

You may also like

Labels: ,

Mar 14, 2014

Yammer Metrics with Spring tutorial

When you are running long term applications like web applications, batch jobs, or stand-alone status update jobs, it is good to know some statistics about them, like number of requests served or request duration. You can also gather more generic information like the state of your internal collections, how many times some portion of code is being executed, or health checks like database availability, or any kind of connection to an external system.

All this kind of instrumentation can be achieved by using native JMX or using a modular project like yammer Metrics. Metrics provides a powerful way to measure the behaviour of your critical components and reporting them to a variety of systems like, JConsole, System Console, Ganglia, Graphite, CSV, or making them available through a web services as JSON data.

Step 1: Required libraries. The metrics-core, metrics-annotation, and metrics-spring are the key libraries for gathering metrics.

Step 2: Artifacts used.

Step 3: Let's create a very basic TradeEngine, and monitor the number of requests and request execution times.

package com.writtentest12;

public interface TradeEngine {
    abstract void execute(Request... requests);

package com.writtentest12;

import java.util.concurrent.atomic.AtomicInteger;
import com.yammer.metrics.annotation.ExceptionMetered;
import com.yammer.metrics.annotation.Gauge;
import com.yammer.metrics.annotation.Timed;

public class TradeEngineImpl implements TradeEngine {

 private final AtomicInteger currentRequests = new AtomicInteger();

 public void execute(Request... requests) {
  try {
   Thread.sleep(2000); //just to emulate some processing
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block

 private void executingRequests(int count) {

Take notice of @Gauge, @Timed, and @ExceptionMetered annotations used for monitoring. The Request class used in the TradeEngine.

package com.writtentest12;

public class Request {


Step 4: Spring applicationContext.xml file to wire up TradeEngine, metrics-registry, and jmx-reporter.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <metrics:metrics-registry id="trade-metrics"/>
    <metrics:health-check-registry id="trade-health"/>
    <metrics:annotation-driven metrics-registry="trade-metrics" />
    <metrics:jmx-reporter metrics-registry="trade-metrics"/>
 <bean id="tradeEngine" class="com.writtentest12.TradeEngineImpl"/>

Step 5: Stand-alone TradeEngineMain class that runs until forcefully stopped. Run continuously so that you can monitor the metrics via JMX compliant jconsole.

package com.writtentest12;

import org.springframework.context.ApplicationContext;

public class TradeEngineMain {

 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "com/writtentest12/applicationContext.xml" });

  TradeEngine tradeEngine = (TradeEngine) context.getBean("tradeEngine");

  try {
   while (true) {
    Request[] requests = new Request[2];
    requests[0] = new Request();
    requests[1] = new Request();

  } catch (InterruptedException e) {


You can run the  TradeEngineMain  application, and then start the jconsole from a command-line and monitor the number of requests processed and the stats on the execution time. I will cover this in the next post.

Labels: , ,

Mar 12, 2014

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know

1. CTRL+1

Probably the most useful one. It activates the quick fix and generates lots of code for you. This means less typing.

Generating local variables: For example, if you have written a method call and you highlight it and press Ctrl+1, Eclipse will give you options to extract to local variable, assign to new local variable or assign to new field.

If you've modified a method in a abstract superclass or interface and you highlight the subclass’ name and hit Ctrl+1, you’ll get options to add unimplemented methods or make the subclass abstract.

Suppose you’ve misspelled “currentTimeMillis”, you can highlight it, press Ctrl+1 and you’ll get an option to correct the spelling.

So, Ctrl+1 is a quick fix that does the thinking for you.

2. CTRL+space

This is a type assist tool. Handy for you to search for handy utility class like DateTimeUtils from the Joda library. There are myriad of libraries used in commercial Java projects, and very handy to pick a class.

Handy to pick your own classes as well if you don't remember the exact name for your model class, but knew that it starts with "Custom".

3. CTRL+o

You have an existing class with 15+ methods defined and want to get to a method quickly, then use CTRL+o.

4. CTRL+l

Say you get a stack trace in your eclipse console or in the log file as shown below, and you want to go directly to the line in your class that caused the exception, then use CTRL+l to go to the exact line number.

Exception in thread "main" java.lang.NumberFormatException: null
 at java.lang.Long.parseLong(
 at java.lang.Long.(
 at com.writtentest11.EclipseShortCutKeys.main(

In the above code, the class is "EclipseShortCutKeys" and line number is 10.

So, use CTRL+SHIFT+T to select the class EclipseShortCutKeys by typing the first few characters to filter, and then once this class is selected use CTRL+l and type 10 to go to the exact line.

5. CTRL+7 or CTRL+/

You may now want to comment out the line causing the java.lang.NumberFormatException. You comment and uncomment with the toggle control keys either CTRL+7 or CTRL+/. Highlight the number of lines you want to comment or uncomment, and then press CTRL+/.

6. CTRL+mouse click

The CTRL short-cuts will not be complete without the most powerful navigation CTRL + mouse click. This brings up the contextual menu to navigate to other classes or interface.  Press the CTRL key first, and then hover over the method -- for example currentTimeMillis( ) on the Joda library class DateTimeUtils, util you get a contextual menu that takes you over to the actual implementation or interface.

In commercial projects, you need to navigate from service layer classes to DAO layer classes, helper classes, domain models, etc. Many different layers will collaborate with each other to implement the business use case. So, you need to rapidly move across different layer classes.

7. CTRL+h

This is a generic search pop up. You can do Java search, File search, etc. Either high-light the type, method, or variable  and then press CTRL+h or without highlighting to fill in the search criteria yourself. Very handy to search your selection, workspace, or working sets.

So far looked at very useful CTRL+. In the next post, will cover CTRL+SHIFT+Top 10 Eclipse Short Cut Keys - Part 2. You will see in this Part 2, the only key that you must remember.

Labels: ,

Mar 11, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 2

Extends Java written test pre-interview Questions and Answers 1-3.

Q4: Given the following class with an equals(...) method

package com.writtentest4;

public class Xyz {
 int a, b;

 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Xyz other = (Xyz) obj;
  if (b != other.b)
   return false;
  return true;

Which of the following hashCode( ) method implementation is correct.

a) public int hashCode() { return a;}
b) public int hashCode() { return a+b;}
c) public int hashCode() { return a*b;}
d) public int hashCode() { return b;}

A4: The answer is d. As per the equals(..) and hashCode( ) contract, whatever fields used in equals(..) must be used in hashCode( ); Since only field "b" is used in equals(...), the hashCode( ) should also use only "b". Can't use "a" because it will break the contract. Refer to the Object class api methods hashCode( ) & equals(..) for the contract.

Q5. An IllegalArgumentException is thrown from

a) JVM when wrong method arguments are passed.
b) pre-condition check on a public method.
c) pre-condition check from a private method.
d) pre-condition check from a public or private method.

A5. The answer is b. You need to understand 2 things here.

1. Firstly, common exceptions classes in Java are:

Runtime exceptions thrown by JVM 

  • ArrayIndexOutOfBoundsException: when your code uses an array index, which is outside the array's bounds.
  • NullPointerException: when your code attempts to use a null reference where an object reference is required.
  • ClassCastException: when an attempt is made to cast an object reference fails.
  • NoClassDefFoundError: thrown by the JVM or class loader when the definition of a class cannot be found. In JDK 1.7 the error message is simplified to "Error: Could not find or load main class xxx" instead of a detailed stack trace.

Runtime exceptions  thrown programmatically

  • NumberFormatException: when an attempt is made to convert a string to a numeric type, but the string does not have the appropriate format. 
  • IllegalArgumentException: to indicate that a method has been passed an illegal or inappropriate argument. For example, a null object or a percentage  value less than 0 or greater than 100. This extends "IllegalStateException".
  • IllegalStateException: when a method is invoked and the program is not in an appropriate state for that method to perform its task. This typically happens when a method is invoked out of sequence, or perhaps a method is only allowed to be invoked once and an attempt is made to invoke it again.

All the above exceptions thrown by either JVM or programmatically indicate a bug in your application and need to be fixed.

2. Design by contract allows you to write fail-fast programs at runtime. The fail-fast programs need to check the validity of the arguments (pre-condition) passed into "public" method.  The public methods exposed and anyone could call the "public" methods with invalid arguments. On the other hand, private methods are under your sole control and it is appropriate to assert the pre-conditions as opposed to throwing an IllegalArgumentException.

Q6. What method do you invoke on the thread class to pause until a signal is received from the other threads?
A6. wait( ) or wait(2000). 

The wait( ), notify (), and notifyAll( ) methods are used to provide an efficient way for threads to communicate with each other. This communication solves the ‘consumer-producer problem’. This problem occurs when the producer thread is completing work that the other thread (consumer thread) will use. Refer Java Multithreading Interview Questions and Answers

Q7. What do you do when an ArrayIndexOutOfBoundsException is thrown?

a) Catch it and do nothing.
b) Catch it and log the full stack trace.
c) Don't do anything as it is a Runtime exception it will bubble all the way up.
d) All of the above.

A7. The answer is c.

The a) is an anti-pattern to to hide exceptions.
The b) is not a best practice to unnecessarily catch and then log. The ArrayIndexOutOfBoundsException indicates a bug in the application, hence it must be fixed and not logged. It will hide the bug unless someone is monitoring the logs or you have Nagios based alert setup to raise alerts and help desk tickets.

You may also like

Labels: ,

Mar 8, 2014

Is the effort you expend on Java certification worth the results?

The answer depends on the individual circumstances.

Who can benefit from certifications?

Those who might really benefit from certifications are those who have no experience and are looking for an entry-level position in the industry. If they are competing against newbies who have no certifications, that might give them an edge in getting that first job. Beyond that ...

If you are job hunting

-- Experience and how well you perform in your pre-interview written tests and job interviews are going to carry far more weight in making hiring decisions than some test result.

If you are working as a Java developer:

-- How well you translate your "knowledge" to skills in "getting things done" and "solving problems" is what matters than some test results.

Employers do look for your soft skills and personal attributes that add value to them

More than the certificate you receive, the real value is in the
  • Learning process that disciplines you to sit and learn the core concepts. For example, prepare, learn, research, and practice.
  • Qualities you exhibit like setting goals, commitment, and taking pride in your accomplishments.

So, just one certification would do, unless you are such an individual who lacks motivation and drive to study without a certificate. In general, talented developers are self-taught and constantly educate themselves to keep relevant with the changes. Employers love these so called on-going learners and ask the following question in the job interviews.

  • Which sites do you frequent to get your technological updates?
  • Who are your industry role models?
  • What was the last article or book you read? When did you read that?
  • Why do you like software development?
  • How do you review quality of others' code?

Compliment your certification with the evidence of hands-on experience acquired via voluntary work, self taught projects, and open-source contribution. This will make you stand-out from other beginners who also happen to have certification.

Another differentiating factor is to prepare prior to your job interviews. Employers love good communicators. Unlike a test preparation where you work hard as an individual, in a real work environment you need to  interact with the multi-disciplinary teams and personalities to get the job done. So, you need to be a good communicator and have "can do" positive attitude to get things done.

Certified or not, you will be grilled in job interviews?

Prospective employers understand that lots of great Java professionals are not certified, and also not all certified professionals are good at getting things done. In interviews, your technical skills, experience, achievements, passion, confidence, soft skills, and personal attributes will be under scrutiny. So, it really pays to apply what you learn technically and non-technically to acquire the much needed hands-on experience. Some candidates look great on paper but are terrible at conveying ideas in the job interviews or team meetings. Prospective employers, especially the larger organizations with multidisciplinary teams favor hiring clear communicators with decent programming skills than hiring a superb programmer with terrible communication skills.

Do you talk up your on the job accomplishments or academic accomplishments?

Employers are after one thing -- "your ability to get the job done".  How do employers determine your ability to get the job done.

  • Pre-interview  phone interview screening.
  • Pre-interview coding and technical tests.
  • Job interview performance -- both technical and soft skills will be under scrutiny.
  • Once you get hired, you might be on probation and your ability to get the job done independently as well as in a team will be closely monitored.
 If you are an experienced professional, and try to talk up your academic achievements, your prospective employers will be concerned about your practical ability to get things done.

When technology is evolving at a rapid pace, can you afford to tinkering with the certification preparation?

When I changed my career from Mechanical engineering to Java in 1999, I had the same dilemma of preparing for Java certification (e.g. spend 3 to 6 months), or press ahead with  learning the sought-after technologies and frameworks. I opted for the second option.
  1. Researched online job advertisements and Google trends to short list the technologies/frameworks in demand to get some hands-on experience via tutorials and self-taught projects.
  2. Prepared for job interviews on the same topics via good books, online articles, and blog posts.
It did pay off for me. I always favor the path less traveled.

Do what works for you.  At the end of the day the most important thing is to get there and how you get there is up to you. So, ask yourself a few questions to determine what will keep you focused on your goals. Knowing and doing are 2 different things. So, become a doer. Start asking questions and writing code. Solve industrial challenges to succeed in your career.

What defines success?

Success means different things to different people. Failing is a life experience. Not getting that top grade on the exam you spent all night studying for, is an experience. Life experiences are a composite of all the skills necessary to get along in the real worldIn college, it’s all about grades. In the real world, it’s about passion, action and experience. Once you get past the first job, no one is ever going to ask you about your grades. 

Both Bill Gates and Steve Jobs are men of tremendous achievement. Both of them did not succeed in a classroom.

Success isn't defined by what we manage to get, but rather by what we are able to give.

So, know your industry, be passionate, ask the right questions, and solve problems through innovative ideas.

Certification has its place, but enjoy it in moderation. There are other avenues like open-source contribution, learn-apply-let the world know, and self-taught projects to develop yourself as a well rounded professional, and I have covered them in detail in my book entitled "How to open more doors as a software engineer".

Take away point is this:

The least important thing is what you have like certificate, brainbench test score, or 1 year experience. The most important thing is what you have become like ability to solve business problems, dedication for ongoing learning, ability to communicate your thoughts, ability to work individually as well as a team, ability to market your skills, disciplining yourself to set goals and act on it, etc.

You may also like

Why Java certification alone not enough?


Mar 7, 2014

Top 15 Core Java pre-interview technical written test questions and answers

Written tests can help short-list candidates and often used by recruitment agencies  and prospective employers. Here are some popular written test questions and answers.

Note: Multiple choice questions may have more than one right answers.

Q1. What will be the output of the following code snippet?

package com.writtentest1;

public class Base {
 int i;

 public Base() {

 public void add(int j) {
   i += j;


package com.writtentest1;

public class Extension extends Base {

 public Extension() {

 public void add(int j) {
   i += j*2;

package com.writtentest1;

public class Main {

 public static void main(String[] args) {
   exec(new Extension());

 private static void exec(Base base) {


a) 21
b) 22
c) 20
d) 16
e) 17

A1. The answers is b, i.e 22.

Step 1: When new Extension( ) is invoked it invokes the constructor Extension( ).
Step 2: The trick here is that default constructors implicitly call super( ), so Base( ) constructor will be invoked next.
Step 3: Base( ) --> add(1) method on Extension class as the stored object is of type Extension and polymorphic will kick in. The value of i becomes 0 + 1*2 = 2.
Step 4: add(2) is invoked from Extension constructor. The i becomes 2 + 2*2 = 6;
Step 5: Finally, add(8) is invoked from Main --> exec, and i becomes 6 + 2*8 = 22.

Q2. What will be happen when you run the following code?

package com.writtentest2;

public class ThreadMain {

 public static void main(String[] args) {
  Runnable runnable = new Runnable() {
   public void run() {
     try {
       System.out.print("Going to sleep. "); 
     } catch (InterruptedException e) {
     System.out.print("Has woken up. "); 
  Thread thread = new Thread(runnable);
  try {
  } catch (InterruptedException e) {


a) prints: Going to sleep. Has woken up. Completed.
b) InterruptedException is thrown with a stack trace.
c) prints: Completed. Going to sleep. Has woken up.
d) prints: Completed.

A2. The answer is a.

There are 2 threads involved in this. Main thread and the worker thread "thread". The main thread spawns the new thread and when thread.start( ) is invoked the run( ) method inside the anonymous inner class for Runnable interface is executed and prints "Going to sleep. ". In the mean time the Main thread is blocked due to thread.join( ) statement. The worker thread sleeps for at least 5 seconds, and then prints "Has woken up. " and it completes its execution. Once the worker thread "thread" has finished, the main thread continues and prints "Completed."

Try commenting out thread.join( ); and its try/catch block see what happens to the output.

Q3: Given the following interface,

package com.writtentest3;

public interface Ixy {
    abstract String get();
    abstract void set(String value);

Which of the following statements are correct?


package com.writtentest3;

public  abstract class IxyImpl implements Ixy {

   public  void calc(String value){}


package com.writtentest3;

public  class IxyImpl implements Ixy {

 public String get() {
    return null;

 public  void calc(String value){}



package com.writtentest3;

public  class IxyImpl {

 public String get() {
    return null;

 public  void calc(String value){}



package com.writtentest3;

public  class IxyImpl {

 public String get() {
    return null;

 public  void calc(String value){}


A3. Answer is: a and d.

a: No compile error since the class is abstract, even though it does not implement all the methods from the interface.
b: Compile error because it is a concrete class, and does not implement the abstract method void set(String value).
c: Compile error because it does not implement the interface Ixy, but the method public String get( ) is still annotated with @Override
d: No compile error as the @Override annotation is no longer there.

You may also like

Labels: ,

Mar 6, 2014

Creating a simple Java Web project with Maven tutorial -- Part 2 Understanding war and pom.xml

Creating a simple Java Web project with Maven tutorial -- Part 1 covered developing a simple Java web application using Maven. This part is all about understanding the war and pom files.

1. The lib directory

Q. How did the servlet-api-2.5.jar get into the WEB-INF/lib folder?
A. You need to understand the pom.xml file that we used n part-1 tutorial.

There are 6 scopes, and most popular ones are

  • compile:  this is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
  • provided: this is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.
  • runtime: this scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
  • test: this scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

Q. Where do the compiled class files and web.xml need to be in the war file?
A. WEB-INF/classes and WEB-INF respectively.

Q. Where do web resources like .jsp, .html, .css, .jpg, .gif, .jsm etc go?
A. If you want it to be publicly accessible via a url like http://localhost:7002/simpleWeb/index.jsp then you need to put in the root (i.e. simpleWeb.war). If you want to protect its direct access, then in subfolders inside WEB-INF. Create folders for html, images, JavaScrip, css, etc. The protected approach is recommended.

Q. What if you want the war file to published to your local maven repository?
A. Run the "mvn install" command.

After running the command, inspect your local maven repository

Q. Where did maven get the group, artifiactId, and version info?
A. From the pom.xml file.

Labels: ,

Mar 4, 2014

Creating a simple Java Web project with Maven tutorial -- Part 1

Three  part tutorial for Java beginners to create a simple web application (i.e. a Web ARchive file -- i.e. a war file).
  1. Part-1: Without using an IDE like eclipse. Just using Maven, Java, and text editor like Notepad++.
  2. Part-2: Analyzing the war file and Maven pom.xml file.
  3. Part-3Import the project into eclipse and use m2e plugin for Maven within eclipse.
 Step 1: Execute the Maven maven-archetype-webapp command to create the Maven web structure with the following command on a DOS command prompt. This assumes that you have set up Java and Maven.

mvn archetype:generate -DgroupId=com.mytutorial -DartifactId=simpleWeb  -DarchetypeArtifactId=maven-archetype-webapp

Enter "0.1-SNAPSHOT" when prompted for the version and "Y" to package: com.mytutorial.

Step 2: You can verify the structure created in the file system as shown below. pom.xml is the maven file to define build details and web.xml is web deployment descriptor file.

Step 3: open the pom.xml file in a text editor like Notepad++. If you don't already have it, download it. Add servlet-api as a dependency.

<project xmlns="" xmlns:xsi=""
  <name>simpleWeb Maven Webapp</name>

Step 4: Define a simple servlet class in a package com.mytutorial. You need to first create a folder named "java" under src/main. Then create folders com and com/mytutorial under the folder java. You can use the notepad++

Create a Java class named

package com.mytutorial;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  PrintWriter out = response.getWriter();


Step 5: Go to the DOS command prompt and change directory to simpleWeb where the pom.xml file is. type the command mvn compile. This should compile your

C:\Users\akumaras\projects\simpleWeb>mvn compile
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building simpleWeb Maven Webapp 0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ simpleWeb ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ simpleWeb ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\akumaras\projects\simpleWeb\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.399s
[INFO] Finished at: Wed Feb 26 17:29:02 EST 2014
[INFO] Final Memory: 7M/243M

Note that in the file system SimpleServlet.class file gets created under target/classes/com/mytutorial.

Step 6: You need to define the web description in the web.xml descriptor file.  You need to configure your Servlet details here.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns=""

 <display-name>Simple web app</display-name>

  <servlet-name>Simple Servlet</servlet-name>

  <servlet-name>Simple Servlet</servlet-name>


Step 7: Java web applications are packaged as a war file. In order to package it, you need to run the Maven command mvn package.

C:\Users\akumaras\projects\simpleWeb>mvn package
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building simpleWeb Maven Webapp 0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ simpleWeb ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ simpleWeb ---
[INFO] Nothing to compile - all classes are up to date
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ simpleWeb ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\Users\akumaras\projects\simpleWeb\src\test\resources
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ simpleWeb ---
[INFO] No sources to compile
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ simpleWeb ---
[INFO] No tests to run.
[INFO] --- maven-war-plugin:2.2:war (default-war) @ simpleWeb ---
[INFO] Packaging webapp
[INFO] Assembling webapp [simpleWeb] in [C:\Users\akumaras\projects\simpleWeb\target\simpleWeb]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\Users\akumaras\projects\simpleWeb\src\main\webapp]
[INFO] Webapp assembled in [53 msecs]
[INFO] Building war: C:\Users\akumaras\projects\simpleWeb\target\simpleWeb.war
[INFO] WEB-INF\web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.575s
[INFO] Finished at: Wed Feb 26 17:45:45 EST 2014
[INFO] Final Memory: 6M/243M
[INFO] ------------------------------------------------------------------------

Inspect your file system for the war file simpleWeb.war under target. If you are curious to see what files are inside, you can unzip it with a WinZip utility.

Step: This war file can be deployed to any web container or application server. For example, Tomcat, JBoss, Weblogic, etc. I deployed this to my local Weblogic server running on port 7002.


Where "simpleWeb" is the name of the war file you had created, and "simple" is the "url-pattern" you defined in your web.xml file.

A simple Java web tutorial without any IDE like eclipse. This also gives you an idea as to how Maven works.

Labels: ,