Good day. I have a function that determines which item from the menu has been clicked. True faced with an incomprehensible error. I declare the message string at the beginning, and then change it (in accordance with the element on which the click occurred). But at the end of the function, where I want to display a toast, which will show exactly which element the user has clicked, I get an error, saying that I have not initialized the variable. But how did I not initialize it if I changed its value in the process of a function?

PS Everything works if you declare and initialize the variable immediately, i.e.

String.message = "";

I give the code:

 public boolean onOptionsItemSelected(MenuItem item) { String message; int id = item.getItemId(); switch(id) { case R.id.menu_item1: message = "menu item 1"; break; case R.id.menu_item2: message = "menu item 2"; break; case R.id.menu_item3: message = "menu item 3"; break; } Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); return true; } 
  • Apparently, either it is necessary to immediately initialize the message variable, or add the default condition to the select statement, but it is probably better to simply initialize with an empty string. - I. Smirnov
  • the variable is assigned, I checked - ikerya
  • In Java, default values ​​for local variables do not exist, so they must be declared and the initial value must be assigned before first use. - Peter Slusar
  • @ikerya, so when you call the onOptionsItemSelected method, the onOptionsItemSelected variable is re-initialized each time, more precisely, it is not initialized, so you should consider the options mentioned above - I. Smirnov

1 answer 1

The error says that the variable could not be initialized. Imagine that for some reason id not equal to any of the 3 options inside the switch . Then assignment to the message variable will not occur anywhere.

Your options:

  • initialize the variable with a value or null before the switch;
  • initialize the variable with the value or null , adding the default section inside the switch :

     switch(id) { case .... case .... default: message = ""; } 
  • Throw new IllegalArgumentException() or new IllegalStateException() from the default section if the unexpected id potentially destructive.