forked from akash-coded/core-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleDimensionalArray.java
More file actions
69 lines (56 loc) · 1.81 KB
/
SingleDimensionalArray.java
File metadata and controls
69 lines (56 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.lang.reflect.Array;
public class SingleDimensionalArray {
public static void example1() {
int[] array; // declaration
array = new int[5]; // instantiation
// initialization
array[0] = 10;
array[1] = 20;
array[2] = 30;
array[3] = 40;
array[4] = 50;
// accessing
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
System.out.println(array[3]);
System.out.println(array[4]);
}
public static void example2() {
int[] array = { 10, 20, 30, 40, 50 }; // declaration, instantiation and initialization
// traversing
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static void example3() {
int[] array = { 10, 20, 30, 40, 50 }; // declaration, instantiation and initialization
// using foreach loop to traverse an array
for (int element : array) {
System.out.println(element);
}
}
public static void example4(int[] arr) {
arr[0] = -1;
// using foreach loop to traverse an array
for (int element : arr) {
System.out.println(element);
}
}
public static int[] example5() {
int[] array = { 10, 20, 30, 40, 50 }; // declaration, instantiation and initialization
array[2] = -2;
return array;
}
public static void main(String[] args) {
// example1();
// example2();
// example3();
// example4(new int[] { 10, 20, 30, 40, 50 }); // anonymous array
int[] array = example5();
// using foreach loop to traverse an array
for (int element : array) {
System.out.println(element);
}
}
}