Array, String and Vector

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

By Dr.

Megha V Gupta, NHITM


 Array is a group of continuous or related data
items that share a common name.
 Syntax:
array_name[value];
 Example:
salary[10];
 ONE-DIMENSIONAL ARRAY
 CREATING AN ARRAY
 DECLARATION OF ARRAY
 CREATION OF ARRAY
 INITIALIZATION OF ARRAY
 ARRAY LENGTH
 TWO-DIMENSIONAL ARRAY
 VARIABLE-SIZE ARRAY
 A list of items can be given one variable name
using only one subscript and such a variable is
called a single- subscripted or One-
dimensional array.
 Express as:
x[1],x[2]………x[n]
 The subscript of an array can be integer
constants, integer variables like i, or
expressions that yield integers.
 Like any other variables, array must be
declared and created in the computer
memory before they are used.
 Creation of an array involves three steps:-
1. Declaring the array
2. Creating memory locations
3. Putting values into the memory locations
 Arrays in Java may be declared in two forms:
Form1 type arrayname[ ];

Form2 Type[ ] arrayname;

Example:
int number[ ];
float average[ ];
int[ ] counter;
float[ ] marks;
 Java allows to create arrays using new
operator only , as shown below:
arrayname = new type[size];

 Examples:
number = new int[5];
average = new float[10];
 In this step values are put into the array created.
This process is known as initialization.
arrayname[subscript] = value;

 Example:
number[0]=35;
number[1]=40;
.............
number[n]=19;
 Java creates array starting with a subscript of
0(zero) and ends with a value less than the
size specified.
 Trying to access an array beyond its
boundaries will generate an error message.
 Array can also be initialized as the other
ordinary variables when they are declared.
 Array initializer is a list of values separated by
commas and surrounded by curly braces.
 All arrays store the allocated size in a variable
named length.
 To access the length of the array a using
a.length.
 Each dimension of the array is indexed from
zero to its maximum size minus one.
 Example:

int aSize = a . Length;


import java.util.Scanner;
public class Search_Element
{
public static void main(String[] args)
{
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the element you want to find:");
x = s.nextInt();
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
}
if(flag == 1)
{
System.out.println("Element found at position:"+(i + 1));
}
else
{
System.out.println("Element not found");
}
}
}
 In this, the first index selects the row and the
second index selects the column within that
row.
 For creating two-dimensional array, same
steps are to be followed as that of simple
arrays.
 Example:
int myArray[ ][ ];
myArray = new int [3] [4];
column 0 column 1 column 2

[0][0] [0][1] [0][2]

Row 0 310 275 365

Row 1 210 190 325

Row 2 405 235 240


import java.util.Scanner;
public class Ex2DArray
{
public static void main(String args[ ])
{
// initialize here.
int row, col, i, j;
int arr[ ][ ] = new int[10][10];
Scanner scan = new Scanner(System.in);
// enter row and column for array.
System.out.print("Enter row for the array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter column for the array (max 10) : ");
col = scan.nextInt();
// enter array elements.
System.out.println("Enter " + (row * col) + " Array Elements : ");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
arr[i][j] = scan.nextInt();
}
}

// the 2D array is here.


System.out.print("The Array is :\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
 Java treats multidimensional arrays as “arrays
of arrays”.
 A two-dimensional array declare as:
int x[ ][ ] = new int [3][ ];
x[0] = new int[2];
x[1] = new int[4];
x[2] = new int[3];
These statements create a 2D array as having
different lengths for each row.
 It is the most common part of many java
programs.
 String represents a sequence of characters.
 The simplest way to represent a sequence of
characters in java is by using a character
array.
 Example:
char charArray[ ] = new char[4];
charArray[0] = ‘J’;
charArray[1] = ‘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 String class.
 Java string as compared to C strings, are
more reliable and predictable.
 A java string is not a character array and
is not NULL terminated.
String stringName;
stringName = new String (“string”);

 Example:

String firstName;
firstName = new String(“Anil”);
 Array can be created and used that contain
strings.

 Above statement create following effects:


 Java String Class is immutable, i.e. Strings in java, once created and initialized,
cannot be changed on the same reference. A java.lang.String class is final which
implies no class and extend it.
 The java.lang.String class differs from other classes, one difference being that the
String objects can be used with the += and + operators for concatenation.

Two useful methods for String objects are equals( ) and substring( ).
The equals( ) method is used for testing whether two Strings contain the same value.
The substring( ) method is used to obtain a selected portion of a String.

Java.lang.String class creation


A simple String can be created using a string literal enclosed inside double quotes as
shown;

 String str1 = “My name is bob”;


 String class defines a number of methods
that allow us to accomplish a variety of string
manipulation tasks.
Sr No. Method call Task Performed
1. s2=s1.toLowerCase Convert string s1 to all lowercase
2. s2=s1.toUpperCase Convert string s1 to all uppercase
3. S2=s1.replace(‘x’, ‘y’) Replace all appearance of x with y.
4. S2=s1.trim() Removes white space at the beginning and end of s1
string.
5. S1.equals(s2) Returns true if s1 is equal to s2.
6. S1.equalsIgnoreCase(s2) Returns true if s1=s2, ignoring the case of character.
7. S1.length() Gives the length of s1.
8. S1.ChartAt(n) Gives nth character of s1.
9. S1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2 and zero if
s1=s2.
10. S1.concat(s2) Concatenate s1 and s2.
11. S1.substring(n) Gives substring starting from nth character.
12 S1.substring(n,m) Gives substring starting from nth character n upto the
mth. (Not including m);
13 String.ValuesOf(p) Create a string object of the object p.
14. p.toString() Create a string representation of the object p.
15. S1.indexOf(‘x’) Gives the position of the first occurence of x in the string
s1.
16. S1.indexOf(‘x’,n) Gives the position of x that occurs after n positions in the
string s1.
17. String.Valueof(Variable) Convert the parameter value to string representation.
 StringBuffer is a peer class of String.
 While String creates strings of fixed_length,
StringBuffer creates strings of flexible length
that can be modified in term of both length
and content.
 We can insert characters and substrings in the
middle of a string to the end.
➢ StringBuffer is a peer class of String that provides much of the
functionality of strings. String represents fixed-length,
immutable character sequences while StringBuffer represents
growable and writable character sequences.

➢ StringBuffer may have characters and substrings inserted in


the middle or appended to the end. It will automatically grow
to make room for such additions and often has more
characters preallocated than are actually needed, to allow
room for growth.
➢ StringBuffer Constructors
StringBuffer( ): It reserves room for 16 characters without reallocation.

StringBuffer s=new StringBuffer();

➢ StringBuffer( int size)It accepts an integer argument that explicitly sets the
size of the buffer.
StringBuffer s=new StringBuffer(20);

➢ StringBuffer(String str): It accepts a String argument that sets the initial


contents of the StringBuffer object and reserves room for 16 more characters
without reallocation.
StringBuffer s=new StringBuffer("Pranali");
The java.lang.StringBuffer class is a thread-safe, mutable
sequence of characters. Following are the important points about
StringBuffer −
➢ A string buffer is like a String, but can be modified.
➢ It contains some particular sequence of characters, but the
length and content of the sequence can be changed through
certain method calls.
➢ They are safe for use by multiple threads.
➢ Every string buffer has a capacity.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.

2)StringBuffer insert() method


The insert() method inserts the given string with this string at the given position.

3) StringBuffer replace() method


The replace() method replaces the given string from the specified beginIndex and endIndex.

4) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.

5) StringBuffer reverse() method


The reverse() method of StringBuilder class reverses the current string.

6) StringBuffer capacity() method


The capacity() method of StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases
the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
PROGRAM:
import java.lang.String;
class buffer
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("This is my college");
System.out.println("This string sb is : " +sb);
System.out.println("The length of the string sb is : "+sb.length());
System.out.println("The capacity of the string sb is : "+sb.capacity());
System.out.println("The character at an index of 6 is : "+sb.charAt(6));
sb.setCharAt(3,'x');
System.out.println("After setting char x at position 3 : "+sb);
sb.setCharAt(3,'s');
System.out.println("Again after setting char s at position 3 : "+sb);
System.out.println("After appending : "+sb.append(" in Thane "));
System.out.println("After inserting : "+sb.insert(19,"NHITM "));
System.out.println("After deleting : "+sb.delete(19,24));
}
}
OUTPUT:

This string sb is : This is my college


The length of the string sb is : 18
The capacity of the string sb is : 34
The characterat an index of 6 is : s
After setting char x at position 3 : Thix is my college
Again after setting char s at position 3 : This is my college
After appending : This is my college in Thane
After inserting : This is my college NHITM in Thane
After deleting : This is my college in Thane
 In Java the concept of variable arguments to a function
is achieved by the use of Vector class contained in the
java.utl package.

 This class can be used to create a generic dynamic


array known as vector that can hold objects of any type
and any number.

 The objects in this do not have to be homogenous.

 Array can be easily implemented as vectors.


Method 1:
Syntax: Vector object= new Vector()
Example: Vector vec = new Vector();
It creates an empty Vector with the default initial capacity of 10. It means the Vector
will be re-sized when the 11th element needs to be inserted into the Vector.

Method 2:
Syntax: Vector object= new Vector(int initialCapacity)
Example: Vector vec = new Vector(3);
It will create a Vector of an initial capacity of 3.

Method 3:
Syntax: Vector object= new vector(int initialcapacity, capacityIncrement)
Example: Vector vec= new Vector(4, 6)
Here we have provided two arguments. The initial capacity is 4 and capacityIncrement
is 6. It means upon insertion of the 5th element the size would be 10 (4+6) and on the
11th insertion it would be 16(10+6).
1 add() It is used to append the specified element in the given vector.
It is used to append all of the elements in the specified collection to the end
2 addAll()
of this Vector.
It is used to append the specified component to the end of this vector. It
3 addElement()
increases the vector size by one.
4 capacity() It is used to get the current capacity of this vector.
5 clear () It is used to delete all of the elements from this vector.
6 contains() It returns true if the vector contains the specified element.
7 elementAt() It is used to get the component at the specified index.
It is used to increase the capacity of the vector which is in use, if necessary.
8 ensur eCapacity() It ensures that the vector can hold at least the number of components
specified by the minimum capacity argument.
9 fir stElement() It is used to get the first component of the vector.
10 lastElement() It is used to get the last component of the vector.
It is used to insert the specified object as a component in the given vector at
11 inser tElementAt()
the specified index.
It is used to remove the specified element from the vector. If the vector does
12 r emove()
not contain the element, it is unchanged.
It is used to delete all the elements from the vector that are present in the
13 r emoveAll()
specified collection.
r emoveAllElement It is used to remove all elements from the vector and set the size of the
14
s() vector to zero.
15 setSize() It is used to set the size of the given vector.
16 size() It is used to get the number of components in the given vector.
PROGRAM:
import java.util.*;
public class VectorExample1
{
public static void main(String args[])
{
Vector<String> vec = new Vector<String>(4);
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
System.out.println("Elements are: "+vec);
System.out.println("The first animal of the vector is = "+vec.firstElement());
System.out.println("The last animal of the vector is = "+vec.lastElement());
System.out.println("The Animal Tiger is found at position : "+vec.indexOf("Tiger"));
vec.removeElement("Lion");
vec.removeElement("Deer");
System.out.println("After removing 2 Animals from Vector ");
System.out.println("Vector Size :"+vec.size());
System.out.println("Elements are: "+vec);
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
}
}
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 10
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
The Animal Tiger is found at position : 0
After removing 2 Animals from Vector
Vector Size :5
Elements are: [Tiger, Dog, Elephant, Rat, Cat]
Tiger is present at the index 0
 A vector can be declared without specifying any
size explicitly.
 A vector can accommodate an unknown number
of items . Even, when a size is specified, this can
be overlooked and a different number of items
may be put into the vector.
DISADVANTAGES OF VECTOR OVER
ARRAYS
 Since, 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 the java.lang packages.

 The wrapper classes have a number of unique


methods for handling primitive data types and
objects.
Simple Type Wrapper Class

boolean Boolean
char Character

double Double

float Float

int Integer

long Long
Let us see the different scenarios, where we need to use the wrapper classes.
 Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the
primitive value in an object, it will change the original value.

 Serialization: We need to convert the objects into streams to perform the


serialization. If we have a primitive value, we can convert it in objects through the
wrapper classes.

 Synchronization: Java synchronization works with objects in Multithreading.

 java.util package: The java.util package provides the utility classes to deal with
objects.

 Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

You might also like