Forums Register Login

How come you cant print a default variable value?

+Pie Number of slices to send: Send
oracle notes say:

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

but why cant you then print out say...

int testNumber;

System.out.print (testNumber);

shouldnt it print 0...if its a field,local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable.

just wondering...thanks
+Pie Number of slices to send: Send
this code did work though



got 10 ...so numberTest got assigned 0 by default.

does this only happen with static/class variables/fields?

+Pie Number of slices to send: Send
 

jon ninpoja wrote:
does this only happen with static/class variables/fields?


Yes, only those will be initialized with default values. Local variables have to be explicitly initialized before you use them.
+Pie Number of slices to send: Send
hi Junilu Lacar

a local variable is any variable thats in a method right?
+Pie Number of slices to send: Send
 

jon ninpoja wrote:
a local variable is any variable thats in a method right?



A local variable is a variable that is declared in a constructor, method, or initializer. Additionally, this also includes the parameters too.

Henry
CLUCK LIKE A CHICKEN! Now look at this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 270 times.
Similar Threads
implicit constructor
default value for arrays?
doubt with static final field
my notes on JLS for any1 who needs them !!
What is the best way to declare a variable or objects?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 18:03:58.