Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question on initialization

 
Abhishek Reddy
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Legal
{
int width=45;

{
height=11;
}

int height,area;
area=width*height;
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

can any one tell me what is wrong with this code......also tell me how to overcome it..
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


i have made some changes in your code
compare your code with above code and see where you have made mistake.
 
Vaibhav Chauhan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Legal
{
int width=45;

{ //line1
height=11;
}

int height,area;
area=width*height; //line 2
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

Note: you should put code at line 2 inside a method otherwise you can put it in a static block by declaring all the variables as static.

note that instance block at line 1 is never executed as you are not creating any instance of class Legal.
 
Abhishek Reddy
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Legal
{
int width=45;

{ //line1
height=11;
}

int height,area;
area=width*height; //line 2
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

ok but when i changed the line 2 say
int height;
int area=weight*height; the code is compiling fine......what is wrong when i say area=width*height; in the code..why it is not compiling..
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code below will compile.

The problem is that you're tring to write logic in the class declaration. In the class block, you can only initialize variables and write methods. You're doing something inbetween. You declare area, and then after the declaration, do some funky manipulation. You just can't do that. If you want to do area=height*width, either do it in a method, or do it right when the variable is declared. Those are the rules.


class Legal
{
int width=45;

{
//what is this?
int height=11;
}

int height;
int area=width*height;

/*This can't be done in the class block*/
//area=width*height;


public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic