Gadgets

Thursday, 21 January 2016

Explain about Vector with an example

1. Heterogeneous Objects are allowed.
2. Insertion order is preserved.
3. Duplicate Objects are allowed.
4. Null insertion is possible.
5. Underlying data structure is Resizable Array or Growable Array.
6. Vector class implements RandomAccess, Serializable and Cloneable interfaces.
7. Best choice for retrieval operation.
8. Every method present inside Vector is synchronized.
9. At a time one thread only allowed and it is thread safe.
10. Relatively performance wise is low because threads are required to wait. 
import java.util.*;
public class VectorDemo {
               public static void main(String[] arg) {                  
                               Vector v=new Vector();
                               v.add("a");
                               v.add(10);
                               v.add(null);//null insertion
                               v.add("a");//duplicate insertion
                               System.out.println(v);//[a, 10, null, a]
                               v.addElement("b");
                               v.removeElementAt(3);//remove element at v[3]
                               v.add(1,"n");//add v[1]=n
                               System.out.println(v);//[a, n, 10, null, b]
                               System.out.println(v.firstElement());//v[0]=a
                               System.out.println(v.lastElement());//v[4]=b
                               System.out.println(v.elementAt(1));//v[1]=n
               }              
}

Explain about LinkedList with an example program

1. Heterogeneous Objects are allowed.
2. Insertion order is preserved.
3. Duplicate Objects are allowed.
4. Null insertion is possible.
5. Underlying data structure is DoubleLinkedList.
6. LinkedList class implements Serializable and Cloneable interfaces.
7. Best choice for insertion and deletion operation.
import java.util.*;
public class LinkedListDemo {
               public static void main(String[] arg) {                  
                               LinkedList l=new LinkedList();
                               l.add("n");
                               l.add("a"); //char insertion
                               l.add(12); //int insertion
                               l.add("r");
                               l.add("e");
                               l.add(14);
                               l.add("n"); //duplicate insertion
                               l.add(null); //null insertion
                               System.out.println(l); //[n, a, 12, r, e, 14, n, null]
                               l.remove(2); //remove l[2]
                               System.out.println(l); //[n, a, r, e, 14, n, null]
                               l.add(2,10); //add l[2]=10
                               System.out.println(l); //[n, a, 10, r, e, 14, n, null]
                               l.addFirst("A"); //add element at first
                               l.removeLast(); //remove last element
                               System.out.println(l); //[A, n, a, 10, r, e, 14, n]
               }             
}

Explain about ArrayList with an example program

1. ArrayList allow Hetrogeneous data elements.
2. Underlying Data Structure is Resizable Array or Growable Array.
3. ArrayList can hold object types only.
      ArrayList al=new ArrayList();
      al.add(10); // allow integer
      al.add(“A”); //allow string
4. Null insertion is possible.
5. Duplicates are allowed.
import java.util.*;
public class ArrayListDemo  {
               public static void main(String[] arg)  {                
                               ArrayList l=new ArrayList();
                               l.add("n");
                               l.add("a"); //char insertion
                               l.add(12); //int insertion
                               l.add("r");
                               l.add("e");
                               l.add(14);
                               l.add("n"); //duplicate insertion
                               l.add(null); //null insertion
                               System.out.println(l); //[n, a, 12, r, e, 14, n, null]
                               l.remove(2); //remove l[2]
                               System.out.println(l); //[n, a, r, e, 14, n, null]
                               l.add(2,10); //add l[2]=10
                               System.out.println(l); //[n, a, 10, r, e, 14, n, null]
               }             
}


Sunday, 20 December 2015

Difference between String,StringBuffer, and StringBuilder

Difference between String and StringBuffer ?
====================================
=>String is Immutable (non changeable) and StringBuffer is Mutable (changeable)
=>String:-
=========
Once we create a String Object then we can’t perform any changes on that Object. If we are trying to perform any changes on that Object, then it will create a new Object
String s=new String("java");
s.concat("technology");
Output:- java
We can't perform concat operation on same object "s". 
------------------------------------------------------------------------------------
String s=new String("java");
String s1=s.concat("technology");
Output:- output is "javatechnology" and it store in new String Object "s1". But we can't perform concat operation on same object "s". 
=>StringBuffer:-
==============
Once we create a StringBuffer Object then we can perform any changes on that Object.
StringBuffer sb=new StringBuffer("java");
sb.append("technology");
Output:- javatechnology

public class Test {
   public static void main(String arg[])
   {
   String s=new String("java");
   s.concat("technology");
   System.out.println("String..."+s);
  
   StringBuffer sb=new StringBuffer("java");
   sb.append("technology");
   System.out.println("StringBuffer..."+sb);
   }
}
/*
Output:
String...java
StringBuffer...javatechnology
*/
Difference between StringBuffer and StringBuilder ?
StringBuffer:-
===========
=>It is synchronized i.e. thread safe. That mean two threads can’t perform operations on StringBuffer simultaneously.
StringBuilder:-
=============
=>StringBuilder is same like StringBuffer, but the difference is StringBuilder is non synchronized i.e, not thread safe. so two threads can perform operations on StringBuilder simultaneously.

public class Test {
   public static void main(String arg[])
   {
       StringBuffer sb=new StringBuffer("java");
       long time=System.currentTimeMillis();
       for(int i=0;i<=10000;i++)
       {
       sb.append("tech");
       }
       System.out.println("if synchronized time taken..."+(System.currentTimeMillis()-time)+"ms");
      
       StringBuilder s=new StringBuilder("java");
       time=System.currentTimeMillis();
        for(int i=0;i<=10000;i++)
       {
       s.append("tech");
       }
       System.out.println("if non-synchronized time taken..."+(System.currentTimeMillis()-time)+"ms");
      
   }
}
/*
Output:
if synchronized time taken...4ms
if non-synchronized time taken...1ms

*/

Thursday, 17 December 2015

Can we access private constructor in other package

How to access private constructor in other package:
Yes we can access by using reflection classes, we can create instance for private constructors.
To get the class.
Class c=Class.forName("test.Test");
To get all the constructors (public, protected, default, private) in the form of array from the class
Constructor con[]=c.getDeclaredConstructors();
con[0] is indicates first constructor, con[1] indicates second constructor and so an
if setAccessible(true) then all the constructors make as public
if setAccessible(false) then we can’t access all the constructors, we access only public constructors(depending on access specifier rules).
To create object for the class
con[0].newInstance(); 
Test.java
========
package test;
public class Test {
               private Test()
               {
                               System.out.println("private constructor...");                              
               }              
}
Client.java
=========
package core;
import java.lang.reflect.Constructor;
public class Client {
               public static void main(String[] arg)
               {
                               try{
                                              //to get the class
                                              Class c=Class.forName("test.Test");
                                              //to access all the constructors in the array form from the class
                                              Constructor con[]=c.getDeclaredConstructors();
                                              //to make constructor as public
                                              con[0].setAccessible(true);
                                              //to create object
                                              con[0].newInstance();
                               }catch(Exception ex){}
               }
}
/*
Output:
private constructor...
*/

Wednesday, 16 December 2015

First Spring application

Example of spring application
Creating first spring application in eclipse, here we have clear steps to create spring application
1. Create the java project
2. Add spring capabilities
3. Create the class file(POJO class)
4. Create the xml file
5. Create the Driver class
Create New Project:
Go to File menu - New - project - Java Project. Write the Project name and click Finish
Add Spring jar files:
Right click on project – Build Path – configure Build Path – select Libraries tab – Add External JARs


Create POJO class:
Test.java
=======
package test;
public class  Test
{
               public void hello()
               {
                               System.out.println("My first Spring Project");
               }
}

Create xml File:
Open org.springframework.beans-3.0.1.RELEASE-A.jar file with winJAR archiver
 and open folder org\springframework\beans\factory\xml
 in xml folder open spring-beans.dtd file
 in spring-beans.dtd file copy line 35 - 37 below code
 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">




spring.xml
========
package resources;
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="test.Test" id="t">
</bean>
</beans>
Create Driver Class:
Client.java
========
package test;
class Client{
               public static void main(String[] args)
               {
                               //find xml file
                              Resource r=new ClassPathResource("resources/spring.xml");
                               //load xml file into container
                               BeanFactory factory=new XmlBeanFactory(r);
                               //creat test class object
                               Object o=factory.getBean("t");
                               //type casting object
                               Test t=(Test)o;
                               t.hello();
               }
}
/*
Output:
My first Spring Project
*/



Monday, 14 December 2015

Check the given string is palindrome or not

Check the given string is palindrome or not:
If we reverse a string that reverse string and original string both are equal then that string is palindrome.
Example:
Original string: java
Reverse string: avaj
Both are not equal so not palindrome.
Original string: madam
Reverse string: madam
Both are equal so palindrome.
length():- length() is final method, it is applicable for String Objects. length() method returns number of characters present in the String.
chatAt() method:-
Returns the char value at the specified index. An index ranges from 0 to length()-1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
import java.util.Scanner;
public class PalindromeTest {
    public static void main(String[] arg){
        String name,rev="";
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Name :");
        name=sc.nextLine();        
        System.out.println("length of the String : "+name.length());
        int i=name.length();//i=string length
        for(int j=i-1;j>=0;j--){
           rev=rev+name.charAt(j);
        }
        System.out.println("reverse string is : "+rev);     
    }
}
/*
Output:-
Enter Name :
java
length of the String : 4
reverse string is : avaj
*/
import java.util.Scanner;
public class PalindromeTest {
    public static void main(String[] arg){
        String name,rev="";
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Name :");
        name=sc.nextLine();        
        System.out.println("length of the String : "+name.length());
        int i=name.length();//i=string length
        for(int j=i-1;j>=0;j--){
           rev=rev+name.charAt(j);
        }
        System.out.println("reverse string is : "+rev);
        if(name.equals(rev)){
            /* check given string and reverse string are equal or not*/
          System.out.println("palindrome ");  
        }
        else{
            System.out.println("not palindrome ");  
        }
    }
}
/*
Output-1:-
Enter Name :
java
length of the String : 4
reverse string is : avaj
not palindrome 
Output-2:-
Enter Name :
madam
length of the String : 5
reverse string is : madam
palindrome
*/