Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I had this java class code -
C#
public class game_setter {

    private String[] blocks = new String[3];

    blocks[0] = "a";
    blocks[1] = "b";
    blocks[2] = "c";

}

And the error highlighting was - Syntax error on token ";", { expected after this token


So I tried to correct the code.
The new code with no error is -
C#
public class game_setter {

    private String[] blocks = new String[3];

    {
    blocks[0] = "a";
    blocks[1] = "b";
    blocks[2] = "c";
    }

}


But I'm unable to understand why the error was there and how it got corrected by just adding brackets?
Posted

1 solution

Your variable blocks is decleared as a class member.

After that you try to assign values to the member - that is not allowed in class body, only in method.


This is the correct way to handle that:

Java
public class game_setter { // class ALWAYS starts with capital letter! No underscores please!
 
    private String[] blocks = new String[3];
 

    public game_setter() {
        blocks[0] = "a";
        blocks[1] = "b";
        blocks[2] = "c";
    }
 
}
 
Share this answer
 
Comments
IAM_Dhruv 7-Oct-14 2:22am    
yes. I got it. I will keep this in mind. Thanks a lot.
IAM_Dhruv 7-Oct-14 2:24am    
And I have also put up a return type to the method. Now its public void game_setter()
TorstenH. 7-Oct-14 3:32am    
no, not on this, it's the constructor.
On other methods - yes. But not in this case.
IAM_Dhruv 7-Oct-14 6:46am    
ok. yes yes. its the constructor. thanks.

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