| Author |
Why does the below code fail to compile?
|
Faisal syed
Ranch Hand
Joined: Mar 25, 2011
Posts: 30
|
|
package myPackage1;
public class Boxer1 {
int j;
j = 1;
}
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1776
|
|
Assignment operation should be placed inside a method or a block like below.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
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.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
James Boswell
Ranch Hand
Joined: Nov 09, 2011
Posts: 657
|
|
You could use
Personally, I don't like this style. Initialising instance members is the job of the constructor.
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4089
|
|
|
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.
|
SCJP
|
 |
 |
|
|
subject: Why does the below code fail to compile?
|
|
|