Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change static variables

I would like know whether it's possible to change the code below that the second output prints the changed variables that I get "2.2noo100onn" instead of "1.1foo200oof"?

Is it possible to return multiple types from different types or is there a way I can crate an mixed variable type array?

The code I'm working on is a lot bigger, but this example works the same way.

public class test 
{
    static String s1 = "foo";
    static String s2 = "oof";
    static double d1 = 1.1;
    static int i1 = 200;

       public static void main (String[] args)
       {
            // Ausgabe Hello World!
            System.out.println(d1+s1+i1+s2);

            bla();
            System.out.println(d1+s1+i1+s2);
       }

    public static void bla() {
         String s1 = "noo";
         String s2 = "onn";
         double d1 = 2.2;
         int i1 = 100;
    }
}
like image 649
Julian Stobbe Avatar asked Jul 23 '26 01:07

Julian Stobbe


2 Answers

Yes, you can.

In method bla() you are re-declaring the variables, such that the new variables have local scope. They are actually different variables from the ones you declared and initialized at the beginning of your class. Instead, manipulate the class-scope variables in this way:

public static void bla() {
     s1 = "noo";
     s2 = "onn";
     d1 = 2.2;
     i1 = 100;
}
like image 161
La-comadreja Avatar answered Jul 24 '26 14:07

La-comadreja


If you want your bla method to change the static variables, don't hide them. When you re-declare those variables in that method, you are creating new local variables, that only exist within the scope of the method.

Change your code to:

public static void bla() 
{
     s1 = "noo";
     s2 = "onn";
     d1 = 2.2;
     i1 = 100;
}
like image 44
Eran Avatar answered Jul 24 '26 16:07

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!