Arrays
Arrays
About Arrays
Declaring Array
INTRODUCTION TO ARRAY
2. Create an Array
• To create an array, you need to allocate memory for it using the
new keyword:
• Example:
int m[]= new int[10];
Here m is an array that can store 10 data items in the memory
with different subscripts. M is the Subscripted Variable and 0 to 9
are the subscripts
M
M M M2 M9
0 1
EXAMPLE
public class Array{ Outp
public static void main(String[] args) ut
{
// initializing array
int arr[] = { 1, 2, 3, 4, 5 };
// size of array
int n = arr.length;
// traversing array
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
TASK
double total = 0;
for (int i = 0; i < myList.length; i++)
{
total += myList[i];
}
System.out.println("Total is " + total);
• arrayRefVar=new datatype[size];
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;
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}
Output:
10
20
70
40
50
PASSING ARRAY TO METHOD IN JAVA
class Testarray2
{
static void minimum(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 arr[]={33,3,4,5};
minimum(arr);//passing array to method
}}
Output: 3
MULTIDIMENSIONAL ARRAY IN JAVA
Output:
123
245
445
COPYING A JAVA ARRAY
class TestArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
Output: caffein
JAVA ENUM
Output:
WINTER
Introduction to Vectors
• Output:
umesh irfan kumar
Accessing Vector Elements
import java.util.Vector;
public class VectorDemo
{
public static void main(String[] args)
{
// create an empty Vector vec with an initial capacity of 4
Vector vec = new Vector(4);
// use add() method to add elements in the vector
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);
// let us get the 3rd element of the vector
System.out.println("Third element is :"+vec.get(3));
}}
Searching For Elements In A
import java.util.Vector;
Vector
public class VectorDemo
{
public static void main(String[] args)
{
// create an empty Vector vec with an initial capacity of 4
Vector vec = new Vector(4);
// use add() method to add elements in the vector
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(3);
// let us get the index of 3
System.out.println("Index of 3 is :"+vec.indexOf(3));
}
}
import java.util.Vector; Working With The Size of The
Vector
public class VectorDemo
{
public static void main(String[] args)
{
// create an empty Vector vec with an initial capacity of 4
Vector vec = new Vector(4);