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

Java

For 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

Nope, all objects, if not initialized, will have a value of null, which is different from 0, you have to give it a start value

but isn´t it a primitive data type? and therefore not an object?

"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

Not exactly, what I was thinking was for (int i; i< Foo, i++) {} Why can't I declare the variable i and not initialize it?

Because '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 :)

so why do these default values exist? When do I use them? https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Right 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.

Understood! thanks! :) Lukas Baumgartner