Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import java.util.

*;
// Arrays allow us to group together variables of the same type and similar
// function under one name.
public class JavaArrays {
public static void main (String [ ] args)
{
Scanner input = new Scanner(System.in);
// To create an array, add square brackets after the variable ty
pe,
// then use new to specify the type and size
int x; // single value
int [ ] y = new int[10]; // array to hold 10 int values
// To add/update a value inside an array, put its index (positio
n)
// inside square brackets following the array name. Indices star
t at 0.
y[3] = 25; // fourth element
y[0] = -14; // first element
// Use the length field to get the total size of an array (this
ignores
// whether a given position is empty)
System.out.println("y is " + y.length + " elements in size");
// Loops go hand-in-hand with arrays
for (int i = 0; i < y.length; i = i + 1)
{
y[i] = y[i] + 15;
}
System.out.println("Contents of array y:");
System.out.println(y); // uses (useless) default toString() code
printArray(y);
// An initializer list allows us to pre-specify the size and val
ues
// for a new array. THIS CAN ONLY BE DONE WHEN THE ARRAY IS DECL
ARED!!!!!!
String [ ] names = {"John", "Mary", "Bob", "Sue", "Harry", "Dian
e"};
System.out.println("names.length is " + names.length);
printArray(names);
}
// We must define/provide a method to print the contents of an array
static void printArray (int [ ] list)
{
System.out.print("[");
for (int i = 0; i < list.length; i = i + 1)
{
System.out.print(" " + list[i]);
}

System.out.println("]"); // close and go to next line


}
// Overloaded version of printArray()
static void printArray (String [ ] list)
{
System.out.print("[");
for (int i = 0; i < list.length; i = i + 1)
{
System.out.print(" " + list[i]);
}
System.out.println("]"); // close and go to next line
}
}

You might also like