Oct 25, 2014

Textual description of firstImageUrl

What is class loading in java - Internals of class loading in java

Lets start our discussion with fundamental question which was asked to me in Oracle Interview: What happens when we run a class file with main method in Java run environment(JRE) with command java <class_file_name> ags1 ,args2 ? OR What happens when we run a java application from command line ?
Answer: First an instance of java virual machine(JVM) is created, and binary representation of a class file is loded in JVM. After that Java Virtual Machine(JVM) links the initial class(class_file_name),initializes it, and invokes the public class method void main(String[]).The invocation of this method drives all further execution. Class loading is crucial step for successful execution of java application.
The main agenda of this post is to understand internals of java class loading.

What is class loader ?

Class loader is a java program(except primordial class loader, we will visit it later) which is responsible for loading class files from file system, network and other resources(i.e rt.jar from JDK).Before going into detail of class loader, we need to understand two important concept which is prerequisite to understand class loading mechanism.

1.What is importance of  "java.lang.Class" in java?
Instances of the class Class represent classes and interfaces in a running Java application. It means, whenever a java file is compiled, the compiler will insert a public, static, final field named class, of the type java.lang.Class into generated .class file, so each and every class exposes its code in the form of an instance of java.lang.Class. Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader. Since this field is public it is accessible from any where and it can be accessed like this :
  //accessing getName() method via class field.
  System.out.println("The name of class Foo is: "+

2. How fully qualified name(FQN) is different at package level(with reference to package) and JVM level?

In Java, a class is identified by its fully qualified class name(i.e : java.lang.Object. java.util.HashMap,etc). The fully qualified class name consists of the package name and the class name. However, at JVM level a class is uniquely identified using its fully qualified class name along with the instance of the Class loader that loaded that particular class.
Lets understand above discussion with an example: if a class named "Classl" in the package "Package" is loaded by an instance "clsLoader1" of the class loader "ClassLoader", the class instance of Class1, i.e. Class1.class is keyed in the JVM as [Classl, Package, ClassLoader].Similarly, if we have an another instance in JVM as [Class1, Package, ClassLoader2],This means that the two class loader instances [Classl, Package, ClassLoader] and [Class1, Package, ClassLoader2] are not same, and classes loaded by them are also completely different. So, important take away from this discussion is : In JVM every class is loaded in context of class loader.

Now come back to our class loading discussion, In Java, class loader follows class hierarchy (parent/child class loader relationship) and works on the principle of Delegation and Visibility. Delegation principle states that :Every class loader(child) before loading any class forward request to its parent class, if parent class does not load requested class ,then only child class will load it.In this way delegation ensures that child Class loader doesn't reload the class already loaded by parent. Visibility principle states that class loaded by parent class is visible to child class loader but parent class loader can not see classes loaded by child.
There are three default class loader used in Java: 1.Bootstrap  2.Extension 3.System or Application class loader. All these class loaders has a predefined location, from where they loads class files.
As we saw earlier, in java each class is loaded by its class loader, and each class loader itself is a class and must be loaded by another class loader, we seem to have the obvious chicken-and-egg problem, i.e.,  From where the very first class loader come from? It is Bootstrap class loader which kick-off class loading.
Bootstrap Class loader: It is responsible for loading standard JDK class files from JRE\lib\rt.jar(java.lang.Object and other runtime class) and i18.jar used for internationalization.It is parent of all class loaders in Java and it does not have any parents.It is also called "primordial class loader' and it written in a native language, such as C, and does not manifest itself within the Java context.For the same reason, the behavior of the bootstrap class loader will also differ across JVMs.
Question :Why System.out.println(java.lang.String.class.getClassLoader()) display null ?
Answer: Since java.lang.String belong to rt.jar and it is loaded by Bootstrap class loader(native implementaion).That's why, it does return null(not any valid class name).

Extension Class loader:
It is responsible for loading all .jar files from "jre/lib/ext" or any other directory pointed by java.ext.dirs system property.Please note,it first forward request to its parent class(Bootstrap) to do loading, if unsuccessful, it loads. Extension Class loader in JVM is implemented by sun.misc.Launcher$ExtClassLoader.

System class loader or AppClassLoader:
It is responsible for loading application specific classes from CLASSPATH environment variables(or Class-Path attribute of Manifest file inside JAR).Extension class loader is immediate parent of Application class loader and its implemented by sun.misc.Launcher$AppClassLoader class.
Note: All Java class loaders extend java.lang.ClassLoader except Bootstrap class loader.

We can summarize above discussion with an example.Consider the following sample code which initialize(try to create an instance of String class) and refer below diagram. Lets explain the flow how CustomClass and String class is loaded ?

The directory location of CustomClass is configured in CLASSPATH environment variable so,CustomClass is loaded by System class loader and is visible to it.When System class loader receives a request to load String class then it forward request to parent class Ext. class loader and Ext.class loader forward this request to Bootstrap class loader.String class is already available, since it is part of rt.jar and loaded by Bootstrap loader. Since String class loaded by parent class loader it is visible to Ext. class loader and system class loader.It was all about default class loader.

Question : What are the method calls performed internally while class loading in java ?
Answer : When JVM requests for a class, it invokes loadClass(<class_name>) function of the ClassLoader by passing the fully classified name of the Class and in turn loadClass function calls for findLoadedClass() method to check that the class has been already loaded or not. It’s required to avoid loading the class multiple times and uniqueness is maintained. If the Class is not already loaded then it will delegate the request to parent ClassLoader to load the class. If the parent ClassLoader is not finding the Class then it will invoke findClass() method to look for the classes in the file system and load it, if found else it will throw ClassNotFound exception.

Apart from default class loader, by extending ClassLoader we can write our own custom class loader.
Question : Why do we need custom class loader and where do we use it ?
Answer :  Java default class loader can load files from local file system that is good enough to full-fill  most of the requirement.However, if we need to load a class from different network via FTP or load resources dynamically at run-time, etc. For such case we need our own custom class loader.Other situation when we need can be found here.
                             ==========End of article============

Happy learning,

Oct 18, 2014

Annotations in Junit 4 and assert statements

In previous post we saw how to create sample Maven Junit project and used various annotations like @Test, @BeforeClass, @AfterClass, etc. Here we will list down all most commonly used annotations and its use.
Annotation Description and Uses
public void getEmpSalaryReport(){ ..}

Method annotated with @Test annotation considered as a test method.

public void setupTestData(){.....}
It is executed before every test method executed in that class. It is used to prepare test environment.(Initialize test data)

public void cleanTestData(){....}
This method is executed after each test methods execution .It is used to clean-up the test environment.(Delete test data and reset value to default)

public static void methodName(){....}
It is static method and it is executed only once before the very first test method is executed. It is used to perform some task which is one time activity like database connection and allocation of resources.
public static void method()

This method is executed after all test methods have been executed. It is used to perform clean-up and resources deallocation. Methods annotated with @BeforeClass and @AfterClass must be static

@Test (expected = Exception.class)
public void testExceptionIsThrown() {
    //exception thrown means, success
Test method execution fails if the method does not throw the named exception.
public void testUpperLimit(){....}
Test method execution fails if it takes more than T milliseconds.

@Ignore or @Ignore("Message of disabling")
public void exceedingUpperLimit(){..}
Test method annotated with @Ignore is not executed.It is used when some test method is taking more time to execute so as build process, so we can skip execution of test method and revisit it later.

Along with annotations, we have some static methods that need special mention when we are dealing with test methods.Assert class contains assert static methods which are mainly used to match expected output from value returned from method executed inside test method. If values matches Junit declares test passed and  switch to next test method , else throw AssertionException or AssertionError. Below is list of assert methods commonly used :
Assert method/statements Description
assertTrue([message,] condition/outcome from some method)
//message is optional , may be omitted

Check that conditional statement is true or not. If true gracefully executed else java.lang.AssertionError thrown.

assertFalse([message,] boolean condition)
Check that conditional statement is false or not. If fasle gracefully executed else java.lang.AssertionError thrown.

assertNull([message,] object/method call returning object)

Check whether object referenced or returned by method call is null or not. If not null, error thrown.

assertNotNull([message,] object/method call returning object)
Check whether object referenced or returned by method call is null or not. If null, error thrown.

assertEquals([message,] expected, actual(value returned from method call))

Compares expected with actual, if equal gracefully executed else error is thrown.

Notes:  Junit 4 support static import of assert methods (assertEquals , asserNotNull).Static import is very handy when it come to using assert methods many places. Because of static import, assert methods are used without specifying class name Assert.Below sample code demonstrate how to use static import:
// without static imports we have to use Assert in each method call.
Assert.assertEquals("Employee's salary is > 1000", 800, emp.getSalary(emp_id));

//with static import
import static org.junit.Assert.assertEquals
assertEquals("Employee's salary is > 1000", 800, emp.getSalary(emp_id));
Read also :  How to create maven junit project

Oct 11, 2014

Textual description of firstImageUrl

Unit testing with JUnit 4 ( Maven project with Junit 4)

Unit testing is an inexpensive and efficient way to produce error free code lines. Although there is a dedicated division in every organization who perform testing and do quality activity on production or staging environment , however it is developer's responsibility to verify the code bocks (function,class,etc) written by them before integration. 
Junit (main agenda of this article) is a handy framework for Java developer for writing unit test cases and verify that functions or class method are working fine. In many organization, it is termed as test driven development (TDD) or test driven methodology and assumed as must-have skills for software developers. 
What is Unit test case and unit testing : A Junit test is a method contained in a class which is only used for testing.It is the piece of code written by developer to verify that outcome of functions/methods of real code lines are as expected what the developer thinks it should do and the process of verifying the same is called unit testing. 
For example, consider a method that generate employee salary slip. Salary computation depends on various factors like HRA, allowance and bonus and these values are retrieved from multiple database tables and some details like employee details are retrieved via a web-service.Here we have various internal methods involved like retrieve salary component from databases table based n employee id (getSalaryComponentsFromDB(.....)) and execute a REST service (http://employeeservice.company.com?empid=<employee id>) to get employee details. Report generation will be failed, if either of the above method and service execution failed or returned wrong data.
Here comes the Junit framework and provide developer a way to execute both of these method and service separately as independent methods with all possible inputs and verify that output retrieved is same as expected outcome. If we can spot our problem in unit testing it can save our many frustrating hours invested in debugging and finding error from holistic view of program at later stage.
What version of Junit test framework we should use ?
Junit has went through very wide range of changes from 3.x to 4.x and provides many others advantage, so we will using Junit 4.x in this post or further. No body will be nostalgic about 3.x unless they have legacy code lines using java 4. For using junit 4.x , we need java 5 and further (remember annotation was introduced in java 5).
Lets consider few important points before writing our  first unit test using junit 4.x :
  1. We need to annotate unit test case method with the @org.junit.Test annotation. (Import org.junit.Test  and just use @Test )
  2. For using Junit 4 , we need to place following jar files in class path or in lib folder.
  3. We have annotations like @BeforeClass, @AfterClass .Please refer this post for complete list of annotations , it is heart of Junit 4.

Environment  set-up for writing Junit: 

Junit test case can be written inside any java project or as a separate project. For shake of simplicity we will create a separate java project.Here I am using eclipse IDE and maven plugin installed in it.
Maven plugin  may not be installed in your eclipse, first install maven plugin and proceed.For Netbeans users step followed are same. You can download following project from here.

Junit maven project in eclipse:

  1. Create a maven project (File ->New -> Project and search for maven wizard and select maven project).And just keep all values default and proceed, fill groupId as com.mycompany and artifact id as JunitMavenproject (you can choose any name however, artifact id will be your project name so better choose a appropriate name as per need)
    Note : If you do not find, maven wizard it means mavn plugin is not installed, first install it.
    If you have created project successfully, project structure will looks like :
  2. You might spot a difference from your project structure in mavan dependencies section. You might having only one jar "junit-3.8.1.jar".No worry, it is just a matter of one simple change in pom.xml.
    Open pom.xml, go to lat tab pom.xml. Find <groupId>junit</groupId> under dependencies and change version associated from <version>3.8.1</version> to <version>4.12</version>. Do save and close pom.xml. Now, you must see two jar files as shown above in Maven dependencies section.
    Note: If you do not find any entry with group id Junit , add following dependency in your pom.xml.
<pre class="prettyprint">
  1. Now we are ready to write our first sample unit test program.Create a java class "MathematicalOperation.java" under src/java/main and paste following sample code or download sample project from here.
package com.mycompany.JunitMavenproject;

public class MathematicalOperation {
 public int multiply(int x, int y) {
     if (x == 0 || y==0) {
       throw new IllegalArgumentException("Input should not be 0," +
         "result will be 0 always ");
     return x * y;
 public int addition(int x, int y) {
     if (x ==y ) {
       throw new IllegalArgumentException("X is equal to Y, " +
         "so better multiply");
     return x + y;
  1. Now we will write Junit test for checking these two methods mutiply and addition(I know addition and multiply are not doing some rocket science work, for a moment just assume it is doing and we have to verify it).Create a java class "TestMathematicalOperation.java" under src/java/test and paste following sample code or download sample project from here.
package com.mycompany.JunitMavenproject;

import static org.junit.Assert.assertEquals;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestMathematicalOperation {
 static MathematicalOperation mo = null; 
 static public void dataSetup(){
  System.out.println("Before first test method execution");
  mo = new MathematicalOperation();
 static public void cleanUp(){
  System.out.println("After last test method execution");
  mo = null;
 public void multiplicationTest() {
  assertEquals("10 x 3 must be 30", 
    30, mo.multiply(10, 3));
  System.out.println("Multiply Tested!!");
 public void additionTest() {
  assertEquals("12 + 23 must be 35",
    35, mo.addition(12, 23));
  System.out.println("Addition Tested!!");
Lets walk through the above code lines:
  • we have declared two test methods annotated by @Test and two supporting methods annotated by @BeforeClass and @AfterClass. Method doSetup() is executed automatically only once before execution of the very first test method (annotated by @Test) and similarly cleanUp() is executed after last test method execution.So the sequence of these methods execution are, first the method annotated with @BeforeClass followed by all test methods annotated with @Test and finally method annotated with @AfterClass. 
  • By default the order in which test methods are executed is not fixed, it may vary run to run. However, order of execution can be controlled by annotating test class with following annotation - it will sort method name in lexicographic order ascending using @FixMethodOrder(MethodSorters.NAME_ASCENDING).Similarly, we have MethodSorters.DEFAULT (default ordering followed )and MethodSorters.JVM(Random order). 
  • In each of the test methods we have assert statement, it compares expected result with actual method (multiply() and addition()) execution output, if both are equals test successfully passed and reported, otherwise it will report error(java.lang.AssertionError) with message passed as first argument to assertEquals method.
  1. Now we will execute the Junit program(Right click on the project -> Run as -> Junit Test) and below is the sample output that appears in console:
      Before first test method execution
      Addition Tested!!
      Multiply Tested!!
      After last test method execution
    and a visual representation specifying test method execution statistics (Run, Errors and Failure) as shown in below diagram(In netbeans the visual representation may not appear):
    JUnit  test method execution statistics 
There are certain naming conventions which need to be followed while creating test class, if do not do we may trap in issue like "Maven does not find JUnit tests to run". Netbeans user can spot this problem or if we try to run junit from command line like "mvn test". I do not find this issue in eclipse, eclipse is smart enough to take care of this.
  • By default Maven uses the following naming conventions when looking for tests to run:
    Test*  -   Test as prefix of test class name
    *Test  -   Test as suffix of test class name
    *TestCase -TestCase as sufix 
  • We can  configure Maven Surefire Plugin to use another pattern for test classes.
Test suite: Suppose we have multiple number of test classes, we can combine all test class and form a test suite. When we execute that test suite, it's all test classes will be considered sequentially and all test methods are executed.Support we have TestMathematicalOperation and TestBinaryOpeartion are two test classes, we can combine these two and make a suit and we just execute this suite class. Below is the code lines for the same: all test methods of TestMathematicalOperation and TestBinaryOperation will be execued.
package com.mycompany.JunitMavenproject;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@SuiteClasses({ TestMathematicalOperation.class,
 TestBinaryOpeartion.class })
public class TestSuite {

In next post we will see revisit some advance concept of Junit and will create sample project without Maven.
Next: Junit advance concepts - Paramertrised class, Junit rule, Cateogry,Mocking

Oct 1, 2014

JavaScript Quiz-2

1. JavaScript variable scoping : Understanding of scope of variable at Function level and Global.
What will be displayed on console ?
var name = "Nikhil";

function display() {
 var name = "Zytham"; // local variable declare and initialise 
 console.log (name); 
console.log (name);

Sample output:

Javascript has broadly classified scope of variable at two level - Function level and Global scope.
Inside function display() variable name is declared and initialised so console.log (name) prints Zytham. However, console.log(name) outside function refers variable declared on top as "Nikhil"

2. JavaScript variable scoping : Understanding of scope of variable and declaration / initialisation of variables.
What will be displayed on console ? 
var name = "Nikhil";

function display() {
 name = "Zytham"; // Hint: variable initialised or reassigned new value ?  
 console.log (name); 
console.log (name);

Sample output

In Javascript, if variable is not declared directly initialised inside function then - either a global variable is created or if variable has already declared then its value is overridden.
On execution of display() function - value of global name is overridden. That' why output is Zytham for both console.log(name) - within function and outside function.

:- If we swap order of display(); console.log (name); then result will be different. Reason, it's obvious. Nikhil is not overridden by Zytham.
> console.log (name);
> display()

3. Does JavaScript support block level scoping ? What will be output ?
var name = "Nikhil";
// HInt: Blocks not function - No local context for the name variable​
if (name) {
 name = "Ranjan"; 
 console.log (name); 

Sample output
: -

JavaScript does not have support of block level scope. Any member variable referenced in block is global variable. If it has been declared earlier then its value will be modified or global variable will be created.

Note:- If user does not declare variable and directly initialises it, JavaScript does declaration task for us and that variable is added in global context.
Any variable declared or initialised outside a function is a global variable, and it is therefore available to the entire application.
// Global variable can be declared in following ways:​

//1. Declare and initialise  
var globalname = "Nikhil";

//2. Just initialise, Javascript will take care of declaration task  
globaladdress = "India";

4. JavaScript Variable Hoisting - Only declared variable is hoisted, not initialised one.
function showName () {
 console.log ("Try printing Name : " + name);
 var name = "Nikhil";
 console.log ("Try printing Name again : " + name);

Sample Output
Try printing Name : undefined
Try printing Name again : Nikhil

A variable used without declaration, JavaScript does declaration internally. All variable declarations are hoisted (pushed and declared) to the top of the function, if defined in a function, or the top of the global context, if outside a function. Here it will be declared on top of function.

First name displayed as "Undefined" as it has been declared by JavaScript but not initialised. However, on second run it displays "Nikhil" - since local variable name is declared and initialised. One important thing to be noted here is name is declared and initialised as "Nikhil" - JavaScript will override name variable that has been declared previously.

How JavaScript engine processes above sample code ?
function showName () {
 var name; //javascript Hoisting, declared on top
 console.log ("Try printing Name : " + name);
 name = "Nikhil"; //above declared variable is overridden
 console.log ("Try printing Name again : " + name);

5. Function Declaration Overrides Variable Declaration When Hoisted. Predict output ?
// Both the variable and the function are named myName​
var myName;
function myName () {
 console.log ("Ranjan");
console.log(typeof myName); 

Sample Output

Both function declaration and variable declarations are hoisted to the top of the containing scope. And function declaration takes precedence over variable declarations (but not over variable assignment).If the variable is initialised, it overrides the function declaration​.Variable assignment is not hoisted, and neither is function assignment.
Above function myName() declaration overrides variable declaration. So typeof operator prints "function".

7. Variable and function with same name but variable is initialised. Predict outcome ?
var myName = "Richard"; 

function myName () {
console.log ("Rich");
console.log(typeof myName); 

Sample output:-

8. JavaScript setTimeout :- The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. General syntax of setTimeout is:
setTimeout(function, milliseconds, param1, param2, ...)
Note:- setTimeout Variables are Executed in the Global Scope. Predict output of below sample ?

var salary = 200;
var tax = 20;
var employee = {
 name : "Nikhil",
 salary : 100,
 tax : 30,
 compute: function(){ 
  console.log("Salary computing ......")
  setTimeout (function() {
  console.log(this.salary -  this.tax);}, 
//call compute function on employee object 

Sample output
Salary computing......