javaobjectstatic

Static variable Java


package drinks;
public class Dairy {
  public static Dairy dairyclssobj = null;
  private Dairy(){}

public static Dairy getDairy() {
    if (dairyclssobj==null) {
         dairyclssobj = new Dairy();
         return dairyclssobj;
    }
    return dairyclssobj;    
}

static String brandname = "  oompaa..lumpaa..Drinks";

public static void main(String[] args) {

    System.out.println(brandname);
}
}
class Chocolateee {
  public static void main(String[] args) {
    
     Dairy.brandname = "..Yum Drinks";
     System.out.println("The brand name now is " + Dairy.brandname);
   }    
}
class Chocolate1  {
  static String bnameString = Dairy.brandname;
  public static void main(String[] args) {
     System.out.println("The brand name now is " + bnameString);
  }
}

I am new to Java, trying to understand the static keyword.

This is in the project I created in Eclipse. Package is dairy and the problem is that the static string brandname value in Dairy class is not changing for Chocolate1 class even when I changed it in the Chocolateee class. It was supposed to be "Yum Drinks" but still the output is "oompaa.lumpaa.Drinks". Even when I made the whole class into a singleton it still produces the same output.

Sequence of execution: First I executed Dairy, 2nd Chocolateee, and 3rd Chocolate1.

Output is for Dairy "oompaa.lumpaa.Drinks", for Chocolatee "Yum Drinks" and for Chocolate1 "oompaa.lumpaa.Drinks".

Am I running the classes in wrong way? Isn't a static variable shared between objects and valued is changed for all if one class changes it... Why am I getting this output?


Solution

  • Actually you have 3 endpoints in your program that cannot execute together. In fact, these are 3 separate programs. If you want to change Dairy.brandname you can try something like this:

    package drinks;
    
    public class Dairy {
        public static String brandname = "  oompaa..lumpaa..Drinks";
    }
    
    public class Chocolateee {
        public static void changeDairyBrandname() {
            Dairy.brandname = "..Yum Drinks";
        }    
    }
    
    public class UnderstandStaticKeyword {
    
        public static void main(String[] args) {
            System.out.println("The brand name now is " + Dairy.brandname);
            Chocolateee.changeDairyBrandname()
            System.out.println("The brand name now is " + Dairy.brandname);
        }
    }
    

    To understand better, you can read this article