-3

I am facing weird error: unexpected end of declaration. And I am very sure that there is no typo. Please help.

package test.anyname;
import android.app.*;
import android.os.*;

public class MainActivity extends Activity {
   boolean ty= true;
   ty= false;       // Error occurred at this line
   @Override
   protected void onCreate(Bundle savedInstanceState){
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
   }
}
Vivek Barai
  • 1,338
  • 13
  • 26
D5fgj
  • 3
  • 3

2 Answers2

2

You can initialize a variable only once and you can't change this variable once again outside of some method. Then, you should do this in a method.

package test.anyname;
import android.app.*;
import android.os.*;

public class MainActivity extends Activity {
   boolean ty = false; // you can initialize only once

   @Override
   protected void onCreate(Bundle savedInstanceState){
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
   }

   void changeTy() {
      ty = !ty;
   }
}    
  • A couple of points (and I'm mostly nitpicking): 1) you can actually initialize a variable multiple times: `boolean ty = ty = ty = false;` is (perhaps surprisingly) legal; 2) you can change the variable in an instance initializer (e.g. `boolean ty = false; {ty = true;}`), which isn't a method. – Andy Turner Dec 15 '17 at 08:34
1

The only things which you can write directly inside a class body are:

  • Field declarations (e.g. boolean ty= true;)
  • Method declarations (e.g. @Override protected void onCreate(Bundle savedInstanceState) { ... })
  • Constructors
  • Declarations of nested interfaces and classes
  • Static and instance initializers

ty = false; is an assignment, which is none of these, so it is not allowed.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243