File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 33
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: 13868
    
  10

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: 973
    
    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: 4339
    
    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?
 
Similar Threads
SCJP 1.4 passed (95%)
How do we get this output ?
Example assigments for part II/III
Opening a new group in java ranch
PA #1.....picture association