arrays in java with example
The main definition of an array is, an array represents the group of elements. In Java, array plays a key role. The main purpose of the array is to hold a fixed set of elements. Why I said fixed set is, while creating array we have to define the size of the array. So, that array can hold only that no of elements in it.
For example, when we have created main() method in our program, you can observe there is a String[] array. Otherwise, JVM can't understand and it will not consider that main method as starting point of the application.
How to create an array in Java?
The below are two different ways of creating an array in java. In the first way, you have to pass the elements between the braces {}.
As I have already mentioned, array represents the group of elements. Those elements should be of same type. Otherwise compiler will not allow to add. But, there is a possibility of casting.
For example, I have an array which holds Integer type of values. Now, I need to insert Float type of values into array. In general, program will not allow of that. But, we can use type casting and convert the value into Integer type and we can add into array.
How to get data from array?
Array can store elements into indexing order. Indexing start from 0 and ends at n position. So, getting specific index element value from array is always O(1) time complexity. For example, we need to get the first positioned element from array, then we need to pass the index as 0.
What are different type of arrays in java?
Majorly there are two different type of arrays in Java. The first one is, single dimensional array also called as one dimensional array and multi dimensional array.
What is one dimensional array?
One dimensional or single dimensional array represents a row or a column of elements. Array declaration is as explained in above only. Here is the another example of one dimensional array,
In the above declaration, String[] represents String type of array. That means the daysInWeek[] array can store only String type of elements.
JVM creates 7 blocks of memory as there are 7 elements being stored into the daysInWeek[] array. These blocks of memory can be individually referred to as daysInWeek[0]....daysInWeek[6].
what is multi dimensional array?
Multi dimensional array represents 2D, 3D...etc. Two dimensional array is a combination of two or more one dimensional array. Similarly, 3D array is combination of two or more 2D arrays.
In other words, two dimensional array represents several rows and columns of data. For example, Subject marks are obtained by a group of Students in five different subjects can be represented by a 2D array. If we write the marks of three students as,
The preceding marks represents a 2D array since it got 3 rows(no.of Students) and five columns(no of Subjects). There are totally, 3*5=15 elements.
How to create two dimensional array?
There are different approaches of creating a 2D array. To represent a two dimensional array we need to define two pairs of square brackets like [][] and each row of elements should be declared between {} braces. First we just declare a two dimensional array without initializing the values and then we allocate sizes of the array.
We can also declare the above two lines code into a single line.
we can also declare a two dimensional array and directly store elements a the time of it's declaration.
Source code for accessing two dimensional array is,
Anonymous Arrays:
There is another type of arrays in Java called as Anonymous Arrays. Declaration of an array without the name is called as Anonymous Array. The main objective of anonymous array is of instance use, not for future use. We can create Anonymous Array as follows,
Note: while creating anonymous array, we should not define the size of the array, otherwise we will get a compilation error.
If we have declared name for anonymous array, then that array is not considered as anonymous array. It will treat as normal array.
Jagged Array:
An array which contains group of arrays with in is called Jagged Array. That means, we can create an array in java, such that other arrays can become it's elements. This is a unique feature in java.
Jagged array can store single and multi dimensional arrays and also can store arrays of any size. Jagged arrays also called as "irregular multi dimensional arrays". The below example explains how to create Jagged array in java.
In the above line, x is a Jagged array with size of 2. It's elements will be x[0] and x[1]. Observe last pair empty square braces in the expression new int[2][]. The last pair of braces represents 1D array. So, x[0] and x[1] can store two 1D arrays. Now, let's allocate memory for x[0] and x[1].
So, the first array represents x[0] and can have 2 elements which can be referred as,
Similarly the second array represented by x[1] can have 3 elements,
Sample source code which uses Jagged arrays,
How to sort array elements into ascending and descending order without using Arrays.sort()?
For example, when we have created main() method in our program, you can observe there is a String[] array. Otherwise, JVM can't understand and it will not consider that main method as starting point of the application.
How to create an array in Java?
The below are two different ways of creating an array in java. In the first way, you have to pass the elements between the braces {}.
int[] ar = {}; or int[] ar = new int[10];
As I have already mentioned, array represents the group of elements. Those elements should be of same type. Otherwise compiler will not allow to add. But, there is a possibility of casting.
For example, I have an array which holds Integer type of values. Now, I need to insert Float type of values into array. In general, program will not allow of that. But, we can use type casting and convert the value into Integer type and we can add into array.
ar[0]=(int) 10.0;
How to get data from array?
Array can store elements into indexing order. Indexing start from 0 and ends at n position. So, getting specific index element value from array is always O(1) time complexity. For example, we need to get the first positioned element from array, then we need to pass the index as 0.
int i = ar[0];
What are different type of arrays in java?
Majorly there are two different type of arrays in Java. The first one is, single dimensional array also called as one dimensional array and multi dimensional array.
What is one dimensional array?
One dimensional or single dimensional array represents a row or a column of elements. Array declaration is as explained in above only. Here is the another example of one dimensional array,
String[] daysInWeek = {"Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur"};
In the above declaration, String[] represents String type of array. That means the daysInWeek[] array can store only String type of elements.
JVM creates 7 blocks of memory as there are 7 elements being stored into the daysInWeek[] array. These blocks of memory can be individually referred to as daysInWeek[0]....daysInWeek[6].
class OneDimensional { public static void main(String[] args) { // declare and initialize the array String[] daysInWeek = { "Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur" }; // display all the 7 elements for (int i = 0; i < daysInWeek.length; i++) { System.out.println(daysInWeek[i]); } System.out.println("Total number of days : " + daysInWeek.length); } }
what is multi dimensional array?
Multi dimensional array represents 2D, 3D...etc. Two dimensional array is a combination of two or more one dimensional array. Similarly, 3D array is combination of two or more 2D arrays.
In other words, two dimensional array represents several rows and columns of data. For example, Subject marks are obtained by a group of Students in five different subjects can be represented by a 2D array. If we write the marks of three students as,
50, 40, 43, 55, 60 79, 57, 48, 43, 66 78, 78, 46, 56, 55
The preceding marks represents a 2D array since it got 3 rows(no.of Students) and five columns(no of Subjects). There are totally, 3*5=15 elements.
How to create two dimensional array?
There are different approaches of creating a 2D array. To represent a two dimensional array we need to define two pairs of square brackets like [][] and each row of elements should be declared between {} braces. First we just declare a two dimensional array without initializing the values and then we allocate sizes of the array.
int marks[][]; //declaring marks array marks[][] = new int[3][5]; // allot memory for storing 15 elements
We can also declare the above two lines code into a single line.
int marks[][] = new int[3][5]; // allot memory for storing 15 elements
we can also declare a two dimensional array and directly store elements a the time of it's declaration.
int marks[][] = {{50, 40, 43, 55, 60},{79, 57, 48, 43, 66},{78,78,46,56,55}};
Source code for accessing two dimensional array is,
class TwoDimensional{ public static void main(String[] args){ //take a 2D array int marks[][] = {{50, 40, 43, 55, 60},{79, 57, 48, 43, 66},{78,78,46,56,55}}; //read and display the array elements for(int i=0;i<3;i++){ for(int j =0; j<5;j++){ System.out.print(marks[ i ][ j ]+"\t"); } System.out.println(); //next line } } }
Anonymous Arrays:
There is another type of arrays in Java called as Anonymous Arrays. Declaration of an array without the name is called as Anonymous Array. The main objective of anonymous array is of instance use, not for future use. We can create Anonymous Array as follows,
new int[]{1,2,3,4}
Note: while creating anonymous array, we should not define the size of the array, otherwise we will get a compilation error.
package com.javatbrains.array; public class Test { public static void main(String[] args) { sum(new int[]{1,2,3,4}); } public static void sum(int[] x){ int total = 0; for(int x1 : x){ total = total+x1; } System.out.println("Sum of the array is: "+total); } }
If we have declared name for anonymous array, then that array is not considered as anonymous array. It will treat as normal array.
String str = new String[]{"A","B"}; System.out.println(str[0]); System.out.println(str[1]); System.out.println(str.length);
Jagged Array:
An array which contains group of arrays with in is called Jagged Array. That means, we can create an array in java, such that other arrays can become it's elements. This is a unique feature in java.
Jagged array can store single and multi dimensional arrays and also can store arrays of any size. Jagged arrays also called as "irregular multi dimensional arrays". The below example explains how to create Jagged array in java.
int x[ ][ ] = new int[2][ ];
In the above line, x is a Jagged array with size of 2. It's elements will be x[0] and x[1]. Observe last pair empty square braces in the expression new int[2][]. The last pair of braces represents 1D array. So, x[0] and x[1] can store two 1D arrays. Now, let's allocate memory for x[0] and x[1].
x[0] = new int[2]; x[1] = new int[3];
So, the first array represents x[0] and can have 2 elements which can be referred as,
x[0][0],x[0][1]
Similarly the second array represented by x[1] can have 3 elements,
x[1][0],x[1][1],x[1][2]
Sample source code which uses Jagged arrays,
class JaggedArray{ public static void main(String[] args){ //Jagged array that can contains two 1D arrays int x[][] = new int[2][]; // Create two more 1D arrays as part of x x[0] = new int[2]; //2 elements in first array x[1] = new int[3]; // Store 2 elements into first array x[0][0] = 10; x[0][1] = 11; //Store 3 elements into second array x[1][0] = 12; x[1][1] = 13; x[1][2] = 14; //display first array for(int i=0;i<2;i++) System.out.print(x[1][i]+","); System.out.println(); //display second array for(int j=0;j<3;j++) System.out.print(x[1][j]+","); } }
How to sort array elements into ascending and descending order without using Arrays.sort()?
Here is the source code for sorting an array elements into ascending as well as in descending order without using Arrays.sort() method.
Do you know?package com.java.array.sort; public class ArraySorting { public static void main(String[] args) { ArraySorting as = new ArraySorting(); int[] ar = { 1, 4, 48, 45, 45, 21, 10, 30 }; as.ascending(ar); System.out.println(); as.descending(ar); } public void ascending(int[] ar) { if (ar.length < 0) { System.out.println("Array is empty."); return; } int temp; for (int i = 0; i < ar.length; i++) { for (int j = i + 1; j < ar.length; j++) { if (ar[i] > ar[j]) { temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } } } for (int i = 0; i < ar.length; i++) { System.out.print(ar[i] + ", "); } } public void descending(int[] ar) { if (ar.length < 0) { System.out.println("Array is empty."); return; } int temp; for (int i = 0; i < ar.length; i++) { for (int j = i + 1; j < ar.length; j++) { if (ar[j] > ar[i]) { temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } } } for (int i = 0; i < ar.length; i++) { System.out.print(ar[i] + ", "); } } }
Comments
Post a Comment