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
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply 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: 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
    
    3

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
    
    2

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
 
I agree. Here's the link: http://jrebel.com/download
 
subject: Why does the below code fail to compile?
 
Similar Threads
Example assigments for part II/III
Opening a new group in java ranch
How do we get this output ?
PA #1.....picture association
SCJP 1.4 passed (95%)