Single dimensional array
- It stores the elements either in one column or one row
Syntax :
NameOfTheDataType variableName[];
Example :
int i[];
float a[];
String names[];
Creating or Instantiating an array :
Syntax :
NameOfTheDataType variableName[] = new NameOfTheDataType[size]
Example
int i[] = new int[10]; // declaration and initialization
length of an array :
- We can find the size of an array by using length
----------------------------------------------------------------------------------Program : To find array length
Program name : ArrayDemo1.java
Output :
The array size is : 5
class ArrayDemo1
{
public static void main(String args[])
{
int a[]=new int[5];
System.out.println("The array size is : "+a.length);
}
}
Compile : javac ArrayDemo1.java
Run : java ArrayDemo1
Output :
The array size is : 5
----------------------------------------------------------------------------------Program : To print defalut values of an array
Program name : ArrayDemo2.java
Output :
0
0
0
0
0
class ArrayDemo2
{
public static void main(String args[])
{
int a[]=new int[5];
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
Compile : javac ArrayDemo2.java
Run : java ArrayDemo2
Output :
0
0
0
0
0
----------------------------------------------------------------------------------Program : To print vlaues from an array
Program name : ArrayDemo3.java
Output :
60
20
80
40
30
class ArrayDemo3
{
public static void main(String args[])
{
int a[]=new int[5];
a[0]=60; // initializing
a[1]=20;
a[2]=80;
a[3]=40;
a[4]=30;
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
Compile : javac ArrayDemo3.java
Run : java ArrayDemo3
Output :
60
20
80
40
30
----------------------------------------------------------------------------------Declaration, Creation and Initialization of an array in single line :
Syntax
NameOfTheDataType variableName[] = {value1, value2, value3};
Example
int i[] = { 52, 24, 38 };
int i[] = { 52, 24, 38 };
----------------------------------------------------------------------------------Program : To print vlaues from an array
Program name : ArrayDemo4.java
Output :
52
24
38
class ArrayDemo4
{
public static void main(String args[])
{
int a[] = {52, 24, 38};
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
Compile : javac ArrayDemo4.java
Run : java ArrayDemo4
Output :
52
24
38
----------------------------------------------------------------------------------
Thanks for your time.
Thanks for your time.
Nireekshan