Java Arrays Tutorial Part2
Java arrays Notes Part-2
👈PART-1Table of Contents
Double Dimensional Array
In a double dimensional array, values are stored in the form of rows and columns.
2D Array structure:
1 is stored at 0, 0 (first row and first col)
2 is stored at 0, 1 (first row and second col)
3 is stored at 1, 0 (second row and first col)
4 is stored at 1, 1 (second row and second col)
Declaration of Double Dimensional Array
syntax:
datatype arrayname [rows][cols];
example:
int a[][];
Array can be declared as shown below.
int [][]a;
int []a[];
Initialization of Double Dimensional Array
It can be done in two ways -
type1:
int a[][] = {{2,3}, {4,5}}; //direct initialization
type2:
Declaring double dimensional array using new operator and using index position storing array values.
int a[][] = new int[2][2];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3; a[1][1] = 4;
if size is not specified, it can any size.
Printing DDarray:
a[][] = {{1,2},{3,4}};
System.out.print(a[0][0]);
System.out.print(a[0][1]);
System.out.print("\n");
System.out.print(a[1][0]);
System.out.print(a[1][1]);
program:
ddarray.java
class DDarray { public static void main(String args[]){ int a[][] = {{1,2},{3,4}};
System.out.print(a[0][0]); System.out.print(a[0][1]); System.out.print("\n"); System.out.print(a[1][0]); System.out.print(a[1][1]);
}
}
o/p:
---
1 2
3 4
Initialization of Double Dimensional char Array :
char names[4][10] = {{'a','a','a','a'},
{'b','b','b'},
{'c','c','c','c'},
{'d','d','d','d'}
};
//4 rows, any no. of columns less than 10.
program: public class DDarray { public static void main(String args[]){ char names[][] = {{'a'}, {'b','b'}, {'c','c','c'}, {'d','d','d','d'} }; for(int i = 0;i<4;i++) { System.out.println(names[i]); } System.out.println(""); } }
Example-1
String names [3][20] = {{"india"},{"Briton"},{"America"}};
names are 3, and length of the name can be max. of 20.
Example-2
String names[][] = {{"india","Rupee"},{"France","Euro"}, {"Us","dollar"},{"japan","yen"}};
public class DDarray1
{
public static void main(String args[]){
String names[][] = {{"India","Rupee"},
{"France","Euro"},
{"USA","Dollar"},
{"Japan","Yen"}};
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
System.out.print(names[i][j]+"\t"+names[i][j+1]);
break;
}
System.out.println("");
}
}
}
o/p:
India Rupee
France Euro
USA Dollar
Japan Yen
Practice Questions on Java Arrays:
- Create cities and capitals arrays. Accept city from keyboard and print its capital.
- Print names contact numbers in dd array.
- Create items and prices arrays, calculate total, print all items, prices, total.
- Take marks and subjects arrays, find the highest marks in which subject.
Comments
Post a Comment