-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraysinjava.java
More file actions
71 lines (46 loc) · 2.08 KB
/
Arraysinjava.java
File metadata and controls
71 lines (46 loc) · 2.08 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
70
71
import java.util.Arrays;
public class Arraysinjava {
// array is a collection of values of homogenous data type
// => variable that can store more than one value
// it's a reference type of data type ... stores the memory address not the values
//
// datatype [] nameOfArray={"values", "values", "values", "values"};
// String [] fruits= {"apple","orange","banana", "coconut"};
// the values in an array are called elements
// they are accessed using index numbers with the first index being index 0
// fruits[1]
public static void main(String []args){
// creating an array
String [] fruits= {"apple","orange","banana", "coconut"};
// printing an arrays out= arraybname[index]
System.out.println(fruits[0]);
// changing value of a given index
fruits[0]="Guava";
System.out.println("changed value of index 0");
System.out.println(fruits[0]);
// getting the lenth of an array== to numbmerr of elements in an array
int length= fruits.length;
System.out.println("the elngth of the array is:"+length);
// printing out all the elements of an array
// FOR LOOP
System.out.println("Printing all elements of an array using for loop");
for(int i =0; i<fruits.length;i++){
System.out.println(fruits[i]);
}
// ENHANCED FOR LOOP/for each loop
System.out.println("Printing all elements of an array using an enhanced for loop /for each loop");
for (String fruit: fruits){
System.out.println(fruit);
}
// Sorting arrays
// we use the Sort method in the Array class
// we therefore have to import the arrays class
Arrays.sort(fruits); // sorts alphabetically
// filling an array with a given value...
// Arrays.fill(arrayName,value);
Arrays.fill(fruits,"Pineapple");
for (String fruit: fruits ){
System.out.println(fruit);
}
}
}