• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instace variable initialitation  RSS feed

 
Ryan Federwitz
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey!

I am new to java and i have some question!Can you answer this?

Can I declare and initialize instance variable on separate lines?
Within a method( local variable )this code works for me


why this code generate some compiler error?I can't declare and initialize instance variable on separate lines,can I?
 
Somnath Mallick
Ranch Hand
Posts: 483
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These links may help you out. Especially the second link:

http://leepoint.net/JavaBasics/methods/methods-22-local-variables.html

http://www.javaworld.com/javaworld/jw-03-1998/jw-03-initialization.html

Hope this helps.
 
Ryan Federwitz
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to your immediate response!
 
Campbell Ritchie
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is a compiler error because the second line is defined as a "statement". Statements are not permitted outside methods initialisers or constructors.
 
Ryan Federwitz
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your kindness Ritchie I think [ String str="string"; ] is a statement,but its worked!


This works well when the initialization value is available and the initialization can be put on one line.The compiler returns compiler error when the initialization value is available and the initialization can be put on separate line,
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!