Wednesday, February 25, 2015

Why Array doesn't have Class file? Still we can create an array object without class file also

Hi,

I would like to let you know about arrays in java.

I have observed so many developers, when I ask to solve below problem they get confused and tell the wrong answer.

int[] a={1, 2, 3};
int[] b={1, 2, 3};

System.out.println(a.equals(b));
O/P= ?

They say true as answer which is a wrong answer.

Immediately I will ask them for explanation. They say both arrays are have same content so JVM checks for content to check the equality.

Then the next question will be what is the use of equals() method....

Explanation why the answer is false:

If we observe the java API. There is no direct class file to create object of type Array.

Whenever you execute above statements JVM internally creates a memory space based on its size and returns the reference to you. It means that there is no class to create object using new operator.

And if you check that object is the instance of Object class. It will show true.

It means, as per java standards any object you create for any class that objects parent object will be always Object only.

Here any kind of array created by JVM is the single level object in hierarchy of the object view. It means the immediate supper class always will be Object only.

You know what is there in Object class's equals() method..

And here in array object there is no implementation for equals() method. If the implementation is really there then we would have the class to create object.

So, whenever you execute above statements there will be two different objects even though they have same content in it and equals() method will be called of Object class object which will check for hashcode equality...

That's why you get false as output. :)

Hint: There is a separate assertion method available in junit to check the equality of two arrays...

Please give your feedback: nagarjuna.lingala@gmail.com

Usage of Vagrant along with Virtualbox

Hi All,

I already used virtualbox earlier. But recently I got a chance to work on it again. But here the usage style it's different. :)

Basically the thing is, we use virtualbox to run another operating system on the current OS. But as a normal user, we expect the UI from it.

As a developer, sometimes we don't require the UI instead we go for services from it. This time how do we run a virtual OS.

Virtualbox developers provided some command line utilities to achieve these kind of things.

But there will be a requirement to play with multiple operating systems virtually.

Here one tool helps us to do in that way...

That tool name is vagrant. It is really awesome to work with virtual operating systems. And no need to interact with the virtualbox directly. There will be a central configuration file for vagrant.

But the vagrant requires virtualbox :) i.e Vagrantfile

We can define which service port numbers of host OS to be routed to which ports of Guest OS.

Sunday, June 29, 2014

PowerMockito usage preparation

Powermockito is required when:
----------------------------------------------------

-    We are unable to mock static methods using normal mockito API.
-    We want to test final classes / methods
-    We are unable to test private methods.
-    We want to mock constructor.

Powermockito limitations:
-------------------------------------------
-    Currently there are no limitations with this API.


Creating mock object with PowerMockito:
-------------------------------------------------------------------
//similar to Mockito
    Singleton mockedObj=PowerMockito.mock(Singleton.class);

//writing stub methods is same as Mockito

 
Mock static method example:
-----------------------------------------------
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.nagarjuna.java.junit.A;
import com.nagarjuna.java.junit.B;
import com.nagarjuna.java.junit.Singleton;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ A.class, B.class, Singleton.class })
public class TestPowerMock {
    @Before
    public void init() {
        PowerMockito.mockStatic(Singleton.class);
        PowerMockito.when(Singleton.getOwnerName()).thenReturn("Suhail");
    }
    @Test
    public void test() {
        System.out.println(Singleton.getOwnerName());
    }
}



Mock private static method example:
--------------------------------------------------
//Similar to mock normal methods..
    http://code.google.com/p/powermock/wiki/MockitoUsage13

Mock void static method example:
-------------------------------------------------------
    PowerMockito.doThrow(new NullPointerException()).when(Singleton.class, "go");
    Singleton.go(); // will throw NullPointerException






Important Note:
-   Partial mock can be done in both Mockito and PowerMockito API using spy concept.
 
Powermockito maevn depedency:
------------------------------------------------------
   
        1.5.4
   

   
       
       
            junit
            junit
            4.11
       

       
            org.powermock
            powermock-module-junit4
            ${powermock.version}
       

       
            org.powermock
            powermock-module-junit4-common
            ${powermock.version}
       

       
            org.powermock
            powermock-api-mockito
            ${powermock.version}
       

       
            org.powermock
            powermock-api-support
            ${powermock.version}
       

       
            org.powermock
            powermock-core
            ${powermock.version}
       

       
            org.powermock
            powermock-api-easymock
            ${powermock.version}
       

       
            cglib
            cglib
            2.2.2
       

       
            easymock
            easymock
            2.0
       

   



VeryGood Resource: http://www.packtpub.com/article/mocking-static-methods

Mockito usage preparation

Mockito is required when:

-    We don't require / unable to create an object to a class which depends on any network related objects.  We can create a mock object to that class and write stubbing method calls.

-    We are unable to stop an object functionality which depends on other object ( returns some response) that will be impossible.  We can spy the real object and write stubbing method calls.

-   


Limitations with Mockito:
-----------------------------------------
-    We can't create mock object to final / immutable classes.
-    We can't write stub method calls for static methods in a class.
-    We can't write stub method calls for private methods in a class.
-    Mockito framework is useful only to create mock object and write stubb method calls on those mocked objects, ( not on static methods ). Go for PowerMockito


Basic examples:

Creating a mock object to class / Interface:
-------------------------------------------------------------------
import org.mockito.Mockito;
    List mockedList=Mockito.mock(List.class);   
    List mockedListC=Mockito.mock(ArrayList.class);



 

Writing basic stub method calls for non-void methods:
---------------------------------------------------------------------------------------
    Mockito.when(mockedList.get(Mockito.anyInt())).thenReturn("mockedresult");

 

Writing basic stub method calls for void methods - mocked object :
----------------------------------------------------------------------------------------------------------
    Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...

    doThrow(new RuntimeException()).when(mockedList).clear();

 
 Creating spy object:
-------------------------------
When you use the spy then the real methods are called (unless a method was stubbed).
    List list = new LinkedList();
    List spy = spy(list);


Writing basic stub method calls for void methods - spy object:
-----------------------------------------------------------------------------------------------
Sometimes it's impossible or impractical to use when(Object) for stubbing spies. Therefore when using spies please consider doReturn|Answer|Throw() family of methods for stubbing.
    List list = new LinkedList();
    List spy = spy(list);
   
    //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
    when(spy.get(0)).thenReturn("foo");
   
    //You have to use doReturn() for stubbing
    doReturn("foo").when(spy).get(0);

 
Reset mock objects:
--------------------------------
    Mockito.reset(mockedList);






Maven depedency:
       
            org.mockito
            mockito-all
            1.9.5
       

Saturday, March 1, 2014

Simple introduction to JUnit

Hi All,

  After a long time I am started posting ....:)

  In this post I show you how to use JUnit4.11

Junit is a java framework for the sake of unit test for our java code.

Here we have to know some notable annnotations .

1) @Before
2) @After
3) @BeforeClass
4) @AfterClass
5) @Test

@Before
    This annotation is used for any object level initialisation part.

This initialisation part will execute once per each test case in a test class.

Suppose if a test class has 4 test cases then this initialisation part will execute 4 times.

@After
    This annotation is used for any object level cleanup part.

This cleanup part will execute once per each test case in a test class.

Suppose if a test class has 4 test cases then this cleanup part will execute 4 times.

@BeforeClass
    This annotation is used for class level initialisation part.

This initialisation part will execute once per test class.

Suppose if a test class has 4 test cases then this cleanup part will execute 1 time only.

@AfterClass
    This annotation is used for class level cleanup part.

This cleanup part will execute once per test class.

Suppose if a test class has 4 test cases then this cleanup part will execute 1 time only.

@Test
    This annotation is the main one which executes our test case.

If you want any method to be executed without main method then use this annotation.

You have to use assertions for test pass.
We can have many assertions from junit framework.

Ex:- assertNotNull,
    assertNull,
    assertTrue,
    assertFalse,
    assertEquals,
    assertNotEquals.....etc

Monday, November 18, 2013

Can we write and execute main method inside an Abstract class ?



- With abstract class, we can't create an instance or object. But that class can have static methods as well as instance methods.

- If we want to utilize instance methods, we must extend that class and implement all abstract methods and then create an object to that child class. Finally we can utilize instance methods.

- We also can write and execute main method from an Abstract class.

Code snippet:

AbstractMain.java
------------------------
public abstract class AbstractMain{
        public static void main(String nag[]){
                System.out.println("hello :");
        }
}//end main

compile the above code and try to run from command-line. We get the output.

So abstract only restricts from object creation for a class. but if we want to use any static methods like above, we can simply use them..:)

Saturday, November 16, 2013

OOPS explanation (concepts)..10/10

OOPS : (Object Oriented Programming System)

Below are the main OOPS concepts...

Object:
Class:
Abstraction:
Encapsulation:
Inheritance:
Polymorphism:
MessagePassing:

Object:
   - An object represents anything that is really existing in the world. Object exists physically. JVM will allocate separate memory for object. because object is physically exist.

Class:
  - A class is model/idea/blue print for creating Objects. JVM can't allocate memory for class, because class doesn't exist physically.

Abstraction:
  - Hiding unnecessary data from user. [ view is an example for abstraction in oracle].
   Hiding implementation details is called Abstraction.
  advantages:  - It increases security
  - Enhancement is easy
  - Improves maintainability

Encapsulation:
  - Binding of data and methods as a single unit.
  example : class
   advantages:  - we can use the same variables or names in different classes.
   ----- If any class contains DataHiding + Abstraction such type of class is called Encapsulation.
  example: java bean
  advantages:  - It increases security
   - Enhancement is easy
   - Improves maintainability

Inheritance: 
  - Producing a new class from existing class.
  advantages : Re-usability of the code.

Polymorphism:
  - If something exists in several forms is called polymorphism. If same method is performing different tasks it is called polymorphism.

Message passing: 
  - Calling a method in OOPS is called message passing.



Friday, November 15, 2013

Main important usable Terms in Collection classes / implementations...10/10


Below are most important terms that we forget regularly....

  • Synchronized - Vector, Hashtable
  • NonSynchronized - All remaining
  • Ordered - ArrayList, Vector, LinkedList, LinkedHashSet, LinkedHashMap
  • Sorted - TreeSet, TreeMap
  • Homogeneous elements - TreeSet, TreeMap
  • Heterogeneous elements - remaining all
  • Allow nulls - ArrayList, Vector, LinkedList, HashSet, LinkedHashSet, 
  • No nulls - TreeSet
  • Allow nullkeys - HashMap
  • No nullkeys - HashTable
  • Allow nullvalues - HashMap
  • No nullvalues - HashTable
  • Iterator - All List and Set implements, All Map implements keySet's
  • ListIterator - only List implements, 
  • Enumeration - legacy Vector, HashTable
  • toArray - All List, Set implements
*** Since List, Set implementations are the instance of Iterable interface, we can iterate them using for-each loop at any time. ***

Monday, November 11, 2013

Count number of duplicate elements in ArrayList objects using Collections API?


Usage of Collections:

Suppose we have an ArrayList of characters / words which are repeated multiple times, And we want to count number of occurrences of each character / word..

We use only collections API.

Take an Example class

Test.java
-----------
import java.util.*;
public class Test{

        public static void main(String ar[]){

                ArrayList al=new ArrayList(); //It allows duplicates
                        al.add("a");
                        al.add("b");
                        al.add("c");
                        al.add("a");
                        al.add("b");
                        al.add("a");

                Set alSet=new HashSet(al); // no duplicates allowed in set, we get uniques

                        for(String element:alSet){ //using for-each loop
                                  int count=Collections.frequency(al,element); // this method counts the occurrences
                                 System.out.println(element+" repeated "+count+" times");
                        }//end for
        }//end main
}//end class



This is one of many methods,,

And similarly we can use Map object to count repeated characters/words..... Will be continued 

Sunday, November 10, 2013

How to print / iterate key and values of any map object?


Displaying key, values of any Map object - simplest way :

     We have many ways to display / iterate key, values of a map object. Here I am following advanced for loop and keySet.

Let us take a sample map object..

Map m=new HashMap();
                               m.put("1","one");
                               m.put("2","two");
                               m.put("3","three");
                               m.put("4","four");
                               m.put("5","five");
                               m.put("6","six");

// now we want to display all the keys with their respected values.

//We have a method called keySet() in Map interface. And this HashMap class implements that method.

//This method returns a Set object of  String elements ( we mentioned keys are strings in map object above).

 Set keySet=m.keySet();

//now we can iterate this Set without the help of iterator, because as per java guidelines from here. we can directly iterate set object using for-each loop with out the help of iterator object. So

 for(String key:keySet){
     System.out.println(key+":"+m.get(key)); // will print both key and value, and iterates..till last key.
 }//end for loop

// instead we can also write in a simple step using below line

for(String key:m.keySet()){
   System.out.println(key+":"+m.get(key));
}//end for loop

This is the benefit of for-each loop. Here we use for-each instead of using iterator object, and also we are no need to check for next object existence. 


code snippet:

Test.java
import java.util.*;
public class Test{

public static void main(String nag[]){

Map mp=new HashMap();
mp.put("i","one");
mp.put("2","two");
mp.put("3","three");

System.out.println("iterating....");
Set keySet=mp.keySet();
for(String key:keySet){
                       System.out.println(key+":"+mp.get(key));
}//end loop

            System.out.println("trying new one..:");
         for(String key:mp.keySet()){
                 System.out.println(key+"-"+mp.get(key));
}//end loop

System.out.println("done with new tech..");
}//end main
}//end class




Please send your valuable feedback to :
javaojavablog@googlegroups.com (or) nagarjuna.lingala@gmail.com



Thursday, November 7, 2013

What is the difference between an Ordered and Sorted Collection?



Ordered:
- An ordered collection means that the elements of the collection have a specific order. The order is independent of the value. A List is an example.

Sorted:
- A sorted collection means that not only does the collection have order, but the order depends on the value of the element. A SortedSet is an example.

-- In contrast, a collection without any order can maintain the elements in any order. A Set is an example.



Wednesday, November 6, 2013

Usage of foreach loop inside foreach loop, and also an example of iterating a List of Map objects ....9/10

Hi,

This page explain how to iterate a List object of Map objects using foreach loops.

Take a class Test.java

source :
package com.nagarjuna.core.collections:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {

public static void main(String[] args) {

List> lMap = new ArrayList>();

Map m = new HashMap();
m.put("1", "one");
m.put("3", "three");
m.put("2", "two");
m.put("0", "zero");

Map m1 = new HashMap();
m1.put("1", "one");
m1.put("0", "zero");
m1.put("2", "two");
m1.put("3", "three");

Map m2 = new HashMap();
m2.put("3", "three");
m2.put("1", "one");
m2.put("2", "two");
m2.put("0", "zero");

Map m3 = new HashMap();
m3.put("1", "one");
m3.put("2", "two");
m3.put("3", "three");
m3.put("0", "zero");

// now trying to put these map objects into a lis object


lMap.add(m1);
lMap.add(m2);
lMap.add(m3);
lMap.add(m2);
lMap.add(m);


// trying to print the key value pairs of each map from the list above

for (Map map : lMap) { //for each map obeject in list object
      System.out.println(lMap.indexOf(map)); //will print the index number of current map object in list
for (String key : map.keySet()) { // for each map's keyset object..iterating this keyset

System.out.println(key + ":" + map.get(key));
}//end inner loop

System.out.println("----------------------------------"); // end of first index of list object
}//end outer loop

}

}//end class


Just observe the above foreach loop code to understand how to use when we have to iterate a collection of collection of like this.



Tuesday, November 5, 2013

Usage of for loop styles in Collections..9/10

Example 1:

for (int i=0, n=list.size(); i < n; i++)
         list.get(i);
 
runs faster than this loop:
     for (Iterator i=list.iterator(); i.hasNext(); )
         i.next();

source: http://docs.oracle.com/javase/6/docs/api/java/util/RandomAccess.html

Monday, October 28, 2013

Singleton in multi threaded environment ? example of asynchronous, threads creating two or more objects to singleton.

Hi All,

In this post I am going to give an example of singleton class which is not thread safe and leads to create multiple objects by multiple threads..

Classes:

Singleton.java
Creator.java
Creator1.java
Test.java


Singleton.java
---------------------
public class Singleton {

private static Singleton s;
public static int count = 0;

private Singleton() {
count++;
}

public static Singleton getInstance() {
if (null == s) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

s = new Singleton();

}
return s;
}
public void display(){

System.out.println("hi");
}

}//end class

---------------------------------------------------------------------------------------------------------

Creator.java
---------------

public class Creator extends Thread {

@Override
public void run() {
Singleton s = Singleton.getInstance();
s.display();
}

}//end class

---------------------------------------------------------------------------------------------------------

Creator1.java
-----------------

public class Creator1 extends Thread {

@Override
public void run() {
Singleton s = Singleton.getInstance();
s.display();
}

}//end class

---------------------------------------------------------------------------------------------------------

Test.java
------------

public class Test {

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

Creator c = new Creator();
Creator1 c1=new Creator1();
c1.start();
c.start();
Thread.sleep(600);

System.out.println(" number of threads created is:" + Singleton.count);

}
}//end class



If you run the above Test class, the output will be like below

trail 1: 
hi
hi
 number of threads created is:1

trail 2:
hi
hi
 number of threads created is:2

trail 3:
hi
hi
 number of threads created is:2


....and so on..

Here even though we have made singleton class, In multi threaded environment, there is a chance of creating two objects / calling constructors two times  by multiple threads.







Wednesday, October 23, 2013

What happens when we write weaker access privileges for a overridden method compare to super class method?



This is an Interview question, This question raises while asking questions in corejava.

- While overriding any method, we must not write weaker privileges than the parent. If we write, we will get compilation error.


Take an example

A.java
public class A{
      public void go(){}
}

B.java
public class B extends A{
       public void go(){}
}

If we compile the above code, we don't get any compilation error and compiles successful.


Suppose change the access specifier of B's go() method to protected or private or default.

B.java
public class B extends A{
     protected void go(){}  --------->   compilation error
}


we will get compilation error stating that ...

error:
go() in B cannot override go() in A; attempting to assign weaker access privileges; was public
protected void go(){}
              ^
1 error

----------------------------------------------------------------------------------------------------------------------------

And one more thing we have to remember that we also cannot override private method...

example:

public class A{

        private void go(){
         }
}
public class B extends A{

        private void go(){ //It compiles successfully, but Its not overridding..
         }
}

How:
- If we write annotation in class B's go() method as @Override, Then the compiler will give us error,
- So, we cant override private methods...

Monday, October 21, 2013

The most important difference between Comparable and Comparator interfaces...


Imp Difference:

- Comparable interface is available in java.lang package, and it is used for natural ordering of the objects.

- Comparator interface is available in java.util package, and it is used for custom ordering of the objects (or) custom comparison between objects.


read Comparable tips.

Comparable - some tips...

Tips :
 
                    -  The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C.


*******  Since null is not an instance of any class, and e.compateTo(null) should throw NullPointerException even though e.equals(null) returns false.

******* This interface is a member of the Java Collections Framework.

 - The implementor must ensure sign(x.compareTo(y)) == -sign(y.compareTo(x)) for all x and y. 
  ( This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

- It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y))

suppose returning value is 'v'.

value           meaning
v<0 dd="" is="" less="" nbsp="" obj="" specified="" than="" the="" this="">
0                 this obj is equal to specified obj,
v>0             this obj is greater than the specified obj


source: http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

Insurance domain knowledge links to read and learn..

Cross compiling in java .... :P


Cross compilation in java:



Basics: 

Here I have two JDK locations in my system.

1) Default Jdk (1.6) is located in $JAVA_HOME (/usr/lib/jdk1.6.0_45)
2) Lower version Jdk (1.5) is located in ~/jdk_5/jdk1.5.0_22/ 

Now take a sample class 

public class Test{

            public static void main(String nag[]){
                     
                     System.out.println("Hello Nagarjuna");

            }
}//end class

now I am compiling using jdk 1.6 like

                $ $JAVA_HOME/bin/javac Test.java
It will be compile and generate Test.class


And now try to run this Test.class file using jdk 1.6

                $ $JAVA_HOME/bin/java Test
                o/p :  Hello Nagarjuna


lly, Now try to run with  jdk 1.5

           $ ~/jdk_5/jdk1.5.0_22/bin/java Test
         o/p:  
       Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)


It is because of higher version compilation and lower version execution.

           But we can compile the above Test.java using jdk 1.5 and can run the generated Test.class file in both jdk1.6 and jdk1.5 . Because lower version compilation can support higher (Latest) version execution.

Now, let us try cross compilation in jdk 1.6


Cross compilation:  

Here we use javac arguments  ( only 'target')

Use 'taget' argument to javac while compiling with jdk1.6.



compilation: 

$ $JAVA_HOME/bin/javac -target 1.5 Test.java

And now, Let us try to run the generated Test.class file in both jdk 1.6 and jdk 1.5

first in jdk 1.6 -
          $ $JAVA_HOME/bin/java Test
          o/p: Hello Nagarjuna

 in jdk 1.5 -
           $  ~/jdk_5/jdk1.5.0_22/bin/java Test
           o/p: Hello Nagarjuna


So, we can do cross compilation using any higher version JDK. 

Try on your own          


Sunday, October 20, 2013

Gererating SerialVersionUID for a serializable class...

Hi All,

In this post I am going to show you how to generate serialVersionUID for a serializable class.(java.io.Serializable)


Purpose of  the serialVersionUID variable : 

Any serializable class will need a unique class identifier called serialVersionUID.

              This long value is used to allow the JVM to know if a version of the class has changed. If you neglect to include it in your class, then one will be generated on the fly. You don’t want that.


Generating serialVersionUId for our custom class : 

  Take an example class A which implements Serializable inteface. 

    public class A implements Serializable{

    } //end class


If we want to generate unique serial version uid, then we have a command in JDK's bin folder with the name serialver.


use below command to generate UID.

$ serialver A
A:    static final long serialVersionUID = -5362330504532103641L;

we can type the above command may times, we will get the same UID all time.


Note: For any library related serializable class  like hibernate or spring related serializable class, while generating UID, all the instance related classes must be in class path. So don't forget to put all compilation related classes in classpath.