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: "+
                             Foo.class.getName());

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,
Nikhil

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
@Test
public void getEmpSalaryReport(){ ..}

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

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

@After
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)

@BeforeClass
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.
@AfterClass
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.
@Test(timeout=<T>)
public void testUpperLimit(){....}
Test method execution fails if it takes more than T milliseconds.

@Ignore or @Ignore("Message of disabling")
@Ignore
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.
         junit.jar
         hamcrest-core.jar  
  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">
          <dependency>
                 <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
                </dependency>
</pre>
  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; 
 @BeforeClass
 static public void dataSetup(){
  System.out.println("Before first test method execution");
  mo = new MathematicalOperation();
 }
 @AfterClass
 static public void cleanUp(){
  System.out.println("After last test method execution");
  mo = null;
 }
 
 @Test
 public void multiplicationTest() {
  assertEquals("10 x 3 must be 30", 
    30, mo.multiply(10, 3));
  System.out.println("Multiply Tested!!");
 }
 
 @Test
 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;


@RunWith(Suite.class)
@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);
display();

Sample output:
Nikhil
Zytham

Explanation:-
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); 
}
display();
console.log (name);

Sample output
:
Zytham
Zytham

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.

Note
:- 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);
Nikhil
> display()
Zytham


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
: -
Ranjan

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);
}
showName()

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);
}
showName()

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
:-
function

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:-
String

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);}, 
    2000);
 }
}
//call compute function on employee object 
employee.compute()

Sample output
:-
Salary computing......
180

Sep 13, 2014

Textual description of firstImageUrl

DBMS_OUTPUT.PUT_LINE not printing - Why do we need set serveroutput on" to see output on console

It is very common problem faced by people trying to execute PL/SQL procedure in SQL Plus or SQL Developer and displaying message or debugging information using DBMS_OUTPUT package. However, no output on console. Why DBMS_OUTPUT.PUT_LINE is not working ? 
DBMS_OUTPUT package enables us to send messages from stored procedures(DBMS server) to client. However, most tools (like SQL*PLUS, SQL developer) do not allocate a buffer for DBMS_OUTPUT to write in this buffer and do not attempt to read from that buffer after PL/SQl program execution.
Fortunately, we have commands (set serveroutput on size <Size of buffer>) to hint DBMS server to dump/flush server output to the client's buffer and client will read from this buffer to display output accordingly.
Before, Oracle 10.2 , there was a upper limit on size of this buffer (limited to one million bytes with a default size of 20,000). However, from oracle 10.2 the upper limit has been removed with restriction on size of buffer, if you specify.We have two cases here:- Specify size of buffer & do not specify size.
  1. If we specify size of buffer:-  Buffer size should be between 2000 and 1 million, else it will throw error.See following execution of set command
        SQL> set serveroutput on size 1000;
        SP2-0547: size option 1000 out of range (2000 through 1000000) 
        SQL> set serveroutput on size 3459988000;
        SP2-0547: size option 3459988000 out of range (2000 through 1000000)
        SQL> set serveroutput on size 30000;   --No error - size in range

  2. If we do not specify size of buffer :- From oracle 10.2 , if you do not specify size of buffer, implicitly buffer size will be set to NULL. NULL means unlimited size of buffer;
    SQL> set serveroutput on    --No error - default size set to NULL

Let's write s small PL/SQL program and see the difference , when server output is on/off. Follow the following diagram: First run: server output OFF, second run - server output ON
In first execution , server output is off so no output message displayed on console. Before second run, we set serveroutput on (as highlighted in above diagram) and this time output message displayed on console.
How do we enable DBMS server output in SQL Developer ?
In SQL Developer also , by default server output is not visible and we need to enable it . Follow the path :  Go to View (menu- bar) -> Open DBMS output .
Now click on , green + button and select the connection from drop down. It will switch on serveroutput.


 ====== End of the article======

Sep 12, 2014

Textual description of firstImageUrl

JavaScript Quiz-1

1. What is outcome of  x == y ? 
var x = "ZYTHAM";             
var y = new String("ZYTHAM");
x==y //prints true/false
Answer: true
== compares values of x and y . Since x and y both has equal values.

2. What will outcome of x === y ?
var x = "ZYTHAM";             
var y = new String("ZYTHAM");
x===y
Answer: false
=== compares both values and type. x is of type String and y is of type Object, It can be verified executing :
typeof x  "string"
typeof  y  "object"

3. What will be outcome of x == y and x === y ?
var x = new String("ZYTHAM");             
var y = new String("ZYTHAM");
x==y //prints true/false
x===y //prints true/false
Answer:  Both prints false.
== prints false because both object are different object. And similarly, === prints false because both are different object.

4. What will be outcome of res and res1 ?
var str = "Nikhil, Ranjan, Devinline";
var res = str.substr(8, 6);
var res1 = str.slice(-17, -11);
Answer: Both will display "Ranjan"
substr(8,6) - starts from index 8 and prints length of 6 char. (start index is 0)
substr(-17,-11) - starts from end(go back 17 chars and then then reaches 11 from end)

5. What will be outcome of below sample unit
var myNumber = 64;
myNumber.toString(16);     
myNumber.toString(8);      
myNumber.toString(2);   
Answer:
myNumber.toString(16);
"40"
myNumber.toString(8);
"100"
myNumber.toString(2);
"1000000"

6. Write a random number generator function in javascript, provided random number should be generated between min and max passed as input.
Answer:
min is included and max is excluded
function getRndomInteger(min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
}

min and max both are included
function getRndomInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

7. Predict outcome of sample code ?

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();  
var points = [40, 100, 1, 5, 25, 10];
points.sort();
Answer:-
["Apple", "Banana", "Mango", "Orange"]
[1, 10, 100, 25, 40, 5]

First output looks as expected, but what happened to second array output. By default, the sort() function sorts values as strings. So, "25" is bigger than "100", because "2" is bigger than "1".

8. Sort above array(number array) in ascending order ? Hint: Use compare function in sort function

var points = [40, 100, 1, 5, 25, 10];
function comparefun(a, b){
  return a - b
}
points.sort(comparefun);
On passing a compare function to sort method, sort method sort numbers as follows.
 [1, 5, 10, 25, 40, 100]
Note:- The purpose of the compare function is to define an alternative sort order(instead of natural sort ordering).The compare function should return a negative, zero, or positive value, depending on the arguments:

9. Sorting Object Arrays based on some attributes - Below arrays contains objects. Sort below objects based on salary.
var positions = [
{type:"VP", Salary:80},
{type:"Manager", Salary:40},
{type:"Director", Salary:50}];
Answer:-  positions.sort(function(a, b){return a.Salary - b.Salary});
Above code lines sort positions array of objects in ascending order, same can be validated with following console output

10. Write a compare function to sort array based on type and verify the output.
Answer:
positions.sort(function(a, b){
    var x = a.type.toLowerCase();
    var y = b.type.toLowerCase();
    if (x < y) {return -1;}
    if (x > y) {return 1;}
    return 0;
});

Aug 17, 2014

Object creation in JavaScript : Object Oriented Programming and Prototypal Object Creation

In JavaScript most common ways to create Objects are - Object Oriented Programming (OOP) way  and Prototypal Object Creation way. In this post we will see OOP way followed by Prototypal way.

Object Oriented Programming - OOP Style object creation 


function Employee(name,designation ) {
    var new_employee = this; // 'new' object

    new_employee.name = name;
    new_employee.designation = designation;
}//Employee is a constructor 
var emp1 = new Employee('Nikhil', 'SE');
var emp2 = new Employee('Ranjan', 'SSE');

In JavaScript, as convention says, function name with Uppercase first letter is a constructor. Here Employee is a constructor which creates object and assign properties values passed to it as arguments.
Two objects emp1 and emp2 created using Employee() constructor.  Verify the same with following execution in console.
> emp1.name
"Nikhil"
>emp2.designation
"SSE"
>emp2.hasOwnProperty('name')
true
>emp1.hasOwnProperty('designation')
true

How to add properties to object - Create Instance Methods


Employee.prototype.combiner = function() {
    return this.name + " "+ this.designation;
}

Here prototype is another object. "combiner" a function is added as properties of prototype object and it is available for all objects. Execute combiner methods on an object created earlier
> emp1.combiner()
"Nikhil-->SE"



Prototypal Object Creation - JavaScript way to create Object !!

function Employee() {}; // no properties
var emp1   = new Employee(),
    emp2  = new Employee();

//Add properties for all objects  
Employee.prototype.welcome = function () {
    return 'Welcome '+ this.name;
};
Employee.prototype.name = "dummy";

Above sample code creates an empty Constructor without any properties. Object is created without any properties and at the end we add properties to all objects. Set properties value for emp1 and emp2 and execute welcome function on these objects.
> emp1.name = "Nikhil"
> emp2.name = "Ranjan"
> emp1.welcome()
"Welcome Nikhil"


How to create properties for specific object - Add properties to object instead of prototype object.

emp1.dowork = function () {
    return 'work started....';
}//dowork function is not added to prototype 

Jun 1, 2014

Reverse a Linked List in block of size N in Java - Iterative and Recursive implementation

Problem Statement :- For a given a linked list and block size N as input, reverse N blocks of nodes so that linked list internal structure is maintained. Solve using recursive and non-recursive approach.
Sample Input and Output:- 
Inputs:  12 --> 18 -->  172 --> 62 --> 632 --> 192 --> 34 , block size N  = 3
Output:  172 --> 18 -->  12  --> 192 --> 632 --> 62 --> 34
Inputs:  12-->18-->172-->62-->632-->192-->2-->61-->82-->72-->32,  block size N  = 4 
Output:  62-->172-->18-->12-->61-->2-->192-->632-->32-->72-->82

Recursive implementation - reverse a linked list in block of size N  

Algorithm:-
1 Iterate over input list and find end of blocks (move up to block size of N) and while traversing loop keep track of previous and next node. Lets say, Node references "nextNode" and "previous" keeps track of next node and previous node of input list.
2. Reverse block of nodes and append it with previous node.  Refer how to reverse a linked list in Java?. In below sample code we have used recursive version for linked list reversal.
3. Recursively call this method for next set of blocks and link the two sub-lists (head.next = reverseLinkedListInBlocksRecursive(nextNode, blockSize) )
4. Finally, once we reaches at end and recursive call is returned to caller and return previous as new head of the list (previous is storing first node of modified sub-list(of size N)).
5. Check for special cases - for empty list and one node list.
/*
 * Recursive approach- reverse the linked list in group (block of size N)
 * and returns new head node.
 */
private Node reverseLinkedListInBlocksRecursive(Node head, int blockSize) {
 Node current = head;
 Node nextNode = null;
 Node previous = null;
 int size = 0;
 /*
  * Check for empty and one node list
  */
 if (current == null || current.next == null)
  return current;

 /* Iterate and find end of blocks */
 while (current != null && size < blockSize) {
  nextNode = current.next;
  previous = current;
  current = nextNode;
  size++;
 }
 /* split sublist from main linked list */
 previous.next = null;
 /* Reverse block of nodes only if size is blockSize */
 if (size == blockSize) {
  previous = reverseLinkedListUsingRecursion(head);
 }

 /*
  * Recursive call for next blocks of nodes and make rest of the list as next of
  * first node
  */
 if (nextNode != null) {
  head.next = reverseLinkedListInBlocksRecursive(nextNode, blockSize);
 }

 /* Return previous as new head of the input list */
 if (size == blockSize)
  return previous;
 else
  return head;
}
Time complexity :- O(n) where n is the number of nodes in the given list.

Iterative implementation - reverse a linked list in block of size N  

Algorithm:- 
1. Do check for empty and single node list, if true return node to caller.
2. Traverse linked list maintaining current and previous node of while list along with of single block, current,previous and blockPrevious is used for input list and blockFirst and blockPrevious associated closely with each blocks(On close scrutiny may be some of variables may be minimized.)
3. Find the end of block and reverse sub-list(blocks of size N) and append with head or previous(appended with head first time and for other iteration appended with previous). Here we have used iterative version of linked list reversal.
4. Repeat step 2 and 3 , until whole list is traversed.
5. Do check for whether a single node is left, if true append with previous.
/*
 * Iterative approach- reverse the linked list in group (block of size N)
 * and returns new head node.
 */
private Node reverseLinkedListInBlocksIterative(Node head, int blockSize) {
 Node current = head;
 Node nextNode = null;
 Node blockPrevious = null;
 Node blockFirst = null;
 Node previous = null;

 /* Check for empty and one node list */
 if (current == null || current.next == null)
  return current;

 /* Loop rest of the list and reverse blocks of nodes */
 while (current != null && current.next != null) {
  int size = 1;
  blockFirst = current;
  while (current != null && size <= blockSize) {
   nextNode = current.next;
   blockPrevious = current;
   current = current.next;
   size++;
  }
  blockPrevious.next = null;

  /* Reverse block of nodes only if size is blockSize */
  if (size == blockSize + 1 && previous == null) {
   previous = head;
   head = reverseLinkedListIterative(head);

  } else {
   Node temp = reverseLinkedListIterative(blockFirst);
   previous.next = temp;
   previous = blockFirst;
  }
  current = nextNode;

 }
 /* Check for isolated blocks */
 if (current != null) {
  previous.next = current;
 }

 /* Return modified head of the list */
 return head;
}
Time complexity :- O(n) where n is the number of nodes in the given list.

Complete sample program- reverse a linked list in block of size N(Iterative and Recursive)  

Below is complete sample program for reversing a linked list in blocks(of size N) in recursive and iterative way :-
package com.devinline.linkedlist;

public class ReverseLinkedListElementsInBlocks {

/*
 * Recursive approach- reverse the linked list in group (block of size N)
 * and returns new head node.
 */
private Node reverseLinkedListInBlocksRecursive(Node head, int blockSize) {
 Node current = head;
 Node nextNode = null;
 Node previous = null;
 int size = 0;
 /*
  * Check for empty and one node list
  */
 if (current == null || current.next == null)
  return current;

 /* Iterate and find end of blocks */
 while (current != null && size < blockSize) {
  nextNode = current.next;
  previous = current;
  current = nextNode;
  size++;
 }
 /* split sublist from main linked list */
 previous.next = null;
 /* Reverse block of nodes only if size is 3 */
 if (size == blockSize) {
  previous = reverseLinkedListUsingRecursion(head);
 }

 /*
  * Recursive call for next blocks and make rest of the list as next of
  * first node
  */
 if (nextNode != null) {
  head.next = reverseLinkedListInBlocksRecursive(nextNode, blockSize);
 }

 /* Return previous as new head of the input list */
 if (size == blockSize)
  return previous;
 else
  return head;
}

/*
 * Iterative approach- reverse the linked list in group (block of size N)
 * and returns new head node.
 */
private Node reverseLinkedListInBlocksIterative(Node head, int blockSize) {
 Node current = head;
 Node nextNode = null;
 Node blockPrevious = null;
 Node blockFirst = null;
 Node previous = null;

 /* Check for empty and one node list */
 if (current == null || current.next == null)
  return current;

 /* Loop rest of the list and reverse blocks of nodes */
 while (current != null && current.next != null) {
  int size = 1;
  blockFirst = current;
  while (current != null && size <= blockSize) {
   nextNode = current.next;
   blockPrevious = current;
   current = current.next;
   size++;
  }
  blockPrevious.next = null;

  /* Reverse block of nodes only if size is 3 */
  if (size == blockSize + 1 && previous == null) {
   previous = head;
   head = reverseLinkedListIterative(head);
   // displayLinkedList(head);

  } else {
   Node temp = reverseLinkedListIterative(blockFirst);
   previous.next = temp;
   previous = blockFirst;
  }
  current = nextNode;

 }
 /* Check for isolated blocks */
 if (current != null) {
  previous.next = current;
 }

 /* Return modified head of the list */
 return head;
}

 /* Reverse a singly linked list using recursion */
 public Node reverseLinkedListUsingRecursion(Node head) {
  /* Return null , if list is empty or head if head.next = null */
  if (head == null || head.next == null) {
   return head;
  } else {
   /* Store next node of list */
   Node nextNode = head.next;
   /* For storing reference of last node of list */
   Node retHead = reverseLinkedListUsingRecursion(nextNode);
   /* Set next reference of the given node to null, breaking the chain */
   head.next = null;
   /* Add next reference in reverse order */
   nextNode.next = head;
   /* Return last node of the given list */
   return retHead;
  }
 }

 /* Reverse a singly linked list */
 public Node reverseLinkedListIterative(Node head) {
  /* Return null , if list is empty or head if head.next Is null */
  if (head == null || head.next == null) {
   return head;
  } else {
   Node previous = null;
   Node current = head;
   Node curNext;
   /* Iterate linked list and reverse the next reference for each node */
   while (current != null) {
    curNext = current.next;// Store next node for iteration
    current.next = previous; // set current next as previous
    /* store current in previous, for next iteration */
    previous = current;
    current = curNext;
   }
   /*
    * Once we complete the list iteration, previous refers to last
    * node, so assign that to head
    */
   head = previous;
  }
  return head;
 }

 class Node {
  public int data;
  public Node next; // reference(handler) for next Node.

  public Node(int data) {
   this.data = data;
   this.next = null;
  }
 }

 /* Display data of nodes/iterate linked list */
 private static void displayLinkedList(Node head) {
  Node current = head;
  if (head != null) {
   System.out.print("[ ");
   while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
   }
   System.out.print(" ]");
  } else {
   System.out.println("Linked list is empty.");
  }

 }

 public static void main(String[] args) {
  ReverseLinkedListElementsInBlocks rpll = new ReverseLinkedListElementsInBlocks();
  Node modifiedHead = null;
  Node node1 = rpll.new Node(12);
  Node node2 = rpll.new Node(18);
  Node node3 = rpll.new Node(172);
  Node node4 = rpll.new Node(62);
  Node node5 = rpll.new Node(632);
  Node node6 = rpll.new Node(192);
  Node node7 = rpll.new Node(13);
  Node node8 = rpll.new Node(19);
  Node node9 = rpll.new Node(15);
  Node node10 = rpll.new Node(67);

  Node head =  node1;
  node1.next = node2;
  node2.next = node3;
  node3.next = node4;
  node4.next = node5;
  node5.next=  node6;
  node6.next = node7;
  node7.next = node8;
  node8.next = node9;
  node9.next = node10;
  System.out.print("Original list is :");
  displayLinkedList(head);
  System.out.print("\nModified linked list is "
    + "(Using recursive Implementation) with block size is  3\n");
  modifiedHead = rpll.reverseLinkedListInBlocksRecursive(head, 3);
  displayLinkedList(modifiedHead);

  System.out.print("\n\nOriginal list is :");
  displayLinkedList(modifiedHead);
  System.out.print("\nModified linked list is "
    + "(Using Iterative Implementation:) block size is  2\n");
  modifiedHead = rpll.reverseLinkedListInBlocksIterative(modifiedHead, 2);
  displayLinkedList(modifiedHead);

 }
}
============Sample output===============
Original list is :[ 12 18 172 62 632 192 13 19 15 67  ]
Modified linked list is (Using recursive Implementation) with block size is  3
[ 172 18 12 192 632 62 15 19 13 67  ]

Original list is :[ 172 18 12 192 632 62 15 19 13 67  ]
Modified linked list is (Using Iterative Implementation:) block size is  2
[ 18 172 192 12 62 632 19 15 67 13  ]
======================================

May 25, 2014

Reverse a linked list in pairs (alternate pairs of nodes) - Recursive and Iterative

Problem Statement :- Reverse a linked list in such a way that, pair of elements are reversed and linked list internal structure is maintained. Solve using recursive and non-recursive approach.
Sample Input and Output:- 
Inputs:  12 --> 18 -->  172 --> 62 --> 632 --> 192 --> 34
Output:  18 --> 12 -->  62  --> 172 --> 192 --> 632 --> 34
Inputs:  12 --> 18 -->  172 --> 62 --> 632 --> 192 
Output:  18 --> 12 -->  62  --> 172 --> 192 --> 632

Recursive implementation - reverse a linked list in pairs 

Algorithm:-
1) Reverse pair of nodes of  input list and store references of next pair of nodes using next2nextNode. keep track of previous node using previous reference.
2) Recursively call for rest of the list and link the two sub-lists(head.next = reverseLinkedListInPairsRecursive(next2nextNode) )
3) Since, previous is storing first node of each pair, so return previous as new head of the list.
4) Check for special cases for empty list and one node list.
/* Recursive- Reverses the linked list in pairs and returns new head node. */
private Node reverseLinkedListInPairsRecursive(Node head) {
 Node current = head;
 Node nextNode = null;
 Node next2nextNode = null;
 Node previous = null;
 /* Check for empty and one node list */
 if (current == null || current.next == null)
  return current;

 /* Reverse pair of nodes - check current and current.next is not null */
 if (current != null && current.next != null) {
  nextNode = current.next;
  next2nextNode = nextNode.next;
  current.next = previous;
  nextNode.next = current;
  previous = nextNode;
 }
 /*
  * Recursive call for next pairs and make rest of the list as next of
  * first node
  */
 if (nextNode != null) {
  head.next = reverseLinkedListInPairsRecursive(next2nextNode);
 }

 /* Return previous as new head of the input list */
 return previous;
}

Iterative approach / Non-recursive implementation - reverse a linked list in pairs

Algorithm:-
1. Check for he null list or one node list, if true return that node.
2. Loop the list, until current node and next node is not null, revert pair of node references(if Node1 - > Node2 it becomes Node2 -> Node1)
3. Update previous reference and head(only first iteration).
4. Finally, check for isolated node, and return modified head.
/* Iterative- Reverses the linked list in pairs and returns new head node. */
private Node reverseLinkedListInPairsIterative(Node head) {
 Node current = head;
 Node nextNode = null;
 Node next2nextNode = null;
 Node previous = null;

 /* Check for empty and one node list */
 if (current == null || current.next == null)
  return current;

 /* Loop rest of the list and reverse pairs of nodes */
 while (current != null && current.next != null) {
  /* Swap references of two nodes */
  nextNode = current.next;
  next2nextNode = nextNode.next;
  nextNode.next = current;
  current.next = next2nextNode;

  /*
   * Update previous.next and head :- head is updated for first time
   * and after that update previous.next to connect next pairs
   */
  if (previous == null) {
   head = nextNode;
  } else {
   previous.next = nextNode;
  }

  previous = current;
  current = next2nextNode;
 }
 /* Check for isolated node in pairs - when one node is left */
 if (current != null) {
  previous.next = current;
 }
 /* Return modified head of the list */
 return head;
}

Complete sample program - recursive and iterative implementation 

package com.devinline.linkedlist;

public class ReverseLinkedListElementsInPairs {
 /* Recursive- Reverses the linked list in pairs and returns new head node. */
 private Node reverseLinkedListInPairsRecursive(Node head) {
  Node current = head;
  Node nextNode = null;
  Node next2nextNode = null;
  Node previous = null;
  /* Check for empty and one node list */
  if (current == null || current.next == null)
   return current;

  /* Reverse pair of nodes - check current and current.next is not null */
  if (current != null && current.next != null) {
   nextNode = current.next;
   next2nextNode = nextNode.next;
   current.next = previous;
   nextNode.next = current;
   previous = nextNode;
  }
  /*
   * Recursive call for next pairs and make rest of the list as next of
   * first node
   */
  if (nextNode != null) {
   head.next = reverseLinkedListInPairsRecursive(next2nextNode);
  }

  /* Return previous as new head of the input list */
  return previous;
 }

 /* Iterative- Reverses the linked list in pairs and returns new head node. */
 private Node reverseLinkedListInPairsIterative(Node head) {
  Node current = head;
  Node nextNode = null;
  Node next2nextNode = null;
  Node previous = null;

  /* Check for empty and one node list */
  if (current == null || current.next == null)
   return current;

  /* Loop rest of the list and reverse pairs of nodes */
  while (current != null && current.next != null) {
   /* Swap references of two nodes */
   nextNode = current.next;
   next2nextNode = nextNode.next;
   nextNode.next = current;
   current.next = next2nextNode;

   /*
    * Update previous.next and head :- head is updated for first time
    * and after that update previous.next to connect next pairs
    */
   if (previous == null) {
    head = nextNode;
   } else {
    previous.next = nextNode;
   }

   previous = current;
   current = next2nextNode;
  }
  /* Check for isolated node in pairs - when one node is left */
  if (current != null) {
   previous.next = current;
  }
  /* Return modified head of the list */
  return head;
 }

 /* Display data of nodes/iterate linked list */
 private static void displayLinkedList(Node head) {
  Node current = head;
  if (head != null) {
   System.out.print("[ ");
   while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
   }
   System.out.print(" ]");
  } else {
   System.out.println("Linked list is empty.");
  }

 }

 class Node {
  public int data;
  public Node next; // reference(handler) for next Node.

  public Node(int data) {
   this.data = data;
   this.next = null;
  }
 }

 public static void main(String[] args) {
  ReverseLinkedListElementsInPairs rpll = new ReverseLinkedListElementsInPairs();
  Node modifiedHead = null;
  System.out.println("------1st test-----");
  Node node1 = rpll.new Node(12);
  Node node2 = rpll.new Node(18);
  Node node3 = rpll.new Node(172);
  Node node4 = rpll.new Node(62);
  Node node5 = rpll.new Node(632);
  Node node6 = rpll.new Node(192);
  Node head = node1;
  node1.next = node2;
  node1.next.next = node3;
  node1.next.next.next = node4;
  node1.next.next.next.next = node5;
  node1.next.next.next.next.next = node6;
  System.out.println("Original list is:  12 18 172 62 632 192 19");
  System.out.print("Modified linked list is "
    + "(Using Iterative Implementation:) ");
  modifiedHead = rpll.reverseLinkedListInPairsIterative(head);
  displayLinkedList(modifiedHead);

  System.out.println("\n------2nd test-----");
  Node node12 = rpll.new Node(12);
  Node node22 = rpll.new Node(18);
  Node node32 = rpll.new Node(172);
  Node node42 = rpll.new Node(62);
  Node node52 = rpll.new Node(632);
  Node node62 = rpll.new Node(192);
  Node node72 = rpll.new Node(19);
  Node head2 = node12;
  node12.next = node22;
  node12.next.next = node32;
  node12.next.next.next = node42;
  node12.next.next.next.next = node52;
  node12.next.next.next.next.next = node62;
  node12.next.next.next.next.next.next = node72;
  System.out.println("Original list is:  12 18 172 62 632 192 19");
  System.out.print("Modified linked list is "
    + "(Using recursive Implementation:) ");
  modifiedHead = rpll.reverseLinkedListInPairsRecursive(head2);
  displayLinkedList(modifiedHead);
 }
}
==============Sample Output====================
 ------1st test-----
Original list is:  12 18 172 62 632 192 19
Modified linked list is (Using Iterative Implementation:) [ 18 12 62 172 192 632  ]
------2nd test-----
Original list is:  12 18 172 62 632 192 19
Modified linked list is (Using recursive Implementation:) [ 18 12 62 172 192 632 19  ]
=============================================

Find length of cycle in linked list in Java - Floyd cycle detection algorithm

Find length of cycle in a liked list is an application of Floyd cycle detection algorithm.In order to solve this problem, first we need to solve two problem in sequence - 1. find cycle in linked list in Java and 2. find beginning of cycle in linked list. Once we have found that beginning of  cycle, just traverse the cycle and manage a count until we reaches that starting node again. Refer above mentioned links for more details about cycle detection and finding beginning node of cycle. Below is the algorithm and sample code for finding length of cycle -
Algorithm:- 
1. First detecting cycle, then
2 .Find starting node of cycle
3. Find length of cycle (reach at beginning of beginning of cycle again)

Finding length of cycle:- 
static public int findLengthOfCycle(Node head) {
int length = 0;
if (head == null)
return 0;
Node fastReference = head;
Node slowReference = head;

/* Iterate linked list to detect cycle */
while (fastReference != null && slowReference != null) {
if (fastReference.next != null) {
/* fast reference - crosses 2 nodes at a time */
fastReference = fastReference.next.next;
}
if (slowReference != null) {
/* fast reference - cross 1 node at a time */
slowReference = slowReference.next;
}
if (fastReference!= null && slowReference!=null &&
fastReference.equals(slowReference)) {
   break;
}
}
/*
* Once cycle detected, place slowRef to start of linked list and
* traverse linked list one by one - they will meet again at start of
* node of cycle
*/
if (fastReference != null && slowReference != null) {
slowReference = head;
while (fastReference != slowReference) {
slowReference = slowReference.next;
fastReference = fastReference.next;
}


/* Find length of cycle - slowRef and fastRef referring same node */
slowReference = slowReference.next;
length++;
while (!slowReference.equals(fastReference)) {
slowReference = slowReference.next;
length++;
}
    }
return length;
}
Explanation:- While finding length of list, first we move slowReference and increment length. After that in while loop we traverse until again it meets fastReference.For each movement we increment length.

Below is the complete  sample program for finding length of cycle, if exist and return length of cycle.If cycle does not exist it return 0.
package com.devinline.linkedlist;

public class LengthOfCycleInCyclicSLL {

static Node head;

static public int findLengthOfCycle(Node head) {
int length = 0;
if (head == null)
return 0;
Node fastReference = head;
Node slowReference = head;

/* Iterate linked list to detect cycle */
while (fastReference != null && slowReference != null) {
if (fastReference.next != null) {
/* fast reference - crosses 2 nodes at a time */
fastReference = fastReference.next.next;
}
if (slowReference != null) {
/* fast reference - cross 1 node at a time */
slowReference = slowReference.next;
}
if (fastReference != null && slowReference != null
&& fastReference.equals(slowReference)) {
break;
}
}
/*
* Once cycle detected, place slowRef to start of linked list and
* traverse linked list one by one - they will meet again at start of
* node of cycle
*/
if (fastReference != null && slowReference != null) {
slowReference = head;
while (fastReference != slowReference) {
slowReference = slowReference.next;
fastReference = fastReference.next;
}

/* Find length of cycle - slowRef and fastRef referring same node */
slowReference = slowReference.next;
length++;
while (!slowReference.equals(fastReference)) {
slowReference = slowReference.next;
length++;
}
}
return length;
}

class Node {
public int data;
public Node next; // reference(handler) for next Node.

public Node(int data) {
this.data = data;
this.next = null;
}
}

public static void main(String[] args) {
LengthOfCycleInCyclicSLL cyc = new LengthOfCycleInCyclicSLL();
Node node1 = cyc.new Node(12);
head = node1;
Node node2 = cyc.new Node(18);
Node node3 = cyc.new Node(172);
Node node4 = cyc.new Node(62);
Node node5 = cyc.new Node(632);
Node node6 = cyc.new Node(192);
head.next = node2;
head.next.next = node3;
head.next.next.next = node4;
head.next.next.next.next = node5;
head.next.next.next.next.next = node6;
node6.next = node4; // cycle formed between node 6 and 4 - 62 is
// start
// of cycle

int lengthOfCycle = findLengthOfCycle(head);
System.out.println("Length of cycle is " + lengthOfCycle);

}

}
===Sample output====
Length of cycle is 3
=================