java code is showing error. ( ';',expected) [closed]

class B { int x,y; int z; z=x*y; void show() { System.out.println(z); } } class A { public static void main(String as[]) { B b=new B(); b.show(); } } 
5

4 Answers

You can't have statements in the class body (z=x*y;). You have (at least) two options:

  • int z = x * y;
  • use initializer block

    { z = x * y; } 

These are virtually the same. I'd prefer the first option (cleaner) See here

5

z=x*y; you cant do it here. put it inside constructor

class B { int x,y; int z; //z=x*y; //you cant do it here. where are you getting x and y value by the way??? public B() { //x and y values should be set 'somehow' before this z = x*y; } void show() { System.out.println(z); } } 
1

I think that your problem is in these lines:

int z; z=x*y; 

This first line is perfectly fine - it declares a class instance variable called z of type int. This second line, however, is the source of your problem. In Java, it's illegal to have code in a class outside of a class method or static initializer. In this case, the statement z = x * y; is legal Java code, but it has to be inside of a method.

To fix this, you can move this code into a constructor or some other method.

 z=x*y; 

mentioned not within method body. You can't do that. Move it to the constructor or another method.

Inside class body and outside method body you can mention only fields, methods and inner class declarations.

You Might Also Like