+ 3
What in the world are arrays in Java?._.
I have no clue how arrays contribute to the code and how they work. When to use them also really confuse me. The lesson gives an example: "arr[2] = 42;" Why does 2 equal 42?!? Why are there brackets around them instead of just printing out 42? Thank you if u can help me!
3 Answers
+ 2
int myArray[5]
// how you can imagine in memory [] [] [] [] [] []
0 1 2 3 4 5
Indexes on the bottom, values inside box. boxes are empty on creation of array. Array tells program to allocate memory for 5 integers, ie makes boxes in memory for integers and index them.
if you want to put a int inside the box, myArray[2] = 35;
// how you can imagine in memory [] [] [35] [] [] []
0 1 2 3 4 5
You cannot put a char like 'H' inside the box, because the array is INT type. you must create a char array if you want the boxes to hold char.
if you still dont understand, you are thinking too hard. very simple.
+ 1
Arrays are like tables,
Arrays values starts from 0.
In your example "arr[2] = 42;" it means "set the third array value to 42.
int arr[] = new int[5]; //You define new array with 5 values.
arr[2]=42; //You set third(because you start from zero, like 0, 1, 2) value as 42
+ 1
Arrays are just a group of elements (String, int, float, etc) that are stored togheter.
Your array "arr" has a 42 (which might be an int, by the looks of it) stored in the third place (0 is the first, and the maximum is the one you set when you initialize the array).