Reputation: 195
class Main {
public static void main(String[] args) {
int x = 3;
int [] a = new int [x];
x+=5;
System.out.println((x+=5));
System.out.println(a.length);
}
}
Why doesn't it effect the length of array "a" ? What am i doing wrong?
The thing is I was asked to add 5 to the length of an array using a loop. I can't even increase the length directly. It looks like a simple issue but I'm still in learning process. I did it yesterday but I don't remember how.
Upvotes: 1
Views: 196
Reputation: 1435
Ok, I sum up to give you a more complete answer:
First, when you initialize an array, you assign a defined/finite chunk of memory to it. If you want to change the length of such an array in Java, you need to initialize a new one. There are no retrospective automatic reinitialization of arrays in Java. Other languages might do something something similar for you, but Java doesn't.
Second, you pass the x
in your array-initialization by value which means, the functionalities, which create your array, receive the value ones but not the memory address. Methods in Java do it likewise: You pass values as parameters to them but they cannot see the variables directly as long as you don't explicitly reference to them in your local environment of each method. This is why no function, which accepts parameters, is directly influenced by changes of the variables from which values have been passed.
Third, if you try to change the size of an array often, you should consider using ArrayLists which include the functionality which you are looking for.
Forth, if you want to keep using arrays instead of something else and want to keep the array members/values, you still need to pass the old array content to a new initialized array. This can be achieved by looping through the old array.
Upvotes: 1
Reputation: 7889
You cannot increase the size of an array directly. You will learn about ArrayList
s later. You can reassign an array variable to a new array; the length is not part of the array type. So, let's break this up into steps.
5
to that variable.for
loop, though System.arrayCopy
is shorter.List
and ArrayList
documentation so you see how people do this in practice.When you work on exercises like this, always break it down into individual steps first. When you program, break your methods into individual methods that do just one thing.
Upvotes: 1
Reputation: 5139
You are just changing the value of x, you also have to reassign this value to change the array length.
int x = 3;
int[] a = new int[x];
x += 5;
a = new int[x];
System.out.println(a.length);
Upvotes: 6
Reputation: 2739
First of all, what are you trying to achieve?
The length of your will be equal to the x value during the array creation (second line at your code),
if you want to use dynamic array you should consider to use java.util.ArrayList
.
Upvotes: 0
Reputation: 8337
Merely changing value of x is not going to help,
You need top explicitly assign modified value back in array
Upvotes: 1