Array
Array
• An array is a collection of similar types of values.
Sunday Monday Tuesday Wednesday Thursday Friday
Important points
• Fixed size.
• Values are of similar types.
• Stored in continuous memory location.
Index of the Array
Types of Array
• Single dimensional Array
• Items are arranged across x dimension only.
• Multi dimensional Array
• Items are arranged in two or more dimensions.
• Also called as n-dimensional array.
Single Dimensional Array
Sunday Monday Tuesday Wednesday Thursday Friday
0 1 2 3 4 5
Int Array 2 4 6 8 10 12
String Array Sunday Monday Tuesday WednesdayThursday Friday
Double Array 1.5 2.5 3.5 4.5 5.5 6.5
Char Array ‘A’ ‘E’ ’I’ ‘O’ ’U’
Declaring and Initializing a single dimensional array
• int a=5; //Declaring and initializing a variable of type int
• int a[]={2,4,6,8,10};
• OR
• int[] a={2,4,6,8,10};
• Number of elements present in the array is called as the
size or length of the array.
• Question:
• Declare array with vowels and fruit names
Access elements in the array
String days[]={“Sunday”,“Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”};
Sunday Monday Tuesday Wednesday Thursday Friday
0 1 2 3 4 5
days[4] “Thursday”
INDEX RANGE
index of the last element is always array length-1.
0 to array length-1
Subscript,subscripted variable and value
• int a[]={1,2,3,4,5,6};
SUBSCRIPTED VARIABLE a[1] 2 SUBSCRIPTED VALUE
SUBSCRIPT
Subscript-The index of the element in the array.
Subscripted array-Name of the array when it is used with a subscript to
access a single element in the array.
Subscripted value-The value of the element at that index.
Length of the array
• int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
• System.out.println(“Length of the array is “+days.length);
Accessing the elements in the array
class array
{ public static void main()
{
int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
System.out.println(“January”+days[0]);
System.out.println(“February”+days[1]);
System.out.println(“March”+days[2]);
System.out.println(“April”+days[3]);
System.out.println(“May”+days[4]);
System.out.println(“June”+days[5]);
System.out.println(“July”+days[6]);
System.out.println(“August”+days[7]);
System.out.println(“September”+days[8]);
System.out.println(“October”+days[9]);
System.out.println(“November”+days[10]);
System.out.println(“December”+days[11]);
}}
class array
{ public static void main()
{
int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
• for(int i=0;i<days.length;i++)
• System.out.println(days[i]);
• }
• }
import java.util.Scanner;
public class Month
{
public static void main(String args[]) {
String month[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
for(int i=0;i<month.length;i++)
{
System.out.println(month[i]+"-->"+days[i]);
}
}
}