Introduction to Java
Jim White
Java Developer
[]
// Declare array variable int[] prices;
// Assign value prices = {10, 20, 30, 40};
[]
:int[] prices = {10, 20, 30, 40};
// Accessing first element
int firstElement = prices[0]; // Value is 10
// Accessing second element
int secondElement = prices[1]; // Value is 20
int[] prices = {10, 20, 30, 40};
// Change value of third element to 95 prices[2] = 95;
int[] itemIDs = {10, 20, 30, 40, 50};
// Accessing sixth element that isn't there
itemIDs[5] = 60; // <- This will cause an error
.length
propertyint[] prices = {10, 20, 30, 40};
int pricesLength = prices.length; // Value is 4
We can print out individual values:
class ArrayElementPrinting {
public static void main (String[] args){
int[] prices = {10, 20, 30, 40};
// Printing element by element
System.out.println(prices[0]);
System.out.println(prices[1]);
}
}
10
20
Printing whole array returns representation:
class ArrayPrinting {
public static void main (String[] args){
int[] prices = {10, 20, 30, 40};
// Printing whole thing
System.out.println(prices);
}
}
[I@d041cf
// Array of Strings
String[] productNames = {"Organic Honey",
"Cold Brew Coffee",
"Dark Chocolate Bar"};
Strings
// Declare and assign
int[] prices = {10, 20, 30, 40};
// Retrieve
int secondElement = prices[1];
// Update
prices[1] = 25;
// Length
// Value is 4
int pricesLength = prices.length;
Introduction to Java