AdSense

AdSense3

Wednesday, 30 September 2015

Basic of Android-2

Q.1 Explain in brief about the important file and folder when you create new android application.

When you create android application the following folders are created in the package explorer in eclipse which are as follows:
src: Contains the .java source files for your project. You write the code for your application in this file. This file is available under the package name for your project.
gen —This folder contains the R.java file. It is compiler-generated file that references all the resources found in your project. You should not modify this file.
Android 4.0 library: This folder contains android.jar file, which contains all the class libraries needed for an Android application.
assets: This folder contains all the information about HTML file, text files, databases, etc.
bin: It contains the .apk file (Android Package) that is generated by the ADT during the build process. An .apk file is the application binary file. It contains everything needed to run an Android application.
res: This folder contains all the resource file that is used byandroid application. It contains subfolders as: drawable, menu, layout, and values etc.

Explain AndroidManifest.xmlfile in detail.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.careerride" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
<activity android:name="com.example.careerride.MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
The AndroidManifest.xml file contains the following information about the application:
  • It contains the package name of the application.
  • The version code of the application is 1.This value is used to identify the version number of your application.
  • The version name of the application is 1.0
  • The android:minSdkVersion attribute of the element defines the minimum version of the OS on which the application will run.
  • ic_launcher.png is the default image that located in the drawable folders.
  • app_name defines the name of applicationand available in the strings.xml file.
  • It also contains the information about the activity. Its name is same as the application name.

Describe android Activities in brief.

Activity provides the user interface. When you create an android application in eclipse through the wizard it asks you the name of the activity. Default name is MainActivity. You can provide any name according to the need. Basically it is a class (MainActivity) that is inherited automatically from Activity class. Mostly, applications have oneor more activities; and the main purpose of an activity is to interact with the user. Activity goes through a numberof stages, known as an activity’s life cycle.
Example:
packagecom.example.careerride; //Application name careerride

importandroid.os.Bundle; // Default packages
importandroid.app.Activity; // Default packages
importandroid.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
When you run the application onCreate method is called automatically.

Describe Intents in detail.

An Android application can contain zero or more activities. If you want to navigate fromone activity to another then android provides you Intent class. This class is available inandroid.content.Intent package.One of the most common uses for Intents is to start new activities.
There are two types of Intents.
Explicit Intents
Implicit Intents
Intents works in pairs: actionand data. The action defines what you want to do, such as editing an item, viewingthe content of an item etc. The dataspecifies what is affected,such as a person in the Contacts database. The data is specified as anUri object.
Explicitly starting an Activity
Intent intent = newIntent (this, SecondActivity.class);
startActivity(intent);
Here SecondActivity is the name of the target activity that you want to start.
Implicitly starting an Activity
If you want to view a web page with the specified URL then you can use this procedure.
Intent i = newIntent(android.content.Intent.ACTION_VIEW,Uri.parse(“http://www.amazon.com”));
startActivity(i);
if you want to dial a telephone number then you can use this method by passing the telephone number in the data portion
Intent i = newIntent (android.content.Intent.ACTION_DIAL,Uri.parse(“tel:+9923.....”));
startActivity(i);
In the above method the user must press the dial button to dial the number. If you want to directly call the number without user intervention, change the action as follows:
Intent i = newIntent (android.content.Intent.ACTION_CALL,Uri.parse(“tel:+9923.....”));
startActivity(i);
If you want to dial tel no or use internet then write these line in AndroidManifest.xml
<uses-permissionandroid:name=”android.permission.CALL_PHONE”/>
<uses-permissionandroid:name=”android.permission.INTERNET”/>

How to send SMS in android? Explain with example.

SMS messaging is one of the basic and important applications on a mobile phone. Now days every mobile phone has SMS messaging capabilities, and nearly all users of any age know how to send and receive suchmessages. Mobile phones come with a built-in SMS application that enables you to send and receiveSMS messages. If you want to send the SMS programmatically then follow the following steps.
Sending SMS Messages Programmatically
Take a button on activity_main.xml file as follows.
<Button android:id="@+id/btnSendSMS" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick=”sendmySMS” android:text="sendSMS" />
According to above code when user clicks the button sendmySMS method will be called. sendmySMS is user defined method.
In the AndroidManifest.xml file, add the following statements
<uses-permissionandroid:name=”android.permission.SEND_SMS”/>
Now we write the final step. Write the given below method in MainActivity,java file
publicvoidsendmySMS(View v)
{
SmsManagersms = SmsManager.getDefault();
sms.sendTextMessage("5556", null, "Hello from careerRide", null, null);
}
In this example I have used two emulator. On the first Android emulator (5554), click the Send SMSbutton to send an SMS message to the second emulator(5556).

Describe the SmsManager class in android.

SmsManager class is responsible for sending SMS from one emulator to another or device.
You cannot directly instantiate this class; instead, you call the getDefault() static method to obtain an SmsManager object. You then send the SMS message using the sendTextMessage() method:
SmsManagersms = SmsManager.getDefault();
sms.sendTextMessage("5556", null, "Hello from careerRide", null, null);
sendTextMessage() method takes five argument.
  • destinationAddress — Phone number of the recipient.
  • scAddress — Service center address; you can use null also.
  • text — Content of the SMS message that you want to send.
  • sentIntent — Pending intent to invoke when the message is sent.
  • deliveryIntent — Pending intent to invoke when the message has been delivered.

How you can use built-in Messaging within your application?

You can use an Intent object to activate the built-in Messaging service. You have to pass MIME type “vnd.android-dir/mms-sms”, in setType method of Intent as shown in the following given below code.
Intent intent = new Intent (android.content.Intent.ACTION_VIEW);
intent.putExtra("address", "5556; 5558;");// Send the message to multiple recipient.
itent.putExtra("sms_body", "Hello my friends!");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
What are different data storage options are available in Android?
Different data storage options are available in Android are:
  • SharedPreferences
  • SQlite
  • ContentProvider
  • File Storage
  • Cloud Storage

Describe SharedPreference storage option with example.

SharedPreference is the simplest mechanism to store the data in android. You do not worry about creating the file or using files API.It stores the data in XML files. SharedPreference stores the data in key value pair.The SharedPreferences class allows you to save and retrieve key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: boolean, floats, int, longs, and strings.The data is stored in XML file in the directory data/data//shared-prefs folder.
Application of SharedPreference
  • Storing the information about number of visitors (counter).
  • Storing the date and time (when your Application is updated).
  • Storing the username and password.
  • Storing the user settings.
Example:
For storing the data we will write the following code in main activity on save button:
SharedPreferences sf=getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editored= sf.edit();
ed.putString("name", txtusername.getText().toString());
ed.putString("pass", txtpassword.getText().toString());
ed.commit();
In this example I have taken two activities. The first is MainActivity and the second one is SecondActivity.When user click on save button the user name and password that you have entered in textboxes, will be stored in MyData.xml file.
Here MyData is the name of XML file .It will be created automatically for you.

MODE_PRIVATE means this file is used by your application only.
txtusernameand txtpassword are two EditText control in MainActivity.
For retrieving the data we will write the following code in SecondActiviy when user click on Load button:
Public static final String DEFAULT=”N? A”;
DEFAULT is a String type user defined global variable.If the data is not saved in XML file and user click on load button then your application will not give the error. It will show message “No Data is found”. Here name and pass are same variable that I have used in MainActivity.
SharedPreferences sf=getSharedPreferences("MyData", Context.MODE_PRIVATE);
String Uname=sf.getString("name", DEFAULT);
String UPass=sf.getString("pass", DEFAULT);
if(name.equals(DEFAULT)||Pass.equals(DEFAULT))
{
Toast.makeText(this, "No data is found", Toast.LENGTH_LONG).show();
}
else
{
Txtusername.setText(Uname);
Txtpassword.setText(UPass) ;
}

Tuesday, 29 September 2015

Basic of Android-1

1. What is meaning of Android Word?
it means a robot with a human appearance.

2. What is Android?
an open-source operating system used for smartphones and tablet computers.

3. Inventors of android ?
Andy Rubin, Rich Miner, Nick Sears

4. Android versions history and there name?

Code nameVersionAPI level
Lollipop5.0API level 21
KitKat4.4 - 4.4.4API level 19
Jelly Bean4.3.xAPI level 18
Jelly Bean4.2.xAPI level 17
Jelly Bean4.1.xAPI level 16
Ice Cream Sandwich4.0.3 - 4.0.4API level 15, NDK 8
Ice Cream Sandwich4.0.1 - 4.0.2API level 14, NDK 7
Honeycomb3.2.xAPI level 13
Honeycomb3.1API level 12, NDK 6
Honeycomb3.0API level 11
Gingerbread2.3.3 - 2.3.7API level 10
Gingerbread2.3 - 2.3.2API level 9, NDK 5
Froyo2.2.xAPI level 8, NDK 4
Eclair2.1API level 7, NDK 3
Eclair2.0.1API level 6
Eclair2.0API level 5
Donut1.6API level 4, NDK 2
Cupcake1.5API level 3, NDK 1
(no code name)1.1API level 2
(no code name)1.0API level 1

5. Features of Android OS?
Most of us are aware of features like 
Live wallpaper
Camera
Messaging
Bluetooth
WIFI
Web Browsing
Music
Alarm etc. etc….

6. Advance Features of Android OS?
Google now (voice assistant)
NFC (Near Field Communication)
Unlock your phone by your face
Use your phone with joystick to enjoy gaming experience
Connect your phone with LED TV via MHL or micro HDMI cable
Screen Capture
Multitasking Future (Task Switcher)
Data Usages (Check and also set limit from device)

7. Tools Required for Developing Android Apps?  
JDK
Eclipse + ADT plugin
SDK Tools.

You can also use Android Studio by Google.

8. ADT stand for?
Android Developer Tools

9. SDK stand for ?
Software Development Kit

10. Advantages of android?
Open-source
Platform-independent
Supports various technologies (having number of native application like: camera, bluetooth, wifi, speech, EDGE)

11. Language Know to develop android apps?
Java
XML

12. Android application main components are?
ComponentsDescription
ActivitiesThey dictate the UI and handle the user interaction to the smartphone screen
ServicesThey handle background processing associated with an application.
Broadcast ReceiversThey handle communication between Android OS and applications.
Content ProvidersThey handle data and database management issues.

13. What is Activities?
An activity is a single, focused thing that the user can do. when ever user click on GUI the next Activity will be start and new GUI set base on coding.

14. What is Intent?
An Intent is exactly what it describes. It's an "intention" to do an action.

An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly.

There are two types of intents in android:

  • Implicit Intent
  • Explicit Intent

15. How to Start Another Activity?
Intent i = new Intent(getApplicationContext(), Activity2.class); 
startActivity(i);

16. Explain Folder, File & Description of Android Apps?
src: This contains the .java source files for your project.

gen: contains the .R file, a compiler-generated file that references all the resources found in your project. You should not modify this file.

bin: contains the Android package files .apk built by the ADT during the build process and everything else needed to run an Android application.

res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density screens.

res/layout
This is a directory for files that define your app's user interface.

res/values
This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions.

AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of the app and defines each of its components.

17. What is AVD?
AVD Stand for Android Virtual Device (emulator), The Android SDK includes a mobile device emulator - a virtual mobile device that runs on your computer

Monday, 28 September 2015

Implement merge sort in java.

Merge sort is a divide and conquer algorithm.

Steps to implement Merge Sort:

1) Divide the unsorted array into n partitions, each partition contains 1 element. Here the one
 element is considered as sorted.
2) Repeatedly merge partitioned units to produce new sublists until there is only 1 sublist 
remaining. This will be the sorted list at the end.
Merge Sort

Merge sort is a fast, stable sorting routine with guaranteed O(n*log(n)) efficiency. 
When sorting arrays, merge sort requires additional scratch space proportional to 
the size of the input array. Merge sort is relatively simple to code and offers performance 
typically only slightly below that of quicksort.

package com.kundan;

public class MergeSort {
 
 private int[] array;
 private int[] tempMergArr;
 private int length;

 public static void main(String a[]){
  
  int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
  MergeSort ms = new MergeSort();
  ms.sort(inputArr);
  for(int i:inputArr){
      System.out.print(i);
      System.out.print(" ");
     }
 }
 
 public void sort(int inputArr[]) {
  this.array = inputArr;
  this.length = inputArr.length;
  this.tempMergArr = new int[length];
  doMergeSort(0, length - 1);
 }

 private void doMergeSort(int lowerIndex, int higherIndex) {
  
  if (lowerIndex < higherIndex) {
   int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
   // Below step sorts the left side of the array
   doMergeSort(lowerIndex, middle);
   // Below step sorts the right side of the array
   doMergeSort(middle + 1, higherIndex);
   // Now merge both sides
   mergeParts(lowerIndex, middle, higherIndex);
  }
 }

 private void mergeParts(int lowerIndex, int middle, int higherIndex) {

  for (int i = lowerIndex; i <= higherIndex; i++) {
   tempMergArr[i] = array[i];
  }
  int i = lowerIndex;
  int j = middle + 1;
  int k = lowerIndex;
  while (i <= middle && j <= higherIndex) {
   if (tempMergArr[i] <= tempMergArr[j]) {
    array[k] = tempMergArr[i];
    i++;
   } else {
    array[k] = tempMergArr[j];
    j++;
   }
   k++;
  }
  while (i <= middle) {
   array[k] = tempMergArr[i];
   k++;
   i++;
  }

 }
}

Output:
4 11 23 28 43 45 65 77 89 98 

Saturday, 26 September 2015

Implement quick sort in java.


Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide
 and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: 
the low elements and the high elements. Quicksort can then recursively sort the sub-lists.
Steps to implement Quick sort:

1) Choose an element, called pivot, from the list. Generally pivot can be the middle index element.
2) Reorder the list so that all elements with values less than the pivot come before the pivot, 
while all elements with values greater than the pivot come after it (equal values can go either way).
 After this partitioning, the pivot is in its final position. This is called the partition operation.
3) Recursively apply the above steps to the sub-list of elements with smaller values and 
separately the sub-list of elements with greater values.

Quick Sort

The complexity of quick sort in the average case is Θ(n log(n)) and in the worst case is Θ(n2).

package com.kundan;

public class MyQuickSort {
 
 private int array[];
 private int length;

 public void sort(int[] inputArr) {
  
  if (inputArr == null || inputArr.length == 0) {
   return;
  }
  this.array = inputArr;
  length = inputArr.length;
  quickSort(0, length - 1);
 }

 private void quickSort(int lowerIndex, int higherIndex) {
  
  int i = lowerIndex;
  int j = higherIndex;
  // calculate pivot number, I am taking pivot as middle index number
  int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
  // Divide into two arrays
  while (i <= j) {
   /**
    * In each iteration, we will identify a number from left side which 
    * is greater then the pivot value, and also we will identify a number 
    * from right side which is less then the pivot value. Once the search 
    * is done, then we exchange both numbers.
    */
   while (array[i] < pivot) {
    i++;
   }
   while (array[j] > pivot) {
    j--;
   }
   if (i <= j) {
    exchangeNumbers(i, j);
    //move index to next position on both sides
    i++;
    j--;
   }
  }
  // call quickSort() method recursively
  if (lowerIndex < j)
   quickSort(lowerIndex, j);
  if (i < higherIndex)
   quickSort(i, higherIndex);
 }

 private void exchangeNumbers(int i, int j) {
  int temp = array[i];
  array[i] = array[j];
  array[j] = temp;
 }
 
 public static void main(String a[]){
  
  MyQuickSort sorter = new MyQuickSort();
     int[] input = {24,2,45,20,56,75,2,56,99,53,12};
     sorter.sort(input);
     for(int i:input){
      System.out.print(i);
      System.out.print(" ");
     }
 }
}

Output:
2 2 12 20 24 45 53 56 56 75 99

Thursday, 24 September 2015

Implement insertion sort in java.

Insertion sort is a simple sorting algorithm, it builds the final sorted array one item at a time. 
It is much less efficient on large lists than other sort algorithms.

Advantages of Insertion Sort:

1) It is very simple.
2) It is very efficient for small data sets.
3) It is stable; i.e., it does not change the relative order of elements with equal keys.
4) In-place; i.e., only requires a constant amount O(1) of additional memory space.

Insertion sort iterates through the list by consuming one input element at each repetition,
 and growing a sorted output list. On a repetition, insertion sort removes one element 
from the input data, finds the location it belongs within the sorted list, and inserts it there. 
It repeats until no input elements remain.

Insertion Sort

The best case input is an array that is already sorted. In this case insertion sort has a linear 
running time (i.e., Θ(n)). During each iteration, the first remaining element of the input is
 only compared with the right-most element of the sorted subsection of the array. The 
simplest worst case input is an array sorted in reverse order. The set of all worst case 
inputs consists of all arrays where each element is the smallest or second-smallest of the
 elements before it. In these cases every iteration of the inner loop will scan and shift
 the entire sorted subsection of the array before inserting the next element. This gives
 insertion sort a quadratic running time (i.e., O(n2)). The average case is also quadratic,
 which makes insertion sort impractical for sorting large arrays. However, insertion sort 
is one of the fastest algorithms for sorting very small arrays, even faster than quicksort; indeed,
 good quicksort implementations use insertion sort for arrays smaller than a certain threshold,
 also when arising as subproblems; the exact threshold must be determined experimentally 
and depends on the machine, but is commonly around ten.

package com.kundan;

public class MyInsertionSort {

 public static void main(String a[]){
  int[] arr1 = {10,34,2,56,7,67,88,42};
  int[] arr2 = doInsertionSort(arr1);
  for(int i:arr2){
   System.out.print(i);
   System.out.print(", ");
  }
 }
 
 public static int[] doInsertionSort(int[] input){
  
     int temp;
     for (int i = 1; i < input.length; i++) {
      for(int j = i ; j > 0 ; j--){
       if(input[j] < input[j-1]){
        temp = input[j];
        input[j] = input[j-1];
        input[j-1] = temp;
       }
      }
     }
     return input;
 }
}


Output:
 2, 7, 10, 34, 42, 56, 67, 88, 

Wednesday, 23 September 2015

Implement selection sort in java

The selection sort is a combination of searching and sorting. During each pass, 
the unsorted element with the smallest (or largest) value is moved to its proper 
position in the array. The number of times the sort passes through the array is 
one less than the number of items in the array. In the selection sort, the inner 
loop finds the next smallest (or largest) value and the outer loop places that 
value into its proper location.
Selection Sort
Selection sort is not difficult to analyze compared to other sorting algorithms since
 none of the loops depend on the data in the array. Selecting the lowest element
 requires scanning all n elements (this takes n − 1 comparisons) and then swapping
 it into the first position. Finding the next lowest element requires scanning the 
remaining n − 1 elements and so on, 
for (n − 1) + (n − 2) + ... + 2 + 1 = n(n − 1) / 2 ∈ Θ(n2) comparisons.
 Each of these scans requires one swap for n − 1 elements.

package com.kundan;

public class MySelectionSort {

 public static int[] doSelectionSort(int[] arr){
  
     for (int i = 0; i < arr.length - 1; i++)
     {
         int index = i;
         for (int j = i + 1; j < arr.length; j++)
             if (arr[j] < arr[index]) 
                 index = j;
  
         int smallerNumber = arr[index];  
         arr[index] = arr[i];
         arr[i] = smallerNumber;
     }
     return arr;
 }
 
 public static void main(String a[]){
  
  int[] arr1 = {10,34,2,56,7,67,88,42};
  int[] arr2 = doSelectionSort(arr1);
  for(int i:arr2){
   System.out.print(i);
   System.out.print(", ");
  }
 }
}

Output:
2, 7, 10, 34, 42, 56, 67, 88, 

Tuesday, 22 September 2015

Implement bubble sort in java

Bubble sort, also referred to as sinking sort, is a simple sorting algorithm that works by repeatedly
 stepping through the list to be sorted, comparing each pair of adjacent items and swapping them 
if they are in the wrong order. The pass through the list is repeated until no swaps are needed, 
which indicates that the list is sorted. The algorithm gets its name from the way smaller elements
 "bubble" to the top of the list. Because it only uses comparisons to operate on elements, 
it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms 
are more efficient for large lists.
Bubble Sort
Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted. 
There exist many sorting algorithms with substantially better worst-case or average complexity of O(n log n).
Even other О(n2) sorting algorithms, such as insertion sort, tend to have better performance than bubble sort.
Therefore, bubble sort is not a practical sorting algorithm when n is large.Performance of bubble sort over an 
already-sorted list (best-case) is O(n).

package com.kundan;
 
public class MyBubbleSort {
 
    // logic to sort the elements
    public static void bubble_srt(int array[]) {
        int n = array.length;
        int k;
        for (int m = n; m >= 0; m--) {
            for (int i = 0; i < n - 1; i++) {
                k = i + 1;
                if (array[i] > array[k]) {
                    swapNumbers(i, k, array);
                }
            }
            printNumbers(array);
        }
    }
 
    private static void swapNumbers(int i, int j, int[] array) {
 
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
 
    private static void printNumbers(int[] input) {
         
        for (int i = 0; i < input.length; i++) {
            System.out.print(input[i] + ", ");
        }
        System.out.println("\n");
    }
 
    public static void main(String[] args) {
        int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
        bubble_srt(input);
 
    }
}

Output:
2, 4, 6, 9, 12, 23, 0, 1, 34, 

2, 4, 6, 9, 12, 0, 1, 23, 34, 

2, 4, 6, 9, 0, 1, 12, 23, 34, 

2, 4, 6, 0, 1, 9, 12, 23, 34, 

2, 4, 0, 1, 6, 9, 12, 23, 34, 

2, 0, 1, 4, 6, 9, 12, 23, 34, 

0, 1, 2, 4, 6, 9, 12, 23, 34, 

0, 1, 2, 4, 6, 9, 12, 23, 34, 

0, 1, 2, 4, 6, 9, 12, 23, 34, 

0, 1, 2, 4, 6, 9, 12, 23, 34, 

Monday, 21 September 2015

Difference between ArrayList and Vector

ArrayList and Vector both implements List interface and maintains insertion order.

But there are many differences between ArrayList and Vector classes that are given below.
ArrayListVector
1) ArrayList is not synchronized.Vector is synchronized.
2) ArrayList increments 50% of current array size if number of element exceeds from its capacity.Vector increments 100% means doubles the array size if total number of element exceeds than its capacity.
3) ArrayList is not a legacy class, it is introduced in JDK 1.2.Vector is a legacy class.
4) ArrayList is fast because it is non-synchronized.Vector is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object.
5) ArrayList uses Iterator interface to traverse the elements.Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.

Example of Java ArrayList

Let's see a simple example where we are using ArrayList to store and traverse the elements.
  1. import java.util.*;    
  2. class TestArrayList21{    
  3.  public static void main(String args[]){    
  4.      
  5.   List<String> al=new ArrayList<String>();//creating arraylist    
  6.   al.add("Sonoo");//adding object in arraylist    
  7.   al.add("Michael");    
  8.   al.add("James");    
  9.   al.add("Andy");    
  10.   //traversing elements using Iterator  
  11.   Iterator itr=al.iterator();  
  12.   while(itr.hasNext()){  
  13.    System.out.println(itr.next());  
  14.   }    
  15.  }    
  16. }    
Output:
Sonoo
Michael
James
Andy

Example of Java Vector

Let's see a simple example of java Vector class that uses Enumeration interface.
  1. import java.util.*;      
  2. class TestVector1{      
  3.  public static void main(String args[]){      
  4.   Vector<String> v=new Vector<String>();//creating vector  
  5.   v.add("umesh");//method of Collection  
  6.   v.addElement("irfan");//method of Vector  
  7.   v.addElement("kumar");  
  8.   //traversing elements using Enumeration  
  9.   Enumeration e=v.elements();  
  10.   while(e.hasMoreElements()){  
  11.    System.out.println(e.nextElement());  
  12.   }  
  13.  }      
  14. }      
Output:
umesh
irfan
kumar