Krivalar Tutorials
Krivalar Tutorials

Java - Working With Arrays

Array Declaration

Arrays can be declared as shown below

``````
byte by[]={56,67,5};
short sh[]={678,300,787,677};
int num[] = {4,5,6,7,8,10};
long numbers[]="567000000L,56L,8500L,456L};

char vowels[]={'a','e','i','o','u'};

float prices[]={45.25f,56.75f,78.90f,1003.55f,800.35f,1.25f};
double amounts[]={5600.67,67.89};

boolean states[]={true, false, false, true};

String expression[]= {"Calm","Awesome","Lovely","Fantastic"};
``````

Accessing Array Elements

Array elements can be printed out using a for loop.

``````
public class ArrayInLoopExample {
public static void main(String a[]){
int num[] = {4,5,6,7,8,10};
for(int i=0;i<num.length;i++){
if(i==0){
System.out.print(num[i]);
}
else{
System.out.print("," + num[i]);
}
}
}
}
``````

Output

```4,5,6,7,8,10
```

Accessing Array Elements in Reverse Order

Array of numbers can be traversed one by one and one printed in reverse as well.
``````
public class ArrayReverseTraversal {
public static void main(String a[]){
int num[] = {4,5,6,7,8,10};
for(int i=num.length-1;i>=0;i--){
if(i==0){
System.out.print(num[i]);
}
else{
System.out.print(num[i]+"," );
}
}
}
}
``````

Output

```10,8,7,6,5,4
```

Two Dimensional Arrays

Data can be stored in two dimensional arrays and printed using nested for loops
``````
public class TwoDArrays {
public static void main(String a[]){
int num[][] = { {0,1},{1,2},{3,4},{6,7},{10,10} };
int arrSize=0;
for(int i=0;i<num.length;i++){
for(int j=0;j<num[i].length;j++){
if(j==0){
System.out.print(num[i][j]);
}
else{
System.out.print("," + num[i][j]);
}
}
System.out.println("\n");
}
}
}
``````

```0,1

1,2

3,4

6,7

10,10
```

Three Dimensional Arrays

Data can be stored in three dimensional arrays and printed using nested for loops In the below, Strings are stored in 3 dimensional arrays and printed using for loops
``````
public class ThreeDArrays {
public static void main(String a[]){
String wordSet[][][] = { { {"Nice","Wonder"},{"Stupid","Wise"} },
{ {"Boy","Girl"} },
{ {"Poda","Podi"},{"Courage","Beauty","Urban"} }
};
int arrSize=0;
for(int i=0;i<wordSet.length;i++){
for(int j=0;j<wordSet[i].length;j++){
for(int k=0;k<wordSet[i].length;k++){
if(k==0){
System.out.print(wordSet[i][j][k]);
}
else{
System.out.print("," + wordSet[i][j][k]);
}
}
System.out.print("\t");

}
System.out.print("\n");
}
}
}
``````

Output

```Nice,Wonder	Stupid,Wise
Boy
Poda,Podi	Courage,Beauty
```