• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

assigning a value to a previously declared (primitive || reference )variable

 
Ranch Hand
Posts: 144
Netbeans IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Guys,

could anyone please tell me why we can't assign a value to a previously declared (primitive || reference )variable inside a class body? but it is ok inside a method body as shown below

 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can only have declarations at that point in the code. Executable statements can go inside methods, as you say, or inside static initializer blocks or instance initializer blocks. Or inside constructors.
 
Hama Kamal
Ranch Hand
Posts: 144
Netbeans IDE Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:You can only have declarations at that point in the code. Executable statements can go inside methods, as you say, or inside static initializer blocks or instance initializer blocks. Or inside constructors.



thanks for the quick reply Paul..
 
Ranch Hand
Posts: 41
Android Chrome Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
May I add - declarations + definitions. The following works inside the class.

int[] testScores = new int[]{2,3,45,6};
 
Hama Kamal
Ranch Hand
Posts: 144
Netbeans IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sanjeev Ba wrote:May I add - declarations + definitions. The following works inside the class.

int[] testScores = new int[]{2,3,45,6};



you are right Sanjeev ,, thanks
reply
    Bookmark Topic Watch Topic
  • New Topic