Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why does the below code fail to compile?

 
Faisal syed
Ranch Hand
Posts: 35
  • 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
  • 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
Posts: 15359
39
Android IntelliJ IDE Java Scala Spring
  • Likes 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
  • 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: 4439
3
Java
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic