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! While you're at it, check out some resources Treehouse students have shared here.
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
Tomás Borges
4,394 PointsFor loop
Why do I need to initialize the int i (int I =0;) in the standard for loop ? Don't int variables have 0 as default value?
4 Answers
Marleen Berg
22,524 PointsNope, all objects, if not initialized, will have a value of null, which is different from 0, you have to give it a start value
Lukas Baumgartner
14,817 Points"The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name." https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
I suppose you want to write a for loop like that:
for(i < Foo; i++){}
You must admit that wouldn't make any sense at all
Tomás Borges
4,394 PointsNot exactly, what I was thinking was for (int i; i< Foo, i++) {} Why can't I declare the variable i and not initialize it?
Lukas Baumgartner
14,817 PointsBecause 'i' would be Null if you don't give it a value.
You just reserve some space in memory for an int variable, and giving it a name to make it more humanly readable. But it has no value if you don't specificallly give it one.
Just think it through. i = Null(not the number zero but null as nothing, or empty)
is Null(or nothing or empty) greater or smaller Foo(that has let's say the value 5)? That question doesn't really make sense, does it?
Maybe it's hard at the beginning to wrap your head around it, but trust me, as you use it more often, it gets clearer and clearer to you :)
Tomás Borges
4,394 Pointsso why do these default values exist? When do I use them? https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Lukas Baumgartner
14,817 PointsRight below the table with default values there is a paragraph that says:
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
Tomás Borges
4,394 PointsUnderstood! thanks! :) Lukas Baumgartner
Tomás Borges
4,394 PointsTomás Borges
4,394 Pointsbut isn´t it a primitive data type? and therefore not an object?