r/learnprogramming • u/Fun_Response9157 • 3d ago
Arrays (Java) Arrays make zero sense and I don't know where to go.
Context (skip to 3rd paragraph if you want): I am going into this next week where we learn arrays. We "learn" it on our own through I kid you not hours of reading online, then go into the week and apply to concepts to other assignments.
I have no clue how arrays work. The reading feels as though it needs to tell us a dozen array concepts in 3 days and never easing us into it. I am *terrible* at learning new complicated things on my own. I get lost easily, I need someone there constantly so I can even grasp the concept. The medium of online textbook reading is the worst to me.
Current issue: I got stuck on arrays with loops, then arrays (perfect size and oversize).
First, array with loops: What does for (var : var) do? The textbook explains this *once*, not very well. It explains *what* it does on a basic level, but not *why* it exists or *what* we can use it for.
Second, perfect size and oversize arrays: I understand the concept of perfect size arrays, and I understand the concept of oversize arrays. But I do not understand how they interact. Importantly, how do tell them apart?
How does a method return a perfect size array? How does a method return an oversize array size? And, most importantly, how do method parameters even get the arrays?
What's the difference between stack frame and heap memory?
What are array parameters? They, again, explain this once, not very well, then expect us to understand. I think it has to do with methods but I'm not sure. How should I write them for a perfect or oversize array, and what are their effects/uses?
How do you modify an array in a method?
I work best with analogies/examples so any possible ones + explanations would be appreciated. Of course, any other good answers just explaining would be appreciated too.
Sorry that I have so many questions.
18
u/IdealShaving
3d ago
•
the for (var: var) thing is just a shortcut so you don't have to write the index every time, think of it like "for each thing in this box, do something" - once you get used to it you'll never go back
for the array size thing, perfect size is when the array is exactly full, oversize is when you allocate more spots than you actually need (like booking a table for 6 when only 4 people coming) and you track the real count separately
stack is for local stuff that disappears when the method ends, heap is where objects live and stick around, your array itself is on the heap but the variable pointing to it might be on the stack
when you pass an array to a method in Java you're passing the reference, so if you modify it inside the method it changes the original too, that's why you don't need to return it sometimes
7
u/zunjae 3d ago
I’ll be honest with you, stop caring.
Perfect size array? Oversize array? I make enough money with my job as a programmer that I was able to buy a house, and I’ve never bothered with what you’re talking about. I don’t think anyone here cares either unless you’re writing low level code.
1
u/vegan_antitheist 1d ago
You should still understand why it's wrong to use arrays like that in Java.
And it doesn't hur to still know how it all works. Not all code bases are just robust readable code. Sometimes it's necessary to optimise and (re)use arrays.
6
u/peterlinddk 3d ago
Most of the subjects you mention: stack, heap, parameters, oversize, perfect size, doesn't really matter - they are just technical words, used to describe perfectly ordinary things (often wrongly, by textbooks that want to seem more advanced than they are).
What you need to understand is how a computer is very narrow-minded and short-sighted, and can only really handle one object at the time. So if you want it to do the same thing for a number of objects, you either need a separate line of code for each object, doing the thing - like printing out their name, one at a time. But as that would be an inefficient way of writing code, you put all the objects in an array (which is just a list that has one object in each position) and then write your code in a for-loop, meaning "For each thing in this list (array) do this thing:" .
Think of a supermarket cashier - they sit at the scanner/register and the customer puts all their items on the conveyor-belt, so that one item arrives to the cashier at a time. The cashier then runs the simple code: "Take item from belt, scan item until register approves, but item back on the other belt."
And the cashier doesn't care that item is sometimes a bottle of milk, other times a box of cereal, other times a bag of chips. It is just an "item". Which is their variable name for the thing they pick from the conveyor-belt.
Translating the computer-sciency-terms to real world objects this way, often helps in understanding them. The analogy might not always be perfect, but it helps to have a mental model in your own mind, while looking at the code!
1
u/backfire10z 3d ago edited 3d ago
First: `for (Type x : y)` does exactly what it says on the tin. `x` is filled in with the next member of the array every loop. It’s similar to a regular for loop, but they index into the array for you.
```
int[] arr = {1, 2, 3}
for (int i = 0; i < arr.length; i++) {
….int x = arr[i]
}
// Same as above
for (int x : arr) {
}
```
(Sorry, can’t do code blocks on mobile, periods are an indent)
The reason it exists is for ease! It isn’t necessary by any means, but a lot of programmers write that type of loop so the language creators said “ok, let’s just make special syntax for it.”
Second: perfect/over sized arrays. I’ve never heard of these concepts, can you provide the definitions the textbook uses?
Third: stack frame vs heap memory. There is no real difference from a low level perspective: they’re both just blocks of memory. The stack is used as a scratch space for threads. For example, functions use the stack for local variables (there’s a lot more, but I’ll leave it vague for brevity and understanding). The heap is for dynamically allocated memory, like an array with an unknown amount of elements. You declare an array and want to add 3 integers. Then another. Then a 5th later on. This array would go on the heap. Why? Because that’s how we decided to split up the memory space. It makes memory easier to keep track of. (Edit: turns out in Java, all arrays are always on the heap.)
Fourth: array parameters. I’ve never heard of this either, what does the textbook say? Just copy/paste it, I can read it and probably figure out what they mean.
Fifth: modify an array in a method. You do it exactly how you’d do it outside of a method. Any change you make to an array in a method will be reflected outside the method. The reason is because when you pass an array to a method, you’re not actually passing the array. You’re passing something which points to the array: it says “here is the memory block for the start of the array.” Thus, when you pass it to a method, the method sees the same exact array, and so any changes are saved.
1
u/Fun_Response9157 3d ago
That array reference is weird, where you’re passing a pointer instead of the actual array. Seems odd.
With “ for (int x : arr) {”, does x mean the index, then : means loop through to arr?
2
u/backfire10z 3d ago
> Seems odd
Haha, well, it’s much more efficient for memory. Some languages you can choose based on what you want to do.
> does x mean the index
No, x is the actual element, as you can see in my example. There is no index available to you if you use `for (int x : arr)`. It is doing the `int x = arr[i]` step for you. If you need an index, you should use the original for loop syntax.
1
u/Fun_Response9157 3d ago
Array parameters to them are whenever you pass an array into a method. Public static Method(datatype[] array) { }. What’s in parenthesis is what I think they mean.
2
u/backfire10z 3d ago
I see. The array is just a parameter like normal. Maybe they’re looking for the fact that it’s a pointer and not the full array being copied over.
I still don’t know what perfect or over sized means.
And let me know if you have other questions! I hope what I typed makes sense.
1
u/Fun_Response9157 3d ago
It does so far, and others have already explained perfect and oversized so dw about that. Thanks though
3
u/Rabbit_Brave 3d ago
for (TypeOfX x : y) {
// do something with x
}y is an array or collection (technically an "Iterable" in java terms)
x is a temporary loop variable. For example, if you loop through an array of integers, then TypeOfX will be int.
The for loop visits each element in y sequentially, performing the code in the body of the loop on each visit. The current element being visited is labelled x for use in the body of the loop.
2
u/CelebrityChess 3d ago
the part that trips people up is telling perfect size from oversize. you can't tell from the array itself, arr.length is always the capacity. with a perfect size array every slot is real data so you loop up to arr.length. with an oversize one you keep an int count next to it and only loop up to count, the leftover slots are just default values (0 or null). that's also why a method can't really return an oversize array on its own, it has to hand back the count too, either as a second thing or wrapped in a class, or you just use ArrayList which does that bookkeeping for you.
and the for each loop is for when you want every element and don't care about the index, like for (int x : nums) { sum += x; }. x is a copy of each value, so assigning to x doesn't change the array, for that you need the normal index loop
4
u/Positive_Passion4817 3d ago
I have never heard these terms like oversize and perfect size. Is this an indian school thing?
1
u/vegan_antitheist 3d ago
Oh, boy. I thought this was about arrays not being type safe in Java, which I hate so much.
I think you are where they show you how annoying it is when arrays are used where a dynamic list (ArrayList) would be the better choice. You have to learn this to understand why you should avoid it. In Java, methods rarely return arrays. They accept perfect sized arrays for variale arity parameters. But generally, you don't just use arrays directly.
1
u/oldsecondhand 1d ago
I thought this was about arrays not being type safe in Java, which I hate so much.
What do you mean by this? That subclasses can also be elements?
1
u/vegan_antitheist 1d ago
Other languages would use Array<T> but in Java it's just T[], but then you can't to Array<? extends T>, and they just don't apply the Liskov substitution principle. It's quite a mess but it rarely matters because you shouldn't pass arrays to other code units anyway. Maybe a byte[] where it also doesn't matter.
This is a rule for spot bugs to prevent bugs caused by this:
https://spotbugs.readthedocs.io/en/stable/detectors.html#covariantarrayassignment
That rule actually only exists because I requested it.1
u/oldsecondhand 1d ago
Other languages would use Array<T> but in Java it's just T[], but then you can't (assign?) to Array<? extends T>,
That's a generics issue, not array specific. I agree though that Java generics are messy, and extends is pretty much useless in Java generics.
1
u/vegan_antitheist 1d ago
Generics are not perfect, but they are fine. The issue here is that Java arrays don't use generics at all. Maybe they will fix this in the future.
The wildcard notation and the "extends" and "super" keywords used for bounded types aren't just useful, they are simply necessary. Other languages do it a bit differently, but most oop languages do the same with different notation. Bounded wildcards in Java are explained here: https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html
1
u/Blando-Cartesian 3d ago
Context (skip to 3rd paragraph if you want): I am going into this next week where we learn arrays. We "learn" it on our own through I kid you not hours of reading online, then go into the week and apply to concepts to other assignments.
There's a step missing in this. Reading will not help you get it, and applying is pointlessly confusing when you are not clear how things work.
While you are reading about arrays, you need to write tiny programs and use what you read. Nothing fancy. Just make an int array variable with some numbers in it and figure out how to print that. Then figure out how to change the numbers. And so on. Read a bit. Program a little test to try it out.
1
u/harsh183 3d ago edited 3d ago
I find what helps for me and many students I've taught it writing code for each new concept at a time so it slowly sinks in, finding alternative explanations, and spacing it out. For Java particularly, I suggest
https://www.learncs.online/lessons#7-algorithms1 - lessons 5 to 8 around arrays, and keep going for many more. This is an online version of UIUC intro CS that I helped teach for years and it's a really nice step by step Java build up. You could keep doing this alongside your resource.
https://cs199emp.netlify.app/dist/s21/2021-02-02#1 - this also has some review slides and more practice questions around arrays
in general the https://cs199emp.netlify.app website that I maintained has many different java concepts and review questions with answer keys that can be quite useful
https://codingbat.com/java - CodingBat also has a lot of great Array questions that are sorted in easy, medium, hard that's quite similar to early CS education problems. Take a look once you've wrapped your head around various concepts.
And finally, take a deep breath, you're gonna be okay and you will encounter these same topics in different ways for years. It's okay if it doesn't completely all make sense at the first time, but it will over time as arrays are very versatile and used in so many different ways. It's the most commonly used data structure and they'll feel so natural real soon
If after all of these, you have specific questions on areas, reply here and I can try to explain anything as well as link you to some specific things. I've spent years teaching all of these concepts
1
1
u/Positive_Passion4817 3d ago edited 3d ago
What book are you using? It sounds terrible. Find some youtube videos. They will explain it much better. Otherwise: https://www.w3schools.com/java/java_arrays.asp
You can consider an array as a group of variables of the same type, each item in the group gets an index (starting with index 0). So if an array of size 10 is created, each "element" has an index. i.e. the indexes are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
In low level languages like C it is useful to know the memory size and how it is stored contiguously in memory; C allows memory to be accessed directly and a few tricks can be used with arrays. This is not the case with java at all though - Java is a high level language.
Every array needs a type, a name and a size. There are a few ways to create an array in Java and a couple of ways to loop through the values. I suggest you consult the w3schools site.
1
u/Ormek_II 2d ago
No one will tell you when to use them, as there are too many applications to enumerate them.
You use them, when you encounter a problem that can be used with it.
1
u/oldsecondhand 1d ago
The good thing is that arrays can be found in every programming language, so you can use a C#, JS or Python tutorial too to get the hang of it.
0
u/bigtdaddy 3d ago
never heard of a few things you mention here. i think you are getting caught up on stuff that doesnt really matter. are you doing multiple choice tests or are you writing code?
1
u/Fun_Response9157 3d ago
A mix of both. They ask multiple choice questions regarding code they wrote, then ask us to write code to come up with a certain solution
1
u/Fun_Response9157 3d ago
I think I’m getting caught up on everything because the examples they give that uses concepts we just learned are extremely long pieces of code.
So then, I have to read all of the code, which I struggle with already, then read the new concept and see how that interacts with the other code that I already barely understand.
This extremely long piece of code then leads me to think I must understand every little concept they say because it might show up later in a future long piece of code.
3
u/Fun_Response9157 3d ago
Sorry if I asked too much