Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Gergő Endrész
7,169 PointsWhy 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
10,359 Pointshi 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

Richard Lambert
Courses Plus Student 7,180 PointsHello 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
Gergő Endrész
7,169 PointsGergő Endrész
7,169 PointsCheers for the prompt answer.