Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my code is this:
Java
class first{
	int x,y;
	x = y = 0;
}
class second{
	public static void main(String args[]){
		first x = new first();
		System.out.println(x.x);
		System.out.println(x.y);
	}
}

Error:
<identifier> excepted
x = y = 0;
^
When I write this code like this:
Java
class first{
	int x=0;
	int y=0;
}
class second{
	public static void main(String args[]){
		first x = new first();
		System.out.println(x.x);
		System.out.println(x.y);
	}
}

there is no error, please explain me why the previous code not work
Posted
Updated 17-Nov-15 0:27am
v2
Comments
Patrice T 17-Nov-15 6:24am    
What is supposed to do this code ?
What is it doing wrong ?
phil.o 17-Nov-15 6:47am    
Because you cannot perform an assignment (except on the same line as a declaration) in the body of a class.

beacuse
Java
int x = 0;

is variable declaration and initialization while
Java
x = 0;
is an assignment, not allowed there.
 
Share this answer
 
Um.
You can't just put code into a class without it being inside a function body. Put the initializer in the class constructor and you'll be fine.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900