This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
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 REST with Spring (video course) this week in the Spring 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

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

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: 15042

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 8 API documentation
James Boswell

Joined: Nov 09, 2011
Posts: 1051

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: 4351

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.

Visit my download page
I agree. Here's the link:
subject: Why does the below code fail to compile?
It's not a secret anymore!