Skip to content

Instantly share code, notes, and snippets.

@tobyink
Created February 7, 2019 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobyink/b34821c7c552760349156b3e9dfe16c6 to your computer and use it in GitHub Desktop.
Save tobyink/b34821c7c552760349156b3e9dfe16c6 to your computer and use it in GitHub Desktop.
Example of using arrays in Java
/* I'm not very good at Java */
class Example {
public static void main(String[] args) {
exampleWithoutArray();
exampleWithArray();
}
public static void exampleWithoutArray () {
int i1 = 1;
int i2 = 2;
int i3 = 3;
int i4 = 4;
int i5 = 5;
int i6 = 6;
int i7 = 7;
int i8 = 8;
int sum = i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8;
System.out.println(sum);
}
public static void exampleWithArray () {
int[] iList = { 1, 2, 3, 4, 5, 6, 7, 8 };
int sum = 0;
for (int i : iList) { sum += i; }
System.out.println(sum);
}
}
/* I mean, the example using the array isn't much easier
when you're adding together eight numbers. If you were
adding 1000 numbers though! Or adding together a list
of numbers where you don't know in advance how many there
will be because you've read them from a file or something.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment