• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Devaka Cooray
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
Bartenders:

Instace variable initialitation

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 483
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks to your immediate response!
 
Marshal
Posts: 81618
593
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,
 
Paper jam tastes about as you would expect. Try some on this tiny ad:
Paul Wheaton's 16th Kickstarter: Gardening playing cards for gardeners and homesteaders
https://coderanch.com/t/889615/Paul-Wheaton-Kickstarter-Gardening-playing
reply
    Bookmark Topic Watch Topic
  • New Topic