Java12 03
Java12 03
Java12 03
PAARAUJO@GMAIL.COM
SEPTEMBER 2021 SESSION 03
Example:
27 12 82 70 54 1 30 34
First Element
index at index 5
00 1 2 3 4 5 6 7 Indices
27 12 82 70 54 1
1 30 34
Array length is 8
(ages.length)
type [] array_identifier;
• Syntax:
• Examples:
• Syntax:
array_identifier[index] = value;
• Examples:
int [] ages = {19, 42, 92, 33, 46};
Shirt [] shirts = {new Shirt(), new Shirt(), new Shirt()};
int [] ages;
ages = {19, 42, 92, 33, 46};
• Setting a value:
status[0] = '3';
names[1] = "Fred Smith";
ages[1] = 19;
prices[2] = 9.99F;
• Getting a value:
char s = status[0];
String name = names [1];
int age = ages[1];
double price = prices[2];
Primitive variable
of type char
0x034009
size L 0 S
1 M
sizes 0x034009
2 L
Primitive variable
of type char held
as array element
0 shirtID
myShirt 0x034009 0.0 price
U colorCode
0 shirtID
0.0 price
U colorCode
Integer.parse
int arg1 = Integer.parseInt(args[0]); Int() converts to
int arg2 = Integer.parseInt(args[1]); int.
System.out.println("Total is: " + (arg1 + arg2));
}
Note
Note parentheses.
parentheses
}
Wednesday
Thursday
Saturday
Tuesday
Monday
Sunday
Friday
Week 1
Week 2
Week 3
Week 4
• Example:
int [][] yearlySales;
• Example:
• yearlySales[0][1] = 1500;
• yearlySales[0][2] = 1800;
• yearlySales[1][0] = 1000;
• yearlySales[3][3] = 2000;
Quarter 1 Quarter 2 Quarter 3 Quarter 4
Year 1 1000 1500 1800
Year 2 1000
Year 3
Year 4 2000
Year 5
• Arrays are not the only way to store lists of related data:
• ArrayList is one of a number of list classes.
• It has a set of useful methods for managing its elements:
• add(), get(), remove(), indexOf(), and many others
• You do not need to specify a size when you instantiate an ArrayList:
• As you add more elements, the ArrayList grows as necessary.
• You can specify an initial capacity, but it is not mandatory to do so.
• An ArrayList can store only objects, not primitives.
import java.util.ArrayList;
public class ArrayListExample {
public static void main (String[] args) {
ArrayList myList;
}
}
Declare a reference.
ArrayList myList;
myList.add("John");
myList.add("Ming"); Initialize the ArrayList.
myList.add("Mary");
myList.add("Prashant");
myList.add("Desmond");
myList.remove(0);
Modify the ArrayList.
myList.remove(myList.size()-1);
myList.remove("Mary");
System.out.println(myList);