Tuesday 28 August 2018

Vectors & Wrapper Classes


Vectors
Vectors class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number. Vector class contained in the java.util.package. The objects do not have to be homogenous. Vectors are created like arrays as follows:

            Vector vect=new vector();       //declaring without size
            Vector vect=new vect(3);                     //declaring with size.

 Vectors possess a number of advantages over arrays:-

  1. It is convenient to use vectors to store objects
  2. A vector can be used to store a list of objects that may vary in size.
  3. We can add and delete objects from the list as and when required.
Vectors can hold only Objects and not primitive types (eg, 5).

Common Vector Methods

There are many useful methods in the Vector class and its parent classes. Here are some of the most useful. v is a Vector, i is an int index, o is an Object.
Method
Description
v.add(o)
adds Object o to Vector v
v.add(i, o)
Inserts Object o at index i, shifting elements up as necessary.
v.clear()
removes all elements from Vector v
v.contains(o)
Returns true if Vector v contains Object o
v.firstElement(i)
Returns the first element.
v.get(i)
Returns the object at int index i.
v.lastElement(i)
Returns the last element.
v.listIterator()
Returns a ListIterator that can be used to go over the Vector. This is a useful alternative to the for loop.
v.remove(i)
Removes the element at position i, and shifts all following elements down.
v.set(i,o)
Sets the element at index i to o.
v.size()
Returns the number of elements in Vector v.
v.toArray(Object[])
The array parameter can be any Object subclass (eg, String). This returns the vector values in that array (or a larger array if necessary). This is useful when you need the generality of a Vector for input, but need the speed of arrays when processing the data.
v.addElement(item)
Adds the item specified to the list at the end
v.elementAt(10)
Gives the name of the 10th object
v.size()
Gives the number of objects present
v.removeElement(item)
Removes the specified item from the list
v.removeElementAt(n)
Removes the item stored in the nth position of the list
v.removeAllElements( )
Removes all the elements in the list
v.copyInto(array)
Copies all items from list to array
v.insertElementAt(item,n)
Inserts the item at nth position

Example Program:
import java.io.*;
import java.util.*;
class VectorDemo1
{
public static void main(String args[]) throws IOException
{
Vector v = new Vector( );
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("1.Creation");
System.out.println("2.Insertion");
System.out.println("3.Deletion");
System.out.println("4.Display");
System.out.println("5.exit");
System.out.println("Enter Ur Choice:");
int n=Integer.parseInt(br.readLine());
switch(n)
{
            case 1:            
                        System.out.println("Enter the Element:");
                        v.addElement(new Integer(br.readLine()));
                        break;
            case 2: System.out.println("Enter the position to be inserted:");
                        int x=Integer.parseInt(br.readLine());
                        v.insertElementAt(new Integer(br.readLine()),x);
                        break;
            case 3:System.out.println("Enter the position to be deleted:");
                        int y=Integer.parseInt(br.readLine());
                        v.removeElementAt(y);
                        break;
            case 4: System.out.println("Elements are:");
                        for(int i=0;i<v.size();i++)
                        System.out.println(v.get(i)+" ");                      
                        break;
            case 5:System.exit(0);
}
}
}
}

Wrapper Classes
Vectors cannot handle primitive data types like int,float,long,char and double. Primitive data types may be converted into object types by using the wrapper classes contained in Java.lang package.


Following table lists the primitive types and the corresponding wrapper classes:
Primitive
Wrapper
boolean
  java.lang.Boolean
byte
  java.lang.Byte
char
  java.lang.Character
double
  java.lang.Double
float
  java.lang.Float
int
  java.lang.Integer
long
  java.lang.Long
short
  java.lang.Short


Strings


Strings

A String represents the sequence of characters the easiest way to represent to a sequence of characters in java is by using a character array.

Example:
Char charArray[ ]=new char[4];
CharArray[0]=’J’;
CharArray[1]=’a’;
CharArray[2]=’v’;
CharArray[3]=’a’;
            In java strings are class objects and implemented using two classes, namely, String and StringBuffer. A java string is an instantiated object of the class String class. A java string is not a character array and is not NULL terminated. Strings may be declared as follows:
                        String Stringname;
                        Stringname = new string(“String”);

 Example:

String firstname;
firstname = new String(“Anil”);
these two statements may be combined as follows:
String firstname = new String(“Anil”);
Like arrays, it is possible to get the length of string using the length method of the String class.
int m=firstname.length();
Java strings can be concatenated using the + operator.

 Example;

String fullName =  name1+name2;
String city = ”New”+”Delhi”;

//Program to find substring in java
import java.io.*;
import java.lang.String;
class strings
{
            public static void main(String []args) throws IOException
            {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                        String fname,sname;
                        int flag=0;
                        System.out.println("Enter the First Name:");
                        fname=String.valueOf(br.readLine());
                        System.out.println("Enter the Second Name:");
                        sname=String.valueOf(br.readLine());
                        for(int i=0;i<fname.length();i++)
                        {
                                    for(int j=0;j<sname.length();j++)
                                    {
                                                if(fname.charAt(i)!=(sname.charAt(j)))
                                                            continue;
                                                else
                                                            flag++;
                                    }
                        }
                        if(flag!=0)
                                    System.out.println(sname + " is a substring of "+fname);
                        else
                                    System.out.println(sname + " is not a substring of "+fname);
            }
}
Output:
D:\ \programs>javac strings.java
D:\ \programs>java strings
Enter the First Name:
mega star
Enter the Second Name:
mega
mega is a substring of mega star

Commonly used string methods

Method Name
Task Performed
S2=s1.toLowerCase;
Converts string s1 to lowercase
S2=s1.toUpperCase;
Converts string s1 to uppercase
S2=s1.replace(‘x’,’y’);
Replace all x with y
S2=s1.trim();
Remove white spaces
s1.equals(s2)
Returns true is s1=s2
s1.equalsIgnoreCase(s2)
Returns true is s1=s2, ignoring the case
s1.length()
Finds the length of s1
s1.charAt(n)
Gives nth character of s1
s1.compareTo(s2)
Returns negative if s1<s2, positive if s1>s2, and zero if s1=s2
s1.concat(s2)
Concatenates s1 and s2
s1.substring(n)
Gives substring starting from nth character
s1.indexOf(‘x’)
Gives the position of first occurrence of x in string s1.


Arrays


One-dimensional Arrays:
A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or  a one dimensional array.
            Ex: x[0],x[1],x[2],…………, x[n]
The subscript can begin with 0 or 1
Like any other variable arrays must be declared and created in the computer memory before they are used. Creation of an array involves 3 steps:
1.                  Declare the array
2.                  Create memory locations
3.                  Put values into the memory location

Declaration of arrays:
Arrays in java may be declared in two forms:

Form1:  type arrayname[ ];

Form2:  type [ ] arrayname;

Examples:
int                    number[ ];
float                 average[ ];
int[ ]                 counter;
float[ ] marks;
Remember that we do not enter the size of the arrays in declaration.

Creation of arrays:
After declaration of an array we need to create it ion memory. Java allows us to create arrays using new operator only. As shown below:
                                    arrayname= new type[size];
Example:
            number            =          new int[5];
            average            =          new float[10];

Initialization of Arrays:
The final step is to put values into the array created. This process is known as initialization this done using the array subscripts as shown below:
                        Arrayname[subscript]=value;
Example:
number[0]=35;
number[1]=40;
…………………
…………………
number[4]=19;
note: java creates arrays starting with a subscript of 0 and ends with a value one less than the size specified.
We can also initialize arrays automatically  in the same way as the ordinary variables when they are declared, as shown below:
type arrayname[  ] = { list of values };
Example:
                        int number[ ] = { 35,40,20,57,19 };

Array length

In java all arrays store the allocated size in a variable named length.
Example: we can access the length of the array A is
            int Asize=A.length;

import java.io.*;
class array1
{
public static void main(String args[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Float [ ]a =new Float [5];
Float x[ ]=new Float[5];
int i,j=0;
System.out.println("enter how many");
int n=Integer.parseInt(br.readLine());
System.out.println("enter the array elements");
for(i=0;i<n;i++)
{
a[i]=Float.valueOf(br.readLine());
}
System.out.println("  given array is....");
for(i=0;i<n;i++)
{
System.out.println("element at index "+ i +"   is  " +a[i]);
}
}
}

OUTPUT::
D:\ \programs>javac array1.java
D:\ \programs>java array1
enter how many
5
enter the array elements
1.1
1.2
1.3
1.4
1.5
given array is....
element at index 0   is  1.1
element at index 1   is  1.2
element at index 2   is  1.3
element at index 3   is  1.4
element at index 4   is  1.5

Two dimensional Arrays:
            For creating two-dimensional arrays we must follow the same steps as that of simple arrays. We may create a two dimensional array like this:
                        int myArray[ ][ ];
                        myArray = new int[3][4];
                                    (or)
                        int myArray[ ][ ]=new int [3][4];

The following example is for addition two matrices:
import java.io.*;
class matrix1
{
public static void main(String args[])throws IOException
{
int a[ ][ ]=new int [3][3];
int b[ ][ ]=new int [3][3];
int c[ ][ ]=new int [3][3];
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter how many rows and columns for matrix A:");
int m=Integer.parseInt(br.readLine());
int n= Integer.parseInt(br.readLine());
System.out.println("enter the lements into matrix:A");
for( i=0;i<m;i++)
{
for( j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("enter how many rows and columns for matrix B:");
int p=Integer.parseInt(br.readLine());
int q= Integer.parseInt(br.readLine());
System.out.println("enter the lements into matrix:B");
for( i=0;i<p;i++)
{
for( j=0;j<q;j++)
{
b[i][]=Integer.parseInt(br.readLine());
}
}
if(m!=p&&n!=q)
{
System.out.println("Addition is not Possible");
System.exit(0);
}
else
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
}
System.out.println("result matrix is...");
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
System.out.print("\t"+c[i][j]);
}
}
}
}
Output:
D:\ \programs>javac matrix1.java
D:\ \programs>java matrix1
enter how many rows and columns for matrix A:
2
2
enter the lements into matrix:A
1
2
3
4
enter how many rows and columns for matrix B:
2
2
enter the lements into matrix:B
1
2
3
4
result matrix is...

        2       4
        6       8