File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why does the below code fail to compile?

 
Faisal syed
Ranch Hand
Posts: 35
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package myPackage1;

public class Boxer1 {


int j;
j = 1;



}
 
John Jai
Rancher
Posts: 1776
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assignment operation should be placed inside a method or a block like below.

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At class level (inside a class, but outside of a method) you can only declare member variables; you cannot execute arbitrary statements.

So the declaration int j; is OK, but the assignment statement j = 1; is not allowed at class level.
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use



Personally, I don't like this style. Initialising instance members is the job of the constructor.
 
Randall Twede
Ranch Hand
Posts: 4353
2
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
now i didn't know that. i guess i just never tried to do it. personally i still like initializing when declaring when possible. but i do buy the argument that it should take place in the constructor. oh well, so i have split personality, no big deal.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic