• Post Reply Bookmark Topic Watch Topic
  • New Topic

How come you cant print a default variable value?  RSS feed

 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this code did work though



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

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

 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Junilu Lacar

a local variable is any variable thats in a method right?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!