Welcome back, bloggers! In this post you will learn about single dimensional arrays in Java.
First of all, what is an array? An array is a fixed sized sequenced collection of elements of a same data type.
Array in Java is index-based. The very first element is stored at 0th position.
1. Memory does not get wasted.
2. We can get any data located at any fixed index value.
Syntax: datatype name[];
Initialization of a single dimensional array: array[] = new int[5];
Now, let's see an example of a single dimensional array:
class JavaArray {
public static void main(String[] args) {
int array[]; //declaration
array = new int[5]; //instantiation
a[0] = 1; //initialization
a[1] = 2;
a[2] = 3;
a[3] = 4;
a[4] = 5;
//printing the array:
for(int i=0; i<=array.length; i++)
System.out.println(array[i]);
}
}
A single dimensional array can also be made by the following way:
Syntax: int array[] = {10,20,30,40,50};
public static void main(String[] args) {
int array[] = {10,20,30,40,50}; //initialization, instantiation and declaration
//printing the array:
for(int i = 0; i<=array.length; i++)
System.out.println(array[i]);
}
}
Thank you for coming to my blog. Now you have learnt how to declare, instantiate, initialize and print a single dimensional array!
FEEL LIKE A PROGRAMMER!!!
If you find this post useful, kindly share it with your friends and colleagues. :)
First of all, what is an array? An array is a fixed sized sequenced collection of elements of a same data type.
Array in Java is index-based. The very first element is stored at 0th position.
Advantages of array in Java:
1. Memory does not get wasted.2. We can get any data located at any fixed index value.
Single Dimensional Array in Java:
A single dimensional array contains only one row and no number of columns.Syntax: datatype name[];
Initialization of a single dimensional array: array[] = new int[5];
Now, let's see an example of a single dimensional array:
class JavaArray {
public static void main(String[] args) {
int array[]; //declaration
array = new int[5]; //instantiation
a[0] = 1; //initialization
a[1] = 2;
a[2] = 3;
a[3] = 4;
a[4] = 5;
//printing the array:
for(int i=0; i<=array.length; i++)
System.out.println(array[i]);
}
}
A single dimensional array can also be made by the following way:
Syntax: int array[] = {10,20,30,40,50};
Example:
class JavaArray {public static void main(String[] args) {
int array[] = {10,20,30,40,50}; //initialization, instantiation and declaration
//printing the array:
for(int i = 0; i<=array.length; i++)
System.out.println(array[i]);
}
}
Thank you for coming to my blog. Now you have learnt how to declare, instantiate, initialize and print a single dimensional array!
FEEL LIKE A PROGRAMMER!!!
If you find this post useful, kindly share it with your friends and colleagues. :)
Comments
Post a Comment