Thursday, December 22, 2011

Inner class and Anonymous classes in Java

Nested Classes in Java

A nested class is a class defined inside the definition (body) of another enclosing class. 
A nested class can be of two types - static or non-static. A nested class is treated as a 
member of the enclosing class. A static nested class is not very tightly integrated with 
the enclosing class and it lives its own independent life as well i.e., a static nested 
class can be instantiated like any other class from just about anywhere. 
They are defined inside the definition of an enclosing class just to get a logical grouping 
of the classes, which in turn increases readability and provides better packaging convenience.

A static nested class can't directly access the members of the enclosing class. Like any other 
top-level class it needs to access the members of the enclosing class via object references only.

Example: a static nested class

class EnclosingClass {
 static class StaticNestedClass{
  //...definition of the static nested class

A static nested class is accessed using the enclosing class name as follows:
EnclosingClass.StaticNestedClass staticNestedObjectRef = new EnclosingClass.StaticNestedClass();

Inner Classes in Java
A non-static nested class is called an inner class and it's tightly integrated with the enclosing 
class unlike a static nested class. An inner class instance can't exist independent to the enclosing 
class instance. An inner class instance always exist within the instance of the enclosing class. 
Since, it's always associated with the enclosing class instance and it has direct access to all the 
members of the enclosing class - even the private members.

Example: an inner class
class EnclosingClass {
 class InnerClass{
 //...definition of the inner class

Since, an instance of an inner class always exists within an instance of the enclosing class, hence 
we must instantiate the enclosing class first and then on that instance we can instantiate the inner class:-

EnclosingClass enclosingObjectRef = new EnclosingClass();
EnclosingClass.InnerClass innerObjectRef = InnerClass();

Can an Inner Class declare static members?
No. Because any instance of an inner class is always associated with an instance of the enclosing class.

Can we have private or protected access for classes in Java?
Yeah... but only for nested classes and not for top-level classes. Nested classes 
are treated as members of the enclosing classes and hence we can specify any of the 
four access specifiers - private, package, protected, or public. We don't have this luxury 
with top-level classes - they can only be declared public or package.

Local Inner Classes in Java
If an inner class has been defined within a code block (typically within the body of a method), 
then such an inner class is called a local inner class. A local inner class is not a member 
of the enclosing class and hence it can not have any access specifier. A local inner class 
will have access to all the members of the enclosing class and it'll have access to the local 
final variables in the scope it's defined.

Example: a typical local inner class
public class EnclosingClass{
 public methodName(){
  //...definition of the local inner class
   class LocalInnerClass {

Anonymous Inner Classes in Java
If an inner class has been declared without a name and within a code block (typically within the 
body of a method) then such an inner class is called an anonymous inner class. 
Since such an inner class doesn't have a name associated, so it'll be accessible only at the point 
where it is defined.

Example: a very common usage of an anonymous inner class
import java.awt.event.*;
public class GUI extends JFrame{
    public void buildComponents(){
        button1 = newJButton();
        button1.addActionListener(new ActionListener(){
          public void actionPerformed(java.awt.event.ActionEvent ae){

Since, an anonymous inner class doesn't have a name, so it can't have a named constructor. 
But, it can have an instance initializer. Access rules for anonymous inner classes are same as that of 
local inner classes. Similar to a local inner class, an anonymous inner class can also not have 
any access specifier attached to it.

Are anonymous inner classes same as local inner classes?
Yeah..., an anonymous inner class is a local inner class in all means except that it doesn't 
have a name and hence it can't be used at any other point except at the point where it has 
been defined. The other difference is that it can't have a named constructor again for the 
same reason that it doesn't have a name.

Tuesday, December 13, 2011

Deadlock in Java

How to avoid Deadlock in Java is one of the question which is flavor of the season for multithreading, 
asked more at a senior level and with lots of follow up questions, though question looks very basic 
but most of the developer get stuck once you start going deep.

Questions starts with "What is deadlock ?"
Answer is simple: When two or more threads waiting for each other to release lock and get stuck for 
infinite time, situation is called deadlock. It will only happen in case of multitasking.

How do you detect deadlock in Java ?
Though this could have many answers, my version is first I would look the code if I see 
nested synchronized block or calling one synchronized method from other or trying to get 
lock on different object then there is good chance of deadlock if developer is not very careful.

other way is to find it when you actually get locked while running the application, try to 
take thread dump, in Linux you can do this by command "kill -3", this will print status of 
all the thread in application log file and you can see which thread is locked on which object.

Another way is to use "jconsole", "jconsole" will show you exactly what are the threads get 
locked and on which object.

Once you answer this, they may ask you to write code which will result in deadlock ?
Here is one of my version
public class ThreadB extends Thread {
    public void run(){
    public void method1(){
            System.out.println("ThreadB: Aquired lock on Integer.class object");
            //Nested synchronized block
            synchronized (String.class) {
                System.out.println("ThreadB: Aquired lock on String.class object");
public class ThreadC extends Thread {
    public void run(){
    public void method2(){
            System.out.println("ThreadC: Aquired lock on String.class object");
            //Nested synchronized block
            synchronized (Integer.class) {
                System.out.println("ThreadC: Aquired lock on Integer.class object");
public class MainExample {
    public static void main(String[] args){
        new ThreadB().start();
        new ThreadC().start();
//Output with System/Java console Hanged:
ThreadB: Aquired lock on Integer.class object
ThreadC: Aquired lock on String.class object
If method1() and method2() both will be called by two or more threads, there is a good chance of 
deadlock because if Thread1 aquires lock on Sting object while executing method1() and Thread2 
acquires lock on Integer object while executing method2() both will be waiting for each other to 
release lock on Integer and String respectively to proceed further which will never happen.

Now interviewer comes to final part, one of the most important in my view, How to fix deadlock? 
or How to avoid deadlock in Java ?

If you have looked above code carefully you may have figured out that real reason for deadlock is 
not multiple threads but the way they access lock, if you provide an ordered access then problem 
will be resolved, here is the fixed version.

public void method1(){
        System.out.println("Aquired lock on Integer.class object");
        //Nested synchronized block
        synchronized (String.class) {
            System.out.println("Aquired lock on String.class object");

public void method2(){
        System.out.println("Aquired lock on Integer.class object");
        //Nested synchronized block
        synchronized (String.class) {
            System.out.println("Aquired lock on String.class object");
Now deadlock is fixed!!!!! There would not be any deadlock because both method is accessing 
lock on Integer and String object in SAME ORDER. So if Thread A acquires lock on Integer object, 
Thread B will not proceed until Thread A releases Integer lock. Same way Thread A will not be 
blocked even if Thread B holds String lock because now Thread B will not expect Thread A to 
release Integer lock to proceed further.

Hope this would be useful. Contents are copied from Internet but Example is modified and tested. Link can be seen here:

Thursday, December 8, 2011

Acre, Metre and Foot Conversion guide

Dear Reader,
Adding some contents here which is a land measurement on 
Acre, Foot and Metre. It definitely will help you.
1 Acre = 43560 Sq.Foot

1 Metre = 3.280 Feet
1 Foot  = 0.3048 Metre (1.0/3.280).
1 Square Metre = 10.76 Sq.Feet (3.28 * 3.28 = 10.76)

1 Square Feet = 0.09290304 Square Metre (0.3048 mtr * 0.3048 mtr)  
1000 Square Feet = 92.903 Square Metre

1 Cubic Metre = 35.3 Cubic Feet (3.28 * 3.28 * 3.28)

1 Foot = 30.48 Centimeters
1 Square Feet = 929.03 Centimeters (30.48 * 30.48 = 929.03) 

1 Square Yard = 0.836 Square Metre
1 Square Metre = 1.196 Square Yards

1 Bigha = 0.4 Hectare.

1 Bigha = .625 Acre = 5/8 Acre (This is different in different parts of World, but mostly used).
1.6 Bigha = 1 Acre

1 Square Mile = 2.59 Square KM = 259 Hectares
1 Mile = 1.6 KM.

Thursday, December 1, 2011

String functions in Oracle

Dear reader, 
Writing few String functions available in Oracle:

-------     --------------   -----------------
Saikumar        8            7
Deepak          6            7

SELECT Length('deepak '), TRIM('deepak '),Length(TRIM('deepak ')) FROM tab;
7  deepak  6

SELECT TRIM(LEADING '#' FROM 'rajesh##') FROM dual;    //rajesh##
SELECT TRIM(LEADING '#' FROM '##rajesh##') FROM dual;  //rajesh##
SELECT TRIM('#' FROM '##rajesh##') FROM dual;          //rajesh
SELECT TRIM('#' FROM '##raj##esh##') FROM dual;        //raj##esh

Source_Str, Start_Pos, End_Pos

Value of Start_Position     
Positive ==    Counts forward from the first character in source_string
Zero (0) ==    Counts forward from the first character in source_string (that is, 
            treats a start_position of 0 as equivalent to 1)
Negative ==    Counts backward from an origin that immediately follows the last character in source_string A 
            value of -1 returns the last character in source_string.


INSTR is used to find the position of any particular character in a word which 
returns numeric value. It IS CASE sensitive.

SELECT instr('KUMAR','e') FROM dual;  //0, e IS NOT present
SELECT instr('KUMAR','m') FROM dual;  //0, NOT matched, CASE sensitive
SELECT instr('KUMAR','M') FROM dual;  //3, INDEX starts FROM 1 here.

Source_Str, OLD_VAL, NEW_VAL
SELECT REPLACE('Deepak kumar', 'De', 'Ra')  FROM dual; //Raepak kumar

Source_Str, Total_No_Char, Filling_Char
SELECT LPAD('Here we are', 11, '-_') FROM dual;  //Here we are
SELECT LPAD('Here we are', 16, '-_') FROM dual;  //-_-_-Here we are  

Generating Secure Numbers or Random Numbers like PIN/OTP

Dear Reader,

I am writing a useful post here: How to generate Secure Number sequences or Random Number sequences like PIN/One time
passwords or any number sequence for Temporary passwords which are numeric. I have explained the complete tutorial by
giving first a practical example that we use in our coding practices. The complete theory is given at the below section
after coding example.

At first, I have written code to generate simple Random Number based on given length, then the secure one:

//Basic Random Generator
package com.dmodi.utils;
import org.apache.commons.lang.RandomStringUtils;
//Add commons-lang-2.4.jar
public class RandomNumberGenerator {
    public static void main(String[] args) {
        for(int i=0;i<10;i++){

    public static String generateRandomNumber(int length){
        String randomNumber="";
        randomNumber = RandomStringUtils.randomNumeric(length);
        return randomNumber;


//Secure Random Generator
//Add commons-lang-2.4.jar
import org.apache.commons.lang.RandomStringUtils;

public class OTP_Generation {
    public static void main(String[] args) {
        int otpLength=4;
        for(int i=0; i<10;i++) {
            System.out.println("OTP using SecureRandomGenerator: "+(i+1)+"==>"+generateOTP(otpLength));
        for(int i=0; i<10;i++) {
            System.out.println("OTP using RandomNumberGenerator: "+(i+1)+"==>"+generateRandomOTP(otpLength));

    public static String generateOTP(int otpLengthNumber){
        String otp = new String();
        int otpSample=0;
        for(int i=0;i<otpLengthNumber;i++){


        SecureRandom prng;
        try {
            prng = SecureRandom.getInstance("SHA1PRNG"); //Number Generation Algorithm
            otp = new Integer(prng.nextInt(otpSample)).toString();
            otp = (otp.length() < otpLengthNumber) ? padleft(otp, otpLengthNumber, '0') : otp;
        } catch (NoSuchAlgorithmException e) {

//        If generated OTP exists in DB -regenerate OTP again
        boolean otpExists=false;
        if (otpExists) {
        } else {
            return otp;
        return otp;
    private static String padleft(String s, int len, char c) { //Fill with some char or put some logic to make more secure
        s = s.trim();
        StringBuffer d = new StringBuffer(len);
        int fill = len - s.length();
        while (fill-- > 0)
        return d.toString();
    public static String generateRandomOTP(int otpLengthNumber){
        String otp = RandomStringUtils.randomNumeric(otpLengthNumber);
        return otp;

While generating random numbers in Java for Security purposes, we use class or
org.apache.commons.lang.RandomStringUtils class. SecureRandom class is designed to provide cryptographically secure
random numbers, however sometime it's become quite predictable if not used properly. I explained below:

SecureRandom class uses Pseudo Random Number Generator (PRNG) implementation for generating numbers. The PRNGs are
part of Cryptographic Service Providers (CSP) (here SUN for JAVA) is default CSP. On Windows env, SUN CSP uses "SHA1PRNG"
algorithm. On Unix env it is using something else, not mentioning here. At present, we use this Window's environment only.

SecureRandom sr1 = new SecureRandom();
//The following will create SUN SHA1PRNG if the highest priority CSP is SUN
SecureRandom sr2 = SecureRandom.getInstance("SHA1PRNG");

//The following will always create SUN SHA1PRNG
SecureRandom sr3 = SecureRandom.getInstance("SHA1PRNG", "SUN");

The PRNG tries to ensure that the output does not reveal any information about the seed, and that somebody observing the
output cannot predict future outputs without knowing the seed.

What is SEED?
An early computer-based PRNG, suggested by John von Neumann in 1946, is known as the middle-square method. The algorithm
is as follows: take any number, square it, remove the middle digits of the resulting number as the "random number", then
use that number as the seed for the next iteration.

For example, squaring the number "1111" yields "1234321", which can be written as "01234321", an 8-digit number being the
square of a 4-digit number. This gives "2343" as the "random" number. Repeating this procedure gives "4896" as the next
result, and so on. "Von Neumann" used 10 digit numbers, but the process was the same.
A problem with this "middle square" method is that all sequences eventually repeat themselves, some very quickly, such
as "0000". Von Neumann was aware of this, but he found the approach sufficient for his purposes, and was worried that
mathematical "fixes" would simply hide errors rather than remove them.

Note that according to Sun’s documentation, the returned instance is not seeded by any of these
calls. If after one of these calls,[]) is called, then the PRNG is seeded using a
secure mechanism provided by the underlying operating system (starting with JRE 1.4.1 in Windows and JRE 1.4.2 in Linux and Solaris).

If or[]) is called before a call to[]), then the internal seeding mechanism is bypassed, and only the provided seed is used
to generate random numbers.

By bypassing the internal secure seeding mechanism of the SHA1PRNG, you may compromise the security of your PRNG output. If you
seed it with anything that an attacker can potentially predict (e.g. the time when the PRNG instance was created), then using may not provide the level of security that you need.

Finally, regardless of how well the PRNG is seeded, it should not be used indefinitely without reseeding. There are two approaches
that can be used for longer-term security of PRNG output:

Periodically throw away the existing instance and create a new one. This will generate a new instance
with a new seed.
Periodically add new random material to the PRNG seed by making a call to
::::>>> ).

In summary, keep the following in mind when using Always specify the exact PRNG and provider that you
wish to use. If you just use the default PRNG, you may end up with different PRNGs on different installations of your application that
may need to be called differently in order to work properly. Using the following code to get a PRNG instance is appropriate:

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");

When using the SHA1PRNG, always call[]) immediately after creating a new instance of the PRNG.
This will force the PRNG to seed itself securely. If for testing purposes, you need predictable output, ignoring this rule and seeding
the PRNG with hard-coded/predictable values may be appropriate. Use at least JRE 1.4.1 on Windows and at least JRE 1.4.2 on Solaris and Linux.

Earlier versions do not seed the SHA1PRNG securely. Periodically reseed your PRNG as observing a large amount of PRNG output generated
using one seed may allow the attacker to determine the seed and thus predict all future outputs.

Some of the theoretical contents are taken from few websites but are tuned as per my way of writing, however the coding example is
completely mine. Please read and leave the comment if found useful.

Another Example with Seeding:

try {
    // Create a secure random number generator
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // Get 1024 random bits
    byte[] bytes = new byte[1024/8];

    // Create two secure number generators with the same seed
    int seedByteCount = 10;
    byte[] seed = sr.generateSeed(seedByteCount);

    sr = SecureRandom.getInstance("SHA1PRNG");
catch (NoSuchAlgorithmException e) {