aspose file tools*
The moose likes Java in General and the fly likes Why does the below code fail to compile? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why does the below code fail to compile?" Watch "Why does the below code fail to compile?" New topic
Author

Why does the below code fail to compile?

Faisal syed
Ranch Hand

Joined: Mar 25, 2011
Posts: 35
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14146
    
  18

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
Bartender

Joined: Nov 09, 2011
Posts: 1020
    
    5

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: 4347
    
    2

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
Visit my download page
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why does the below code fail to compile?