Search code examples
javaandroidstringpublic-method

Make a String in java Global


I am an Android developer and I have made a string for generating a random 6-digit OTP which is there in the protected void onCreate(Bundle savedInstanceState) {, the first thing in a java program.:

String otp = new DecimalFormat("000000").format(new Random().nextInt(999999));
Toast.makeText(getApplicationContext(), "Your OTP is " + otp, Toast.LENGTH_SHORT).show();

I have another public void in my java program in which I have to call the OTP String but, I don't know how to do that.

Any type of help will be appreciated.


Solution

  • Define your String variable either as a class(static) variable or instance variable in your class.

    Sample solution

    public class Main{
       String otp; //Define your variable here
    
    
       public void method1(){
    
          //Now you can access the variable otp and you can make changes
    
       }
    
      public void method2(){
    
         //Now you can access the variable otp and you can make changes
    
    
      }
    
    }