0% found this document useful (0 votes)
3 views49 pages

unit-1javaArrays

The document provides a comprehensive overview of arrays in Java, detailing their definition, creation, initialization, and types, including single-dimensional, multi-dimensional, and jagged arrays. It explains how to declare, access, and manipulate arrays, as well as the concept of array length and the use of arrays of objects. Additionally, it includes examples and code snippets to illustrate the concepts discussed.

Uploaded by

Anvi Suri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views49 pages

unit-1javaArrays

The document provides a comprehensive overview of arrays in Java, detailing their definition, creation, initialization, and types, including single-dimensional, multi-dimensional, and jagged arrays. It explains how to declare, access, and manipulate arrays, as well as the concept of array length and the use of arrays of objects. Additionally, it includes examples and code snippets to illustrate the concepts discussed.

Uploaded by

Anvi Suri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 49

ARRAYS IN JAVA

By Gargi mukherjee
ARRAYS
 An array is a collection of similar type of elements which
has contiguous memory location
 Java array is an object which contains elements of a
similar data type. Additionally, The elements of an array
are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
 Array in Java is index-based, the first element of the
array is stored at the 0th index, 2nd element is stored on
1st index and so on.
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
TYPES OF ARRAY IN JAVA
 There are two types of array.
• Single Dimensional Array

• Multidimensional Array

• Jagged Arrays

 Single Dimensional Array in Java


 Syntax to Declare an Array in Java
1. dataType[] arr; (or)
2. dataType arr[];

 Instantiation of an Array in Java


1. arrayRefVar=new datatype[size];
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
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];
^
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


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 {}
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)
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
7 74 66 68 70
2
value
DEMONSTRATION
int[] marks = new int[20];
marks[0] = 2;
marks[1] = 3;
int[] marks2=marks;
System.out.println(marks2[0]);
marks2[0]=5;
System.out.println(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<marks.length;k++)
….
 Sample Code:
int[ ] marks = new int[5];
System.out.println(marks.length);
Output: 5
EXAMPLE OF ARRAY
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
FOR-EACH LOOP FOR JAVA ARRAY

 The Java for-each loop prints the array elements one by


one. It holds an array element in a variable, then
executes the body of the loop.
 The syntax of the for-each loop is given below:

1. for(data_type variable:array){

2. //body of the loop

3. }

4. class Testarray1{

5. public static void main(String args[]){

6. int arr[]={33,3,4,5};

7. //printing array using for-each loop

8. for(int i:arr)

9. System.out.println(i);

10.}}
JAVA PROGRAM TO DEMONSTRATE THE WAY OF
PASSING AN ARRAY

 class Testarray2{
 //creating a method which receives an array as a parameter
 static void min(int arr[]){
 int min=arr[0];
 for(int i=1;i<arr.length;i++)
 if(min>arr[i])
 min=arr[i];

 System.out.println(min);
 }

 public static void main(String args[]){


 int a[ ]={33,3,4,5};//declaring and initializing an array
 min(a);//passing array to method
 }}
CHANGE IN ARRAY LENGTH
 If number of elements in the array are changed,
JAVA will automatically change the length
attribute!
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 . E.g Int a[3][10]
={{1,2,3,4,5,6,7,8,9,10},{10,20,30,40,50,60,70,80,90,10
A[0][
0] 1 2
0},{11,12,13,14,15,16,17,18,19,21}}
A[0][1] A[0][2]
3
A[0][3]
4
A[0][4] A[0][5]
[6] 7 8 9
A[1][0] A[1][ 1]
10 20

A[2][0] A[2][1] 14
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
 class twoarray{
 public static void main(String args[]){

 //declaring and initializing 2D array

 int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

 //printing 2D array

 for(int i=0;i<3;i++){

 for(int j=0;j<3;j++){

 System.out.print(arr[i][j]+" ");
 }

 System.out.println();

}

 }}
OUTPUT

123
245

445
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
 f we are creating odd number of columns in a 2D array,
it is known as a jagged array. In other words, it is an
array of arrays with different number of columns.
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++)
{
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
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 < uneven.length; row++ )
//changes row
{
System.out.print("Row " + row + ": ");
for ( int col=0; col < uneven[row].length;
col++ ) //changes column
System.out.print( uneven[row][col] +
" "); System.out.println();
}
}
}
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<samples.length;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
ARRAY OF OBJECTS IN JAVA
 Java is an object-oriented programming language. Most
of the work done with the help of objects. We know
that an array is a collection of the same data type that
dynamically creates objects and can have elements of
primitive types. Java allows us to store objects in an
array. In Java, the class is also a user-defined data type.
An array that conations class type elements are known
as an array of objects. It stores the reference variable of
the object.
 Syntax: ClassName obj[ ]=new ClassName[array_length]; //declare and instantiate
an array of objects or ClassName[] objArray;
 Code:
 public class arrobj
 { public static void main(String args[])
 { //create an array of product object
 Product[] obj = new Product[5] ;
 //create & initialize product objects using constructor
 obj[0] = new Product(23907,"Dell Laptop");
 obj[1] = new Product(91240,"HP 630");
 obj[2] = new Product(29823,"LG OLED TV");
 obj[3] = new Product(11908,"MI Note Pro Max 9");
 obj[4] = new Product(43590,"Kingston USB");
 //display the product object data
 System.out.println("Product Object 1:");
 obj[0].display();
 System.out.println("Product Object 2:");
 obj[1].display();
 System.out.println("Product Object 3:");
 obj[2].display();
 System.out.println("Product Object 4:");
 obj[3].display();
 System.out.println("Product Object 5:");
 obj[4].display();
 //Product class with product Id and product name as attributes
 class Product
 {
 int pro_Id;
 String pro_name;
 //Product class constructor
 Product(int pid, String n)
 {
 pro_Id = pid;
 pro_name = n;
 }
 public void display()
 {
 System.out.print("Product Id = "+pro_Id + " " + " Product Name = "+pro_name);
 //System.out.println();
 }
 }
Obj[0] Obj[1] Obj[2] Obj[3]
pid,pn
ame
OBJ
obj[0] Pid=123 Pname=“hp”
Obj[1] Pid=“121” Pname
=“Lenovo”
Obj[2] Pid=154 Pname=“dell”
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.
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,

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.
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 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());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +v.capacity());

v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +v.capacity());

v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +v.capacity());

v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +(Integer)v.firstElement());
System.out.println("Last element: " +(Integer)v.lastElement());
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();
}
}
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