• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with arrays

 
Soma RaviKumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am a java newbie and I couldn't find answer to this situation in any of the books available in my college. Please help understand this.

How is it that I am not able to assign values to arrays outside of a method?

class TestArrays
{
int classid;
int studentids[]= int[10];

classid = 10; // I can assign values to this without a problem
studentids[0] = 20; /** I can't do this..Why? I can do this with out a problem if I put this in a main method or any other method.*/

}
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello .

First there are a few compilation errors in your code before that line.
Here is the correct version (until the line you asked):

Now to your question:

You can only initialize variables outside a method in a class when you declare them.
Because you declared the array in one line (you initialized it there), you can't assign to it stuff in other line if they are not in a method.
Same goes for the classid variable.
You can however do these linea:


Notice that this way we initialize the variables in the same line we create them.
Otherwise, you have to that in the contsructor or in a method.

check this urls for more info:
url1
url2
[ January 03, 2006: Message edited by: Roy Ben Ami ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When declaring a variable, you can assign a value at the point of declaration. But note that the variable here is "studentids," so you're providing a "value" (an object reference) for the array itself -- not the values (references) it holds.

Note that in the case of arrays, you have the option of using a "short-cut" syntax...

int[] studentIDs = { 10, 20, 30, 40, 50 };
 
Soma RaviKumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your quick reply. I have one more question regarding this.
Is an array created on STACK or on HEAP ?
I know that the objects are created on HEAP and the references to it reside on STACK.
In the case of arrays, what is on STACK and what is on HEAP?
Thanks again.
 
vivekkumar sharma
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Soma,
Arrays are Objects so they are no different than other objects.
regards
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic