Eager Initialization over static block












0















As I'm trying to understand things better, I'm realizing how less I know. I'm sorry, if this sounds like a simple or silly question.



Do we really need static block, if it is ONLY for initialization of STATIC variables without any other logic coded in the block. We can directly do the eager initialization of those static variables, right?. Because from what I understand, static block gets executed when the class loads, so is the initialization of the static variables. And if it is only for variable initialization, isn't good enough to have the static variable eager-initialized, instead of having a exclusive static block for that.



For example, take the following code, and call it Case 1.



static String defaultName = null;
static String defaultNumber = 0;
static {
defaultName = "John";
defaultNumber = "+1-911-911-0911";
}


And the following code, and call it Case 2.



static String defaultName = "John";
static String defaultNumber = "+1-911-911-0911";


So, don't Case 1 and Case 2, give the same result or performance. Is static block necessary at all, in cases like this (for any purpose like readability like having all the data initialization at one place or so) while the Case 2 serves the purpose clean and clear? What am I missing?










share|improve this question


















  • 1





    It's indeed rarely needed. But it can be handy when you just want to trigger a side effect (like loading a class or a native library), or when you want to initialize several variables using more than an expression.

    – JB Nizet
    Nov 23 '18 at 16:49






  • 1





    Static blocks can also initialize a more complex class, like a map or a list, than can be done with a single line. For simple static fields like Strings or primitives obviously a static block is not needed.

    – markspace
    Nov 23 '18 at 16:54
















0















As I'm trying to understand things better, I'm realizing how less I know. I'm sorry, if this sounds like a simple or silly question.



Do we really need static block, if it is ONLY for initialization of STATIC variables without any other logic coded in the block. We can directly do the eager initialization of those static variables, right?. Because from what I understand, static block gets executed when the class loads, so is the initialization of the static variables. And if it is only for variable initialization, isn't good enough to have the static variable eager-initialized, instead of having a exclusive static block for that.



For example, take the following code, and call it Case 1.



static String defaultName = null;
static String defaultNumber = 0;
static {
defaultName = "John";
defaultNumber = "+1-911-911-0911";
}


And the following code, and call it Case 2.



static String defaultName = "John";
static String defaultNumber = "+1-911-911-0911";


So, don't Case 1 and Case 2, give the same result or performance. Is static block necessary at all, in cases like this (for any purpose like readability like having all the data initialization at one place or so) while the Case 2 serves the purpose clean and clear? What am I missing?










share|improve this question


















  • 1





    It's indeed rarely needed. But it can be handy when you just want to trigger a side effect (like loading a class or a native library), or when you want to initialize several variables using more than an expression.

    – JB Nizet
    Nov 23 '18 at 16:49






  • 1





    Static blocks can also initialize a more complex class, like a map or a list, than can be done with a single line. For simple static fields like Strings or primitives obviously a static block is not needed.

    – markspace
    Nov 23 '18 at 16:54














0












0








0








As I'm trying to understand things better, I'm realizing how less I know. I'm sorry, if this sounds like a simple or silly question.



Do we really need static block, if it is ONLY for initialization of STATIC variables without any other logic coded in the block. We can directly do the eager initialization of those static variables, right?. Because from what I understand, static block gets executed when the class loads, so is the initialization of the static variables. And if it is only for variable initialization, isn't good enough to have the static variable eager-initialized, instead of having a exclusive static block for that.



For example, take the following code, and call it Case 1.



static String defaultName = null;
static String defaultNumber = 0;
static {
defaultName = "John";
defaultNumber = "+1-911-911-0911";
}


And the following code, and call it Case 2.



static String defaultName = "John";
static String defaultNumber = "+1-911-911-0911";


So, don't Case 1 and Case 2, give the same result or performance. Is static block necessary at all, in cases like this (for any purpose like readability like having all the data initialization at one place or so) while the Case 2 serves the purpose clean and clear? What am I missing?










share|improve this question














As I'm trying to understand things better, I'm realizing how less I know. I'm sorry, if this sounds like a simple or silly question.



Do we really need static block, if it is ONLY for initialization of STATIC variables without any other logic coded in the block. We can directly do the eager initialization of those static variables, right?. Because from what I understand, static block gets executed when the class loads, so is the initialization of the static variables. And if it is only for variable initialization, isn't good enough to have the static variable eager-initialized, instead of having a exclusive static block for that.



For example, take the following code, and call it Case 1.



static String defaultName = null;
static String defaultNumber = 0;
static {
defaultName = "John";
defaultNumber = "+1-911-911-0911";
}


And the following code, and call it Case 2.



static String defaultName = "John";
static String defaultNumber = "+1-911-911-0911";


So, don't Case 1 and Case 2, give the same result or performance. Is static block necessary at all, in cases like this (for any purpose like readability like having all the data initialization at one place or so) while the Case 2 serves the purpose clean and clear? What am I missing?







java static-variables static-block variable-initialization






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 16:45









ConfusedCoderConfusedCoder

566




566








  • 1





    It's indeed rarely needed. But it can be handy when you just want to trigger a side effect (like loading a class or a native library), or when you want to initialize several variables using more than an expression.

    – JB Nizet
    Nov 23 '18 at 16:49






  • 1





    Static blocks can also initialize a more complex class, like a map or a list, than can be done with a single line. For simple static fields like Strings or primitives obviously a static block is not needed.

    – markspace
    Nov 23 '18 at 16:54














  • 1





    It's indeed rarely needed. But it can be handy when you just want to trigger a side effect (like loading a class or a native library), or when you want to initialize several variables using more than an expression.

    – JB Nizet
    Nov 23 '18 at 16:49






  • 1





    Static blocks can also initialize a more complex class, like a map or a list, than can be done with a single line. For simple static fields like Strings or primitives obviously a static block is not needed.

    – markspace
    Nov 23 '18 at 16:54








1




1





It's indeed rarely needed. But it can be handy when you just want to trigger a side effect (like loading a class or a native library), or when you want to initialize several variables using more than an expression.

– JB Nizet
Nov 23 '18 at 16:49





It's indeed rarely needed. But it can be handy when you just want to trigger a side effect (like loading a class or a native library), or when you want to initialize several variables using more than an expression.

– JB Nizet
Nov 23 '18 at 16:49




1




1





Static blocks can also initialize a more complex class, like a map or a list, than can be done with a single line. For simple static fields like Strings or primitives obviously a static block is not needed.

– markspace
Nov 23 '18 at 16:54





Static blocks can also initialize a more complex class, like a map or a list, than can be done with a single line. For simple static fields like Strings or primitives obviously a static block is not needed.

– markspace
Nov 23 '18 at 16:54












4 Answers
4






active

oldest

votes


















1














Obviously one would never prefer case 1. For case 2, sometimes an initialization is more complicated than can be done in one line.



public final class Stooges {

private final static Map<String,String> stooges = new HashMap<>();
static {
stooges.put( "Larry", "Larry Fine" );
stooges.put( "Moe", "Moe Howard" );
stooges.put( "Curly", "Curly Howard" );
}
}


Here you can't easily put the initialization of stooges in a single line, so the static block makes it easier (and more readable for a maintainer) to init the values.






share|improve this answer



















  • 1





    You can actually: private final static Map<String,String> stooges = createStooges();

    – JB Nizet
    Nov 23 '18 at 17:19













  • Also, in Java 11: private static final var stooges = Map.of("Larry", "Larry Fine", "Moe", "Moe Howard", "Curly", "Curley Howard");. Or, if you want a mutable one, ... = new HashMap<>(Map.of(...)).

    – Klitos Kyriacou
    Nov 23 '18 at 17:42



















2














I think that if you need to initialize a static variable with a starting value available, you can use Case 2, while if you need to initialize a variable according to some logical operations, you can put it in a block of static code and execute his initialization through it






share|improve this answer































    1














    One reason you might use a static block is if you want to set more than one variable:



    private static int n;
    private static String s;
    static {
    if (someExpensiveOperation()) {
    n = 123;
    s = "foo";
    } else {
    n = 456;
    s = "bar";
    }
    }





    share|improve this answer
























    • I'll take that as, if the initialization of variable(s) is more complicated than done in one line as @markspace mentioned. Like for example, conditionally, as in your example. Thanks.

      – ConfusedCoder
      Nov 27 '18 at 17:50



















    0














    Static block is used when you are doing the logical operation or processing when class is getting loaded into memory then variables getting intialized



    Example:



    public class R {

    public static int example;

    static {
    int example1 = 2 + 3;
    example = example1;
    }


    public static void main(String args) {
    System.out.println(example); // print 5
    }

    }


    In case if the value is already known then can be directly assigned (Case 2);






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53450353%2feager-initialization-over-static-block%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Obviously one would never prefer case 1. For case 2, sometimes an initialization is more complicated than can be done in one line.



      public final class Stooges {

      private final static Map<String,String> stooges = new HashMap<>();
      static {
      stooges.put( "Larry", "Larry Fine" );
      stooges.put( "Moe", "Moe Howard" );
      stooges.put( "Curly", "Curly Howard" );
      }
      }


      Here you can't easily put the initialization of stooges in a single line, so the static block makes it easier (and more readable for a maintainer) to init the values.






      share|improve this answer



















      • 1





        You can actually: private final static Map<String,String> stooges = createStooges();

        – JB Nizet
        Nov 23 '18 at 17:19













      • Also, in Java 11: private static final var stooges = Map.of("Larry", "Larry Fine", "Moe", "Moe Howard", "Curly", "Curley Howard");. Or, if you want a mutable one, ... = new HashMap<>(Map.of(...)).

        – Klitos Kyriacou
        Nov 23 '18 at 17:42
















      1














      Obviously one would never prefer case 1. For case 2, sometimes an initialization is more complicated than can be done in one line.



      public final class Stooges {

      private final static Map<String,String> stooges = new HashMap<>();
      static {
      stooges.put( "Larry", "Larry Fine" );
      stooges.put( "Moe", "Moe Howard" );
      stooges.put( "Curly", "Curly Howard" );
      }
      }


      Here you can't easily put the initialization of stooges in a single line, so the static block makes it easier (and more readable for a maintainer) to init the values.






      share|improve this answer



















      • 1





        You can actually: private final static Map<String,String> stooges = createStooges();

        – JB Nizet
        Nov 23 '18 at 17:19













      • Also, in Java 11: private static final var stooges = Map.of("Larry", "Larry Fine", "Moe", "Moe Howard", "Curly", "Curley Howard");. Or, if you want a mutable one, ... = new HashMap<>(Map.of(...)).

        – Klitos Kyriacou
        Nov 23 '18 at 17:42














      1












      1








      1







      Obviously one would never prefer case 1. For case 2, sometimes an initialization is more complicated than can be done in one line.



      public final class Stooges {

      private final static Map<String,String> stooges = new HashMap<>();
      static {
      stooges.put( "Larry", "Larry Fine" );
      stooges.put( "Moe", "Moe Howard" );
      stooges.put( "Curly", "Curly Howard" );
      }
      }


      Here you can't easily put the initialization of stooges in a single line, so the static block makes it easier (and more readable for a maintainer) to init the values.






      share|improve this answer













      Obviously one would never prefer case 1. For case 2, sometimes an initialization is more complicated than can be done in one line.



      public final class Stooges {

      private final static Map<String,String> stooges = new HashMap<>();
      static {
      stooges.put( "Larry", "Larry Fine" );
      stooges.put( "Moe", "Moe Howard" );
      stooges.put( "Curly", "Curly Howard" );
      }
      }


      Here you can't easily put the initialization of stooges in a single line, so the static block makes it easier (and more readable for a maintainer) to init the values.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 23 '18 at 17:02









      markspacemarkspace

      6,98521529




      6,98521529








      • 1





        You can actually: private final static Map<String,String> stooges = createStooges();

        – JB Nizet
        Nov 23 '18 at 17:19













      • Also, in Java 11: private static final var stooges = Map.of("Larry", "Larry Fine", "Moe", "Moe Howard", "Curly", "Curley Howard");. Or, if you want a mutable one, ... = new HashMap<>(Map.of(...)).

        – Klitos Kyriacou
        Nov 23 '18 at 17:42














      • 1





        You can actually: private final static Map<String,String> stooges = createStooges();

        – JB Nizet
        Nov 23 '18 at 17:19













      • Also, in Java 11: private static final var stooges = Map.of("Larry", "Larry Fine", "Moe", "Moe Howard", "Curly", "Curley Howard");. Or, if you want a mutable one, ... = new HashMap<>(Map.of(...)).

        – Klitos Kyriacou
        Nov 23 '18 at 17:42








      1




      1





      You can actually: private final static Map<String,String> stooges = createStooges();

      – JB Nizet
      Nov 23 '18 at 17:19







      You can actually: private final static Map<String,String> stooges = createStooges();

      – JB Nizet
      Nov 23 '18 at 17:19















      Also, in Java 11: private static final var stooges = Map.of("Larry", "Larry Fine", "Moe", "Moe Howard", "Curly", "Curley Howard");. Or, if you want a mutable one, ... = new HashMap<>(Map.of(...)).

      – Klitos Kyriacou
      Nov 23 '18 at 17:42





      Also, in Java 11: private static final var stooges = Map.of("Larry", "Larry Fine", "Moe", "Moe Howard", "Curly", "Curley Howard");. Or, if you want a mutable one, ... = new HashMap<>(Map.of(...)).

      – Klitos Kyriacou
      Nov 23 '18 at 17:42













      2














      I think that if you need to initialize a static variable with a starting value available, you can use Case 2, while if you need to initialize a variable according to some logical operations, you can put it in a block of static code and execute his initialization through it






      share|improve this answer




























        2














        I think that if you need to initialize a static variable with a starting value available, you can use Case 2, while if you need to initialize a variable according to some logical operations, you can put it in a block of static code and execute his initialization through it






        share|improve this answer


























          2












          2








          2







          I think that if you need to initialize a static variable with a starting value available, you can use Case 2, while if you need to initialize a variable according to some logical operations, you can put it in a block of static code and execute his initialization through it






          share|improve this answer













          I think that if you need to initialize a static variable with a starting value available, you can use Case 2, while if you need to initialize a variable according to some logical operations, you can put it in a block of static code and execute his initialization through it







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 16:49









          FedericoFederico

          334




          334























              1














              One reason you might use a static block is if you want to set more than one variable:



              private static int n;
              private static String s;
              static {
              if (someExpensiveOperation()) {
              n = 123;
              s = "foo";
              } else {
              n = 456;
              s = "bar";
              }
              }





              share|improve this answer
























              • I'll take that as, if the initialization of variable(s) is more complicated than done in one line as @markspace mentioned. Like for example, conditionally, as in your example. Thanks.

                – ConfusedCoder
                Nov 27 '18 at 17:50
















              1














              One reason you might use a static block is if you want to set more than one variable:



              private static int n;
              private static String s;
              static {
              if (someExpensiveOperation()) {
              n = 123;
              s = "foo";
              } else {
              n = 456;
              s = "bar";
              }
              }





              share|improve this answer
























              • I'll take that as, if the initialization of variable(s) is more complicated than done in one line as @markspace mentioned. Like for example, conditionally, as in your example. Thanks.

                – ConfusedCoder
                Nov 27 '18 at 17:50














              1












              1








              1







              One reason you might use a static block is if you want to set more than one variable:



              private static int n;
              private static String s;
              static {
              if (someExpensiveOperation()) {
              n = 123;
              s = "foo";
              } else {
              n = 456;
              s = "bar";
              }
              }





              share|improve this answer













              One reason you might use a static block is if you want to set more than one variable:



              private static int n;
              private static String s;
              static {
              if (someExpensiveOperation()) {
              n = 123;
              s = "foo";
              } else {
              n = 456;
              s = "bar";
              }
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 23 '18 at 17:49









              DodgyCodeExceptionDodgyCodeException

              3,5031424




              3,5031424













              • I'll take that as, if the initialization of variable(s) is more complicated than done in one line as @markspace mentioned. Like for example, conditionally, as in your example. Thanks.

                – ConfusedCoder
                Nov 27 '18 at 17:50



















              • I'll take that as, if the initialization of variable(s) is more complicated than done in one line as @markspace mentioned. Like for example, conditionally, as in your example. Thanks.

                – ConfusedCoder
                Nov 27 '18 at 17:50

















              I'll take that as, if the initialization of variable(s) is more complicated than done in one line as @markspace mentioned. Like for example, conditionally, as in your example. Thanks.

              – ConfusedCoder
              Nov 27 '18 at 17:50





              I'll take that as, if the initialization of variable(s) is more complicated than done in one line as @markspace mentioned. Like for example, conditionally, as in your example. Thanks.

              – ConfusedCoder
              Nov 27 '18 at 17:50











              0














              Static block is used when you are doing the logical operation or processing when class is getting loaded into memory then variables getting intialized



              Example:



              public class R {

              public static int example;

              static {
              int example1 = 2 + 3;
              example = example1;
              }


              public static void main(String args) {
              System.out.println(example); // print 5
              }

              }


              In case if the value is already known then can be directly assigned (Case 2);






              share|improve this answer




























                0














                Static block is used when you are doing the logical operation or processing when class is getting loaded into memory then variables getting intialized



                Example:



                public class R {

                public static int example;

                static {
                int example1 = 2 + 3;
                example = example1;
                }


                public static void main(String args) {
                System.out.println(example); // print 5
                }

                }


                In case if the value is already known then can be directly assigned (Case 2);






                share|improve this answer


























                  0












                  0








                  0







                  Static block is used when you are doing the logical operation or processing when class is getting loaded into memory then variables getting intialized



                  Example:



                  public class R {

                  public static int example;

                  static {
                  int example1 = 2 + 3;
                  example = example1;
                  }


                  public static void main(String args) {
                  System.out.println(example); // print 5
                  }

                  }


                  In case if the value is already known then can be directly assigned (Case 2);






                  share|improve this answer













                  Static block is used when you are doing the logical operation or processing when class is getting loaded into memory then variables getting intialized



                  Example:



                  public class R {

                  public static int example;

                  static {
                  int example1 = 2 + 3;
                  example = example1;
                  }


                  public static void main(String args) {
                  System.out.println(example); // print 5
                  }

                  }


                  In case if the value is already known then can be directly assigned (Case 2);







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 17:36









                  saurav omarsaurav omar

                  767




                  767






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53450353%2feager-initialization-over-static-block%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'