my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Problem with arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with arrays" Watch "Problem with arrays" New topic
Author

Problem with arrays

Soma RaviKumar
Greenhorn

Joined: Jan 03, 2006
Posts: 6
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

Joined: Jan 13, 2002
Posts: 732
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

Joined: Aug 31, 2004
Posts: 11343

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 };


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Soma RaviKumar
Greenhorn

Joined: Jan 03, 2006
Posts: 6
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

Joined: Dec 21, 2005
Posts: 70
Hi Soma,
Arrays are Objects so they are no different than other objects.
regards
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with arrays
 
Similar Threads
(re)assigning arrays?
arrays
My Array Notes Correct Me if i'm wrong
arrays are like strings which are objects!
getting values from for loop