Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

java.util.

Arrays
Methods: -
public static void sort(int[ ]);
public static void sort(char[ ]);
public static void sort(float[ ]);
public static int binarySearch(int[ ],int);
public static Boolean equals(int[ ], int[ ]);
public static String toString(int[ ]);
 It returns string representation of array elements.

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[ ] a={23,93,65,35,89};
String s1 = Arrays.toString(a);
System.out.println(”Beforesorting…..”);
System.out.println(s1);
Arrays.sort(a);
String s2 = Arrays.toString(a);
System.out.println(“Aftersorting…”);
System.out.println(s2);
}
}
class Demo
{
int[ ] getElements()
{
int[ ] a={23,45,93,67,88,65,45,76};
return a;
}
public static void main(String[] args)
{
Demo d = new Demo();
int[ ]=d.getElements();
for(int y:x)
{
System.out.println(y);
}
}
}
Two Dimensional Arrays: -
Declaration: -
Syntax: -
DataType ArrayReference[ ][ ] = new DataType[rows][cols];
Example: -
int a[ ][ ]=new int[3][3];
(OR)
int [ ][ ]a=new int[3][3];
(OR)
int[ ][ ] a=new int[3][3];
(OR)
int [ ]a[ ]=new int[3][3];
(OR)
int [ ] a; a=new int[3][3];
Assignment: -
Syntax: -
ArrayReference[row-index][col-index]=Literal;
Examples: -
a[0][0]=34;
a[0][1]=93;
a[0][2]=98;
a[1][0]=92;
a[1][1]=85;
row index

int[ ][ ] object col index


0 1 2
a 0 1 2 0 1 2 0 1 2
0 34 0 93 0 98 0 92 0 85 0 0 0 0

element
Initialization: -
Syntax: -
DataType ArrayReference[ ][ ]=new DataType[ ][ ] { Literal1,
Literal2,……},{Literal1,Literal2,…..},…..};
Example: -
int a[ ][ ]=new int[ ][ ]{{2,4,6},{3,9,5}};
(OR)
int a[ ][ ];
a=new int[ ][ ]{{23,49,45},{98,93,66}};
(OR)
int a[ ][ ]={{23,45,66},{93,45,77}};

class Demo
{
public static void main(String[] args)
{
int[ ][ ] a={{23,45,66},{23,45,55},{34,34,34}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+” “);
}
System.out.println();
}
}
}
Jagged Arrays: -
If the array created with different no.of columns in each row, then it is said to
be Jagged array.
Declaration: -
Syntax: -
DataType ArrayReference[ ][ ]=new DataType[rows][ ];
ArrayReference[row-index]=newDataType[cols];

Example: -
int a[ ][ ]=new int[3][ ];
a[0]=new int[3];
a[1]=new int[4];
a[2]=new int[2];

Initialization: -
DataType ArrayReference[ ][ ]={{Literal1,Literal2,….},{Literal1,Literal2,….}…};
Example: -
int a[ ][ ]={{34,39,13},{23,45,66,36},{23,45}};

class Demo
{
public static void main(String[] args)
{
int[ ][ ] a=new int[ ][ ]{{23,45,66},{23,45,55,44},{34,34}};
for(int i=0;i<a.lenght;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.println(a[i][j]+” “);
}
System.out.println();
}
}
}
class Demo
{
public static void main(String[ ] args)
{
int[ ][ ] a=new int[ ][ ]{{23,45,66},{23,45,55,44},{34,34}};
for (int b[ ]:a)
{
for(int c:b)
{
System.out.print(c+” “);
}
System.out.println();
}
}
}

You might also like