0% found this document useful (0 votes)
7 views41 pages

Understanding Arrays in Java Basics

Uploaded by

Ashish Nayyar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views41 pages

Understanding Arrays in Java Basics

Uploaded by

Ashish Nayyar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

ARRAYS IN JAVA

Ashish K. Nayyar
Asst. Prof.
JIMS-VK
WHAT ARE ARRAYS?
It is a user defined homogeneous datatype.
Unlike a variable used to store a single
value,
int debt =2;
debt
s2

an array declared is used to store


series of values of the same
type(homogeneous), sequentially.
int marks[]=new int[5];
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];
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
GRAPHICAL REPRESENTATION
Index
marks

marks[0] marks[1] marks[2] marks[3] marks[4]

72 61 81 79 72

value
WHAT HAPPENS IF …
If we define
int[ ] marks=new long[5];
[Link]: 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
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 [Link]: variable k might not have been
initialized
int[ ] marks = new int[k];
^
ARRAY SIZE THROUGH INPUT
….
BufferedReader in1 = new BufferedReader (new InputStreamReader([Link]));
int num;
[Link]("Enter a Size for Array:");
num = [Link]([Link]( );
int [ ] marks = new int[num];
[Link](“Array Length=”+[Link]);
….
SAMPLE RUN:
Enter a Size for Array:
4
Array Length=4
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
ACCESSING ARRAY ELEMENTS
 Index of an array is defined as
 Positiveint, byte or short values
 Expression that results into these types
 Anyother types used for index will
give error
 long, double, etc.

 Indexing starts from 0 and ends at N-1


VALIDATING INDEXES
 JAVA checks whether the index values are
valid at runtime
 Ifindex 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 {}
WHAT HAPPENS IF …

int[] marks = new int[5];


marks[6]=33;
….
Runtime Error:
Exception in thread “main”
[Link]: 6
at [Link]([Link])
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];
 Previousarray will be discarded
 Cannot alter the type of array
INITIALIZING ARRAYS
 Initialize
and specify size of array while
declaring an array variable
int[] marks={2,3,5,7,11,13,17}; //7
elements
 Youcan 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
GRAPHICAL REPRESENTATION

even

0 1 2 3 4
72 74 66 68 70

value
DEMONSTRATION
int[] marks = new int[20];
marks[0] = 2;
marks[1] = 3;
int[] marks2=marks;
[Link](marks2[0]);
marks2[0]=5;
[Link](marks[0]);
OUTPUT
2
5
ARRAY LENGTH
 Refer to array length using length
A data member of array object
 array_variable_name.length
 for(int k=0; k<[Link];k++)
….
 Sample Code:
int[] marks = new int[5];
[Link]([Link]);
Output: 5
CHANGE IN ARRAY LENGTH
 If number of elements in the array are
changed, JAVA will automatically change the
length attribute!
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 < [Link]; index++ )
if ( array[ index ] < min )
min = array[ index ] ;
[Link]("The minimum of this array is: " +
min );
}
}
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
INITIALIZING ARRAY OF ARRAYS
int[][] array2D = { {99, 42, 74, 83,
100}, {90, 91, 72, 88, 95}, {88, 61,
74, 89, 96}, {61, 89, 82, 98, 93},
{93, 73, 75, 78, 99}, {50, 65, 92, 87,
94}, {43, 98, 78, 56, 99} };
//7 arrays with 5 elements each
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
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
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.
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++;
}
}
for(i=0; i<4; i++)
{
for(j=0; j<i+1; j++)
{
[Link](twoD[i][j] + " ");
}
[Link]();
}
}
}
Output:
0
1 2
3 4 5
6 7 8 9
SAMPLE PROGRAM
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2,
3, 4 } };
// print out the array
for ( int row=0; row < [Link]; row++ )
//changes row
{
[Link]("Row " + row + ": ");
for ( int col=0; col < uneven[row].length;
col++ ) //changes column
[Link]( uneven[row][col] +
" "); [Link]();
}
}
}
OUTPUT
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4
TRIANGULAR ARRAY OF ARRAYS
 Triangular Array
for(int k=0; k<[Link];k++)
samples[k]=new float[k+1];
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]
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
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.
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,

[Link] addElement(Object element): The object specified by element is added


to the vector.
[Link] capacity( ): Returns the capacity of the vector.
[Link] 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.
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.
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.
// Demonstrate various Vector operations.
import [Link].*;
class VectorDemo
{
public static void main(String args[])
{
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
[Link]("Initial size: " + [Link]());
[Link]("Initial capacity: " + [Link]());
[Link](new Integer(1));
[Link](new Integer(2));
[Link](new Integer(3));
[Link](new Integer(4));
[Link]("Capacity after 4 additions: " +
[Link]());
[Link](new Double(5.45));
[Link]("Current capacity: " +[Link]());

[Link](new Double(6.08));
[Link](new Integer(7));
[Link]("Current capacity: " +[Link]());

[Link](new Float(9.4));
[Link](new Integer(10));
[Link]("Current capacity: " +[Link]());

[Link](new Integer(11));
[Link](new Integer(12));
[Link]("First element: " +(Integer)[Link]());
[Link]("Last element: " +(Integer)[Link]());
if([Link](new Integer(3)))
[Link]("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = [Link]();
[Link]("\nElements in vector:");
while([Link]())
[Link]([Link]() + " ");
[Link]();
}
}
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

You might also like