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.



Saturday, October 19, 2013

Inheritance prevention mechanism in java..

Inheritance prevention mechanism :

As of my knowledge, I got two mechanisms to prevent inheritance in java.

1) Using final keyword
2) Using private keyword


1) We know the usage of final keyword.

- If we use 'final' for any variable, that variable can't be changed later.
- If we use 'final' for any instance method, that method can't be overridden.
- If we use 'final' for any class, that class can't be inherited or extended.

example code:
public final class A{

}//end class

public class B extends A{ // can't be done

}//end class

- we will get compilation error stating that the class A is final and can't extend.



2) We know that we can't write private in front of the class.

But we can write this private keyword in front of the constructor. ( used in singleton class)
- It means, once we specify the constructor as private, no one can call that constructor from outside of that class.
- So by using this logic, we can say that we can't extend that class.

explanation: 

- If we see constructor chaining, the child class constructor should call its parent class constructor then only the object creation will be done. If the child class is unable to call its parent class constructor then we can't use that class to create an object.
- From the above logic, once the constructor is declared as private then No other class can extend this class.



example code:

public class A{
      //private constructor
      private A(){
      }
}//end class

public class B extends A{
   //public constructor
   public B(){
    }
}//end class


If we try to compile class B, we will get compilation  error that ....

A() has private access in A
public class B extends A{
       ^
1 error

Can a Singleton class can be inherited?


Please read Inheritance prevention mechanisms at javaojava.blogspot.in/2013/10/inheritance-prevention-mechanism-in-java.html

Can constructor throws Exception?

Constructors also can throw exceptions like methods: 

Let us take an example


CException.java :
public class CException{

        //Constructor 
        public  CException()throws Exception{
               //.....
        }
}

From the above code snippet, 
      A constructor also can throw an exception like a method, and the object creation logic has to handle this exception. The handling will be done using try, catch block as we use for methods..

If we try to write object creation code to the above class, we will get compilation error like..

unreported exception java.lang.Exception; must be caught or declared to be thrown
CException ce=new CException();
             ^
1 error

...So be careful in the interview...


Wednesday, October 16, 2013

Hashtable imp methods

Hashtable:


- It doesn't allow null keys and null values. But it already has one null key and one null value in it , And we are no more able to insert null keys and null values.

-It is Synchronized object.

- Since it extends Dictionary, There are two important metthods
abstract  Enumeration<V>elements()
          Returns an enumeration of the values in this dictionary.
abstract  Enumeration<K>keys()
          Returns an enumeration of the keys in this dictionary.

So HashTable has to implement there methods...
These two methods are not there in HashMap class because it implements Map interface and extends AbstractAMap class so no more methods it has to implement.

- Since it implements  Map interface, There are three important methods
 Set<Map.Entry<K,V>>entrySet()
          Returns a Set view of the mappings contained in this map.
 Set<K>keySet()
          Returns a Set view of the keys contained in this map.
 Collection<V>values()
          Returns a Collection view of the values contained in this map.

So, here you can do both iterate and enumerate keys as well as values.

- Since Hashtable implements Serializable, we can serialize this object. 
- Since Hashtable implements cloneable, we can get the shallow copy of the object.

HashMap imp methods


Spring MVC workflow..

Spring MVC: 

The main components in spring-mvc are front controller, handler mappings, controllers, view resolvers, and views.


work flow:

- First a web request is submitted to the application.

- The FrontController receives the request and interprets it to find the appropriate handle mapping. The handle mapping maps the request to an appropriate Controller object.

- The front controller forwards the request to the controller object.

- The controller receives the request, processes it, and returns a Model and View object to the front controller.

- The front controller uses View Resolvers to find the appropriate View object.

- The view object is used to render the result which then sends it back to the client.





Using HIBERNATE with SPRING (HibernateTemplate)

HibernateTemplate:

      Spring offers HibernateTemplate to simplify implementation of the Hibernate data access code.
HibernateTemplate includes various methods that reflect the Hibernate Session methods.

- It takes the responsibility to manage the Hibernate Session making the application free from implementing the code for opening and closing the Hibernate session accordingly.
- It provides a service - to convert the HibernateException's into DataAccessExceptions.

Spring framework includes two HibernateTemplate classes
1) org.springframework.orm.hibernate.HibernateTemplate  -  to work with hibernate2.1
2) org.springframework.orm.hibernate3.HibernateTemplate  - to work with hibernate3

Note: spring framework from its 2.5 version onwards supports to work with Hibernate3.1 or higher version only.

To use HibernateTemplate object, you must pass SessionFactory object to it and then use.

There are 3 constructors in HibernateTemplate class
1) HibernateTemplate()
     - you must pass SessionFactory object before you use any method of this object using setSeesionFactory() method.

2) HibernateTemplate(SessionFactory)
3) HinernateTemplate(SessionFactory, boolean)
  - if you pass true as boolean value... HibernateTemplate perform its own Session management instead of participating in a custom Hibernate current session context.



It is not recommended to use now these days. ***

source:
Spring and Hibernate (SANTOSH KUMAR K)

tomcat web application deployment and configuration tips.

HashMap important methods... notes ...

HashMap:

java.util.Map is an Interface

public interface java.util.Map{
    public abstract int size();
    public abstract boolean isEmpty();
    public abstract boolean containsKey(java.lang.Object);
    public abstract boolean containsValue(java.lang.Object);
    public abstract java.lang.Object get(java.lang.Object);
    public abstract java.lang.Object put(java.lang.Object, java.lang.Object);
    public abstract java.lang.Object remove(java.lang.Object);
    public abstract void putAll(java.util.Map);
    public abstract void clear();
    public abstract java.util.Set keySet();
    public abstract java.util.Collection values();
    public abstract java.util.Set entrySet();
    public abstract boolean equals(java.lang.Object);
    public abstract int hashCode();
}


java.util.HashMap is an implementation class to Map interface

public class java.util.HashMap extends java.util.AbstractMap implements java.util.Map,java.lang.Cloneable,java.io.Serializable{
    static final int DEFAULT_INITIAL_CAPACITY;
    static final int MAXIMUM_CAPACITY;
    static final float DEFAULT_LOAD_FACTOR;
    transient java.util.HashMap$Entry[] table;
    transient int size;
    int threshold;
    final float loadFactor;
    volatile transient int modCount;
    public java.util.HashMap(int, float);
    public java.util.HashMap(int);
    public java.util.HashMap();
    public java.util.HashMap(java.util.Map);
    void init();
    static int hash(int);
    static int indexFor(int, int);
    public int size();
    public boolean isEmpty();
    public java.lang.Object get(java.lang.Object);
    public boolean containsKey(java.lang.Object);
    final java.util.HashMap$Entry getEntry(java.lang.Object);
    public java.lang.Object put(java.lang.Object, java.lang.Object);
    void resize(int);
    void transfer(java.util.HashMap$Entry[]);
    public void putAll(java.util.Map);
    public java.lang.Object remove(java.lang.Object);
    final java.util.HashMap$Entry removeEntryForKey(java.lang.Object);
    final java.util.HashMap$Entry removeMapping(java.lang.Object);
    public void clear();
    public boolean containsValue(java.lang.Object);
    public java.lang.Object clone();
    void addEntry(int, java.lang.Object, java.lang.Object, int);
    void createEntry(int, java.lang.Object, java.lang.Object, int);
    java.util.Iterator newKeyIterator();
    java.util.Iterator newValueIterator();
    java.util.Iterator newEntryIterator();
    public java.util.Set keySet();
    public java.util.Collection values();
    public java.util.Set entrySet();
    int capacity();
    float loadFactor();
}


The above code is generated from the command 'javap'  
usage: javap java.util.Map
           javap java.util.HashMap

From the above methods, some methods are very important methods we have to consider.

in Map:

1) public java.lang.Object put(java.lang.Object, java.lang.Object);
 
-  put method is to put an element/ object / value  in the map object with a reference/map to it (key).
-  Here key, values can be any type.
-  Most preferably key must be immutable and value can be any. Because HashMap concept is depending on hashcode / hashing mechanism. If the key is mutable then the hashcode will be changed, So, It may leads to unreliable. see hashing and bucketing concept  for more clarity.

          This put method returns an object only when try to put an object in the place of old object, and this old object will be returned. From this we will be notified that the returned object is replaced by new object.

      For example: 
m.put("1","one")      --->    returns null   ( because no object (value) was there with that key)
m.put("1","ONE")    --->   returns "one" (because "one" was the old object)


2) public java.lang.Object remove(java.lang.Object); 

- remove removes an element/ value from the map object, here we have to say map that remove the element which is referenced/mapped with this key. So we have to give the corresponding key to remove an element/ value from map object.
      
       remove(key) : returns value of that key
        This remove method returns an Object that is the mapping value you specified key to remove from map object otherwise returns null if the specified key is not there in map object. From this we will be notified that the specified key is removed along with value.

    For example: 
m.put("1", "one")    ----> returns null (because no object (value) was there with that key)
m.remove("1")        ----> returns "one" (because "one" is there with that key)
m.remove("1")        ----> returns null (because no object (value) is there with that key)


3) public java.util.Set keySet();

     This keySet method returns java.util.Set implemented class Object ( We have unknown collection implementations ) , So we have to consider this object as Set type object.

  -  An unordered Set object.
  -  we can iterate this set object and get values from map object.
  -  we can make this collection object to an array object.


    For example:
       1)    Set set = m.keySet();
               Iterator itr = set.iterator();

while (itr.hasNext()) {
System.out.println(m.get(itr.next()));
}//end while  
o/p ...
three
two
one
         2)      Object[] oar= set.toArray();
                  for (int i = 0; i < oar.length; i++) {
System.out.println((String)oar[i]);
}//
o/p...
3
1

     In this second example you cannot convert the object oar to String array object directly like this
String[] strAr=(String[]) oar;  ----- X    
          Because the elements of Object[] array are to be type casted to String type at runtime. 

4) public java.util.Collection values();

      This values method returns all values in the map object in Collection form / notation /view  that can be of any collection interface implementation class object type.

-  An unordered Collection object.
-  we can iterate this Collection object and use values of map object.
-  we can make this collection object to an array object.

  see keySet method example .

5) public java.util.Set entrySet(); 

     Set<Map.Entry<K,V>>  entrySet() 

  This entrySet method returns Set object which contains Entry(is a inner class from Map interface) class objects. These Entry objects are the main objects which holds key, value pairs.


look into Entry api 


in HashMap:

1) public java.lang.Object clone();

 -   Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.

     This clone method returns a copy of the map object that will have all the elements as old in it.

for example:

           map.remove("2");
           HashMap hMap=(HashMap)map;
           Map bMap =(HashMap)hMap.clone();
                                System.out.println(bMap.isEmpty()); -- > false
                                System.out.println(bMap.size()); --> some value
                                System.out.println(bMap.containsKey("1")); -- >true
                                System.out.println(bMap.containsValue("two"));-->false
                                System.out.println("TWO".equalsIgnoreCase(bMap.get("two"))); --> false



Key Points....

- Hashmap allows duplicate keys and duplicate values including null also.

for example:
                                       Map mp=new HashMap();
                                        mp.put(null,null);
                                        mp.put(null,null);
                                        mp.put("1",null);
                                        mp.put("2","ttt");
                                System.out.println(mp.get("1"));
                                        mp.put(null,"33");
                                System.out.println(mp.put("1","one"));
                                System.out.println(mp.put("2","two"));
                                System.out.println(mp.get("1"));
o/p:
null
null
ttt
one

- This implementation (HashMap) is not synchronized.
 If we need HashMap to be synchronized, we have to approach 
   Map m = Collections.synchronizedMap(new HashMap(...));

- Initially this HashMap object contains null key, null value...and we can insert null key and null values later also. 

for example:
                                        Map mp=new HashMap();
                                        System.out.println(mp.put(null,null)); --- > returns null

and also we can insert one more null later..


Hashtable imp methods



to be continued......








Wednesday, October 9, 2013

Standard Maven installation in Linux / Unix . 10 /10

Unix-based Operating Systems (Linux, Solaris and Mac OS X)

  1. Extract the distribution archive, i.e. apache-maven-3.1.1-bin.tar.gz to the directory you wish to install Maven 3.1.1. These instructions assume you chose /usr/local/apache-maven. The subdirectory apache-maven-3.1.1 will be created from the archive.
  2. In a command terminal, add the M2_HOME environment variable, e.g. export M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1.
  3. Add the M2 environment variable, e.g. export M2=$M2_HOME/bin.
  4. Optional: Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.
  5. Add M2 environment variable to your path, e.g. export PATH=$M2:$PATH.
  6. Make sure that JAVA_HOME is set to the location of your JDK, e.g. export JAVA_HOME=/usr/java/jdk1.5.0_02 and that $JAVA_HOME/bin is in your PATH environment variable.
  7. Run mvn --version to verify that it is correctly installed.

How to connect to any machine without password using SSH ? And how to configure ? 9/10

Hi All,

Here I am going to show you how to connect to any machine with the use of ssh.

Here we consider two machines  ( both are Linux here)
1) Master
2) Slave

Now the scenario is, I want to access Master machine from Slave Machine.

What to do:
Steps...

- Install openssh-server in both of these machines.
                       Use command 'sudo apt-get install openssh-server'
- ssh configuration files are created in the location ' ~/.ssh ' is a directory.
- Since Slave wants to connect to Master, Slave needs public key of Master machine in it.

Note: Think the machine name nagarjuna@nagarjuna-Aspire-4736 is a Master Machine.

pic1:


- Generate public key, using ssh-keygen command in Master machine

pic2:

- we get files like below, can see using tree command.

pic3:

- Here we need the file named ' id_rsa.pub ' to be copied to Slave machine.


Key Copying process to Slave Machine:

- Create a touch file with the name ' authorized_keys ' under the .ssh folder in the Slave machine.
- And now copy the Masters ' id_rsa.pub ' content to ' authorized_keys ' file using below command
  ' cat id_rsa.pub >>authorized_keys ' .
- Now connect to Master using the command ' ssh nagarjuna@nagarjuna-Aspire-4736 ' in the Slave Machine.


Troubleshooting :

- If you are unable to connect to master machine. Follow below steps
1) The above process will be successed only when domain is registered with an IP address.
2) Otherwise edit the public key - meaning - at the end of the public key, we will see domainname like
nagarjuna@nagarjuna-Aspire-4736.  Here you have to replace nagarjuna-Aspire-4736 with the IP address of Master machine.
3) Now try to connect.

If you want to know the IP address of Master machine, use the command ' ifconfig ' , You will IP.


If you still facing problems while connecting, then try to restart ssh server service in both Machines using
sudo /etc/init.d/ssh restart


sources:
https://help.ubuntu.com/10.04/serverguide/openssh-server.html
http://www.cyberciti.biz/faq/howto-start-stop-ssh-server/



Tuesday, October 8, 2013

All about premitive and characters...conversions...etc ************************

The Low level  discussion of primitive data types and Representations :


byte notation   bit notation                                                        combinations            range

1byte    = =      8bit    = =    pow(2,8)                                            256                -128 to +127
2byte    = =      16bit  = =    pow(2,8)*pow(2,8)                           65536          -32,768 to +32,767
4byte    = =      32bit  = =    pow(2,8)*pow(2,8)*pow(2,8)             xxxxxxx           xxxxxxxxxxxxxx
8byte    = =      64bit  = =    pow(2,8)*pow(2,8)*pow(2,8)*pow(2,8)  xxx              xxxxxxxxxxxxx


In java primitive

byte  - The byte data type is an 8-bit signed two's complement integer.
short - The short data type is a 16-bit signed two's complement integer.
int    -  The int data type is a 32-bit signed two's complement integer.
long - The long data type is a 64-bit signed two's complement integer.

float - The float data type is a single-precision 32-bit IEEE 754 floating point.
double - The double data type is a double-precision 64-bit IEEE 754 floating point.

char - The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000'  (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

here char is of 16 bit unicode so it's data representation will be in the form of hexadecimal like /uffff


here hexadecimal start with '0' and ends with 'f'

so numberin will be like below

0    - 0
1    - 1
2    - 2
3    - 3
4    - 4
5    - 5
6    - 6
7    - 7
8    - 8
9    - 9
10  -A
11  -B
12  -C
13  -D
14  -E
15  -F

TOTAL numbers from 0 to 15 are 16, means base 16.

char clarification :
    Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as ' \u0061' ( Latin small letter A)

below code will give you clarity

code snippet:
char i= '\u0061';
char j= 97;
char k= 'a';

System.out.println(i);
System.out.println((int)i);
System.out.println((char)i);
System.out.println(j);
System.out.println((int)j);
System.out.println((char)j);
System.out.println(k);
System.out.println((int)k);
System.out.println((char)k);

output:
a
97
a
a
97
a
a
97
a



Value conversions: 

From the above code, let us discuss on char 'a'

\u0061  -  it is in hexa decimal notation  -- 16bit -- 2byte -- pow(2,8)*pow(2,8) -- combinations of 16 bits in binary representation.

0000000001100001   is the Binary representation of character 'a' ( total 16bits)  use this link1 or link2 to calculate the value of this binary code.

convert it into decimal like this

0*pow(16,3)+0*pow(16,2)+6*pow(16,1)+1*pow(16,0) =  0+0+6*16+1*1 = 0+0+96+1 =  97 

So, 97 is the decimal notation of character 'a'.


..
..
..
..
To be continued.......


sources:
http://www.binaryhexconverter.com/decimal-to-binary-converter
http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html
http://en.wikipedia.org/wiki/List_of_Unicode_characters
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
http://docs.oracle.com/javase/tutorial/i18n/text/string.html ****



Binary String to Integer conversion ..

Convert a Binary string to Integer...

code snippet:

method 1 :-
import java.util.*;

public class BinaryToInt{


public static void main(String nag[]){

Scanner console= new Scanner(System.in);

System.out.println("enter any binary number:");

String binaryString=console.next().trim();

System.out.println("int representation of the given binary is:"+binaryToInt(binaryString));


}


private static  int binaryToInt(String numberString){
int result=0;

int numberStringLength=numberString.length();
char[] binaryCharArray=new char[numberStringLength];

for(int i=0;i<numberStringLength;i++){
binaryCharArray[i]=numberString.charAt(i);
}

int[] binaryIntArray=convertBinaryCharArrayToBinaryIntArray(binaryCharArray);

result= calculateBinary(binaryIntArray);

return result;
}

private static int[] convertBinaryCharArrayToBinaryIntArray(char[] charArray){

int arrayLength=charArray.length;
int[] intArray=new int[arrayLength];

for(int i=0;i<arrayLength;i++){

if((int)charArray[i]==48){
intArray[i]=0;
}
if((int)charArray[i]==49){
intArray[i]=1;

}
}
return intArray;
}

private static  int calculateBinary(int[] binaryIntArray){

int value=0;
int arrayLength=binaryIntArray.length;


for(int i=0;i<arrayLength;i++){

value=value+binaryIntArray[i]*pow(2,(arrayLength-1)-i);

}

return value;
}

public static  int pow(int value, int power){

int v=1;
for(int i=0; i<power;i++){

// System.out.println("loop:"+(i-1));
v=v*value;
}
return v;
}
}//end class

method 2 :-
Use    Integer.parseInt(String str, int num);  directly

Wednesday, October 2, 2013

java interview questions today links ... ********************



9.5/10
--------
http://servlets.javabook.org/

http://www.javabook.org/

http://jsp.javabook.org/

http://jdbc.javabook.org/

http://hibernate.javabook.org/

http://spring.javabook.org/

http://struts.javabook.org/

http://basicunix.javabook.org/


10/10
---------
http://howtodoinjava.com/

Monday, September 23, 2013

How to convert an Array to a List object?

converting an Array to List: 

The below code shows you how to convert an Array to List object

code snippet:
 
        String[] str=new String[2];
        str[0]="nagarjuna";
        str[1]="kalyan";
       
        List<String> lstr=Arrays.asList(str);
       
        for(String s:lstr){
            System.out.println(s);
        }//end


The resultant is the List<String> type object, And the object 'lstr' is an implementation is of ArrayList type.
But this ArrayList is not expected ArrayList that availables in java.util.ArrayList.

This ArrayList is a private inner class in Arrays class.

If we observe the below code snippet, we can understand what is going in the back ground.

code snippet:
        System.out.println(lstr instanceof java.util.ArrayList);
        System.out.println(lstr.getClass().getName());//end

If we run the above code, we get the output like

o/p:
false
java.util.Arrays$ArrayList


So the implementation of the List is of type ArrayList which is available in the package java.util.Arrays$ArrayList



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



Difference between Sorted and Ordered collections ?


Generally we have Collection implementations like ArrayList, Vector, HashSet...etc.

But we have four kind of collections ...

1) Ordered Collection
2) UnOrdered Collection
3) Sorted Collection
4) UnSorted Collection

If we know what is Ordered and Sorted collection, We can understand all the above 4 collections.

Ordered Collection:
  When a Collection is ordered, It means you can iterate through the collection in a specific (not-random) order.
- A HashTable collection is not ordered.
- An ArrayList keeps the order established by the element's index position.
- LinkedHashSet keeps the order established by insertion, so the last element inserted is the last element in the LinkedHashSet.
- Some collections that keep an order referred to as the natural order of the elements, and those collections are then not just ordered, but also sorted.

collection implementations order properties:
TreeMap - Sorted
LinkedHashMap - By insertion order or  last access order.
TreeSet - Sorted
LinkedHashSet - By insertion order
ArrayList - By index
Vector - By index
LinkedList - By index



Sorted Collection:
The order in the collection is determined according to some rule or rules, known as the sort order.

Sorting is done based on properties will figure out what order to put them in, based on the sort order.
Most commonly, the sort order used is something called the natural order.

collection implementations order properties:
TreeMap - By natural order or custom comparison rules
TreeSet - By natural order or custom comparison rules

Sunday, September 22, 2013

What is Singleton and Usage of It? and How to use System.gc() and Runtime.gc() ( Garbage Collection) ?

Hi All,

In this post, I am going to show you Two examples

1 - Example program for limiting objects creation using factory method style    (Singleton).
2 - Usage of System.gc() using the above example.


1) Limiting Object's creation: (requirement is creation of objects to a class is 7 only)

ObjectFactory7.java:

package com.nagarjuna.core.singletons;

public class ObjectFactory7 {

    private static int objcount = 0;

    private ObjectFactory7() {

    }

    public static ObjectFactory7 getInsance() throws ObjectCreationException {

        ObjectFactory7 obj = null;
        //
        if (objcount < 7) {
            obj = new ObjectFactory7();
            objcount++;
        } else {
            throw new ObjectCreationException();
        }
        return obj;
    }

    @Override
    protected void finalize() throws Throwable {// decrease the count of objcount for
                                                // Garbage Collection of each
                                                // object
        objcount--;
    }

    public static void showNumberOfObjects() {
        System.out.println("no of objects created from this factory are :"+ objcount);
    }

}//end class


ObjectCreationException.java:
package com.nagarjuna.core.singletons;

public class ObjectCreationException extends Exception {

    @Override
    public void printStackTrace() {
        System.out.println("Object creation exception occured, Creation of objects is limited to sevev (7) only..");
    }

}//end class

ObjCreationTest.java
package com.nagarjuna.core.singletons;

public class ObjCreationTest {

    public static void main(String[] args) {

        ObjectFactory7 o1, o2, o3, o4, o5, o6, o7, o8;

        try {

            ObjectFactory7.showNumberOfObjects();
            //
            o1 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o2 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o3 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o4 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o5 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o6 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o7 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            System.out.println("-----------------------------------------------");
            //
            o1 = null;

            ObjectFactory7.showNumberOfObjects();
            //
            o8 = ObjectFactory7.getInsance();//trying to create 8th object
            ObjectFactory7.showNumberOfObjects();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}//end class

If we try to run the above code we get an exception at 8th object creation code. we made o1 unreachable (null) and must be garbage collected.

output:
no of objects created from this factory are :0
no of objects created from this factory are :1
no of objects created from this factory are :2
no of objects created from this factory are :3
no of objects created from this factory are :4
no of objects created from this factory are :5
no of objects created from this factory are :6
no of objects created from this factory are :7
-----------------------------------------------
no of objects created from this factory are :7
Object creation exception occured, Creation of objects is limited to seven (7) only..

___________________________________________________________________________________________

The above code is an example for both Singleton and Limit Objects creation.





2) Usage of System.gc() :

ObjCreationTest.java:


package com.nagarjuna.core.singletons;

public class ObjCreationTest {

    public static void main(String[] args) {

        ObjectFactory7 o1, o2, o3, o4, o5, o6, o7, o8;

        try {

            ObjectFactory7.showNumberOfObjects();
            //
            o1 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o2 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o3 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o4 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o5 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o6 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o7 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            System.out.println("-----------------------------------------------");
            //
            o1 = null;
            // System.gc();
            Thread.sleep(500);
            ObjectFactory7.showNumberOfObjects();
            //
            o8 = ObjectFactory7.getInsance();//trying to create 8th object
            ObjectFactory7.showNumberOfObjects();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}//end class

When we try to run the above code, exception will be raised.

If we observe the above code in ObjectFactory7.java, It has finalize() method and by using this method we can decrease the count of objcount.

But we will get an exception, It means Garbage Collector is not guaranteed for garbage collection, and also we can't force the GC to collect the unreachable object.

But we can ask the GC to collect the unreachable object to be garbage collected by adding code System.gc() after below statement.

o1 = null;


Now try to run the above code with out Thread.sleep(500), Still we get the same exception. It means Calling System.gc() is also useless.

Since GC is a daemon service with the thread priority of 5 and runs in the background, But when we try to execute System.gc(), the GC will try to remove the memory of the unreachable object after some time ( must give some amount of time like  Thread.sleep(10) or (1) also). The GC will work perfectly.

Now  uncomment System.gc(), also keep Thread.sleep(500) and then run the code.
You won't get the exception and the count also decreases and the new object creation code also will be executed successfully.

Try it once.

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