2. WHAT ARE ARRAYS?
It is a user defined homogeneous datatype. Unlike
a variable used to store a single value,
int debt =2;
an array declared is used to store series
of values of the same type(homogeneous),
sequentially.
int marks[]=new int[5];
2
debt
s
3. DECLARING AN ARRAY VARIABLE
Array in java is created in two steps.
In first step we just create a reference name
int [ ] marks;
int marks[ ];
Both syntaxes are equivalent. No memory allocation
at this point.
To create actual array we use new operator as shown
below:
marks=new int[5];
OR
We can also create array in single step as:
int marks[]=new int[5];
4. INITIALIZATION OF AN ARRAY
While initializing an array new operator is not required
int[ ] marks={72,61,81,79,72};
In JAVA, int is of 4 bytes, total space=4*5=20 bytes
6. WHAT HAPPENS IF …
If we define
int[ ] marks=new long[5];
marks.java:5: incompatible types
found: long[ ]
required: int[ ]
int[ ] marks = new int[5];
^
The right hand side defines an array, and thus
the array variable should refer to the same
type of array
7. WHAT HAPPENS IF …
Valid code:
int k=5;
int[ ] marks = new int[k];
Invalid Code:
int k;
int[ ] marks =new int[k];
Compilation Output:
More marks.java:6: variable k might not have been initialized
int[ ] marks = new int[k];
^
8. ARRAY SIZE THROUGH INPUT
….
BufferedReader in1 = new BufferedReader (new InputStreamReader(System.in));
int num;
System.out.println("Enter a Size for Array:");
num = Integer.parseInt(in1.readLine( );
int [ ] marks = new int[num];
System.out.println(“Array Length=”+marks.length);
….
SAMPLE RUN:
Enter a Size for Array:
4
Array Length=4
9. DEFAULT INITIALIZATION
When array is created, array elements are
initialized
Numeric values (int, double, etc.) to 0
Boolean values to false
Char values to ‘u0000’ (unicode for blank character)
Class types to null
10. ACCESSING ARRAY ELEMENTS
Index of an array is defined as
Positive int, byte or short values
Expression that results into these types
Any other types used for index will give error
long, double, etc.
Indexing starts from 0 and ends at N-1
11. VALIDATING INDEXES
JAVA checks whether the index values are valid at
runtime
If index is negative or greater than the size of the array
then an ArrayIndexOutOfBoundException will be thrown
Program will normally be terminated unless handled in
the try {} catch {}
12. WHAT HAPPENS IF …
int[] marks = new int[5];
marks[6]=33;
….
Runtime Error:
Exception in thread “main”
java.lang.ArrayIndexOutOfBoundsException: 6
at marks.main(marks.java:6)
13. REUSING ARRAY VARIABLES
Array variable is separate from array itself
Like a variable can refer to different values at
different points in the program
Use array variables to access different arrays
int[] marks=new int[5];
……
marks=new int[50];
Previous array will be discarded
Cannot alter the type of array
14. INITIALIZING ARRAYS
Initialize and specify size of array while
declaring an array variable
int[] marks={2,3,5,7,11,13,17}; //7 elements
You can initialize array with an existing array
int[] even={72,74,66,68,70};
int[] value=even;
One array but two array variables!
Both array variables refer to the same array
Array can be accessed through either variable
name
18. ARRAY LENGTH
Refer to array length using length
A data member of array object
array_variable_name.length
for(int k=0; k<marks.length;k++)
….
Sample Code:
int[] marks = new int[5];
System.out.println(marks.length);
Output: 5
19. CHANGE IN ARRAY LENGTH
If number of elements in the array are changed,
JAVA will automatically change the length attribute!
20. Changing the size of array is not
possible!
On changing the size of an existing array, a new array gets
created at a different memory location.
21. import java.io.*;
class Array1{
public static void main(String args[])throws IOException
{
int n,i,noe;
BufferedReader in1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no of array elements");
noe=Integer.parseInt(in1.readLine());
int arr[]=new int[noe];
System.out.println("Array details"+arr);
System.out.println("Enter "+ noe+" array elements");
for(i=0;i<arr.length;i++)
{
arr[i]=Integer.parseInt(in1.readLine());
}
System.out.println("Entered array elements are as follows:");
for(i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
22. System.out.println("nLets increase number of elements by 2 ");
arr=new int[noe+2];
System.out.println("Array details after increased size"+arr);
System.out.println("Enter "+ (noe+2)+" array elements");
for(i=0;i<arr.length;i++)
{
arr[i]=Integer.parseInt(in1.readLine());
}
System.out.println("Entered array elements are as follows:");
for(i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
}
}
24. SAMPLE PROGRAM
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current minimum
for ( int index=0; index < array.length; index++ )
if ( array[ index ] < min )
min = array[ index ] ;
System.out.println("The minimum of this array is: " + min );
}
}
25. ARRAYS OF ARRAYS
Two-Dimensional arrays
float[][] temperature=new float[10][365];
10 arrays each having 365 elements
First index: specifies array (row)
Second Index: specifies element in that array (column)
In JAVA float is 4 bytes, total Size=4*10*365=14,600
bytes
27. ARRAYS OF ARRAYS OF VARYING LENGTH
(JAGGED ARRAYS)
All arrays do not have to be of the same length
float[][] samples;
samples=new float[5][];//defines no of rows in an array
samples[0]=new float[6];
samples[1]=new float[101];
Not required to define all arrays
28. INITIALIZING VARYING SIZE ARRAYS
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
29. To allocate memory for a 2D array, we need to specify the
memory for the first(Leftmost) dimension. Then remaining
dimensions can be allocated separately.
For eg:
int arr2d[][]=new int[3][];
arr2d[0]=new int[3];
arr2d[1]=new int[3];
arr2d[2]=new int[3];
Above declaration allocates memory for the first dimension of
arr2d when it is declared. Then we allocate memory for the
second dimension separately. There is no benefit of doing
memory allocation this way in above example but it is helpful
when we may want to allocate unequal number of elements
across each row. An array created in this fashion in java is called
Jagged Array.
30. JAGGED ARRAY
Class JaggedArray {
public static void main(String args[])
{
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
{ for(j=0; j<i+1; j++)
{
twoD[i][j] = k;
k++;
}
}
35. MULTIDIMENSIONAL ARRAYS
A farmer has 10 farms of beans each in 5 countries,
and each farm has 30 fields!
Three-dimensional array
int[][][] beans=new int[5][10][30];
//beans[country][farm][fields]
36. VARYING LENGTH IN MULTIDIMENSIONAL
ARRAYS
Same features apply to multi-dimensional arrays as
those of 2 dimensional arrays
int beans=new int[3][][];//3 countries
beans[0]=new int[4][];//First country has 4 farms
beans[0][4]=new int[10];
//Each farm in first country has 10 fields
37. Vector
Vector is a legacy class available in java.util package. Vector
implements a dynamic array. Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
The first form creates a default vector, which has an initial size of
10.
The second form creates a vector whose initial capacity is specified
by size.
The third form creates a vector whose initial capacity is specified
by size and whose increment is specified by incr. The increment
specifies the number of elements to allocate each time that a vector
is resized upward.
38. Important Points:
1. All vectors start with an initial capacity.
2. After this initial capacity is reached, the next time that you
attempt to store an object in the vector, the vector
automatically allocates space for that object plus extra room
for additional objects.
3. By allocating more than just the required memory, the vector
reduces the number of allocations that must take place. This
reduction is important, because allocations are costly in terms
of time.
4. The amount of extra space allocated during each reallocation
is determined by the increment that you specify when you
create the vector.
5. If you don’t specify an increment, the vector’s size is doubled
by each allocation cycle.
39. Vector defines these protected data members:
int capacityIncrement;
int elementCount;
The increment value is stored in capacityIncrement. The number of elements
currently in the vector is stored in elementCount.
Vector defines several legacy methods,
1.void addElement(Object element): The object specified by element is added
to the vector.
2. int capacity( ): Returns the capacity of the vector.
3. boolean contains(Object element): Returns true if element is
contained by the vector, and returns false if it is not.
4. Object elementAt(int index): Returns the element at the
location specified by index.
5. void ensureCapacity(int size) :Sets the minimum capacity of the
vector to size.
40. 6. Object firstElement( ): Returns the first element in the vector.
7. int indexOf(Object element) :Returns the index of the first
occurrence of element. If the object is not in the vector, –1 is
returned.
8. int indexOf(Object element, int start) Returns the index of
the first occurrence of element at or after start. If the object is not
in that portion of the vector -1 is returned.
9. void insertElementAt(Object element, int index): Adds
element to the vector at the location specified by index.
10. boolean isEmpty( ): Returns true if the vector is empty
and returns false if it contains one or more elements.
41. 11. void removeAllElements( ): Empties the vector. After this
method executes, the size of the vector is zero.
12. boolean removeElement(Object element): Removes element from the vector.
If more than one instance of the specified object exists in the vector, then it is the
first one that is removed. Returns true if successful and false if the object is not
found.
13. void removeElementAt(int index): Removes the element at the
location specified by index.
14. void setElementAt(Object element, int index):The location specified by
index is assigned element.
15. void setSize(int size): Sets the number of elements in the vector to size. If the
new size is less than the old size, elements are lost. If the new size is larger than the
old size, null elements are added.
42. // Demonstrate various Vector operations.
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after 4 additions: " +
v.capacity());
44. if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
45. The output from this program is shown here:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12