Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Gergő Endrész
Gergő Endrész
7,169 Points

Why do we have to initialize variables?

Hi, just wondering why the "treets" variable was initialized in the load() method. It throws an error if it isn't, but I still don't get it when I am supposed to initialize a variable and how(for example different types than an Object array).

Here is the code snippet which I am referring to: public static Treet[] load(){ Treet[] treets = new Treet[0]; //Initialize treets try{ FileInputStream fis = new FileInputStream("treets.ser"); ObjectInputStream ois = new ObjectInputStream(fis);
treets = (Treet[]) ois.readObject(); ... Also, why was it initialised as an empty array?

2 Answers

Fahad Mutair
Fahad Mutair
10,359 Points

hi Gergő Endrész , It's default array that has no elements inside it , the purpose of using it to cast the object of ObjectInputStream readObject method to get Treet type and then assign it to that array again.

It's a useful way to use Array objects in binary files.

Also you can assign it to null instead of Treet[0]

Treet[] treets = null; // this way
Treet[] treets = new Treet[0]; // or this 

Also someone asked same question but different point heres link to it

Gergő Endrész
Gergő Endrész
7,169 Points

Cheers for the prompt answer.

Richard Lambert
PLUS
Richard Lambert
Courses Plus Student 7,180 Points

Hello mate,

By default, reference-type member variables that are not explicitly initialized, are implicitly assigned a value of null. This is in contrast with locally declared variables within a method that aren't implicitly assigned a default value. It is for this reason that you will often see them explicitly initialized with a value of null; to prevent an error being generated along the lines of "suchNsuchVariable may not have been initialized".

Hope this helps