Java – how to use variables outside of method

android, java

how do i pass char1 out of the onCreate method into another method — in this case, pass it into selectChar2? Can i make char1 and char2 global or something? I'm not sure what's the proper way to go about this. please help!

private String char1,char2; // does this even do anything? I thought this would let me use char1 and char2 [email protected] void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_pick_char2);    Bundle extras = getIntent().getExtras();    if (extras != null) {        String char1 = (String) extras.getString("char1"); //is the (String) necessary?        TextView textView = (TextView) findViewById(;        textView.setText(char1+" vs "+"char2");    }}public void selectChar2(View v) {    Button btn = (Button)v;    String char2 = btn.getText().toString();    Intent intent = new Intent(PickChar2.this, DisplayMatchUp.class);    Bundle extras = new Bundle();    extras.putString("Character1",char1); //char1 here is do I get the value from the method above?    extras.putString("Character2", char2);    intent.putExtras(extras);    startActivity(intent);

Best Solution

as it is, you have declared and used two separate variables:

  1. an instance variable: char1
  2. a local variable: char1

1 is scoped to the class instance (it's accessible in any non-static scope within the class). 2 is scoped in the block where it is defined. in this case, simply don't create a local variable, and use the instance variable,

    char1 = (String) extras.getString("char1");