Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By Junky

Thread: Where to initialize varialbles?

  1. #1
    Drew345 is offline Member
    Join Date
    May 2015
    Posts
    31
    Rep Power
    0

    Default Where to initialize varialbles?

    So, back in the day, all variables were initialized at the top of the program.

    int i, j,
    int k=0;

    for (i = 0; i<100; i++)
    for (j = 0; j<100; j++)
    k += k;

    But nowadays variables are initialized the first times they are used like:

    int k=0;

    for ( int i = 0; i<100; i++)
    for (int j = 0; j<100; j++)
    k += k;

    So my question is this: Even though it is nice and pretty to initialize the variables the first times they are used, isn't it a bit slower and wasteful? I mean, the counter variables have to be "constructed" and "torn down" every time a loop is entered and exited. Isn't it actually better the old way where the variable is only constructed once?
    But nobody does it that way anymore, so what am I missing?

    Thanks,
    Drew

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Where to initialize varialbles?

    No, it's the compiler that does the job, i.e. it can calculate the offset on the stack for every local variable and so it knows the total stack size needed for a single method; on entry of that method, the JVM creates a stack with that particular size, so there's no need to 'contruct' or remove variables over and over again ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,807
    Rep Power
    13

    Default Re: Where to initialize varialbles?

    0.02c

    Many believe that variables should be declared in the smallest scope possible. Therefore if you have a class with 1000 lines of code and a loop way down at line 970 then declare your loop variables in or near the loop. No need to declare them waaaaaaay up the top of the class.
    Mike U likes this.

Similar Threads

  1. Trying to initialize arrays
    By supremegrandruler in forum New To Java
    Replies: 10
    Last Post: 04-05-2014, 12:30 PM
  2. Replies: 11
    Last Post: 04-11-2012, 05:57 PM
  3. How do initialize these Strings?
    By eLancaster in forum New To Java
    Replies: 1
    Last Post: 03-02-2011, 05:09 PM
  4. Initialize a Variable
    By lala in forum New To Java
    Replies: 13
    Last Post: 11-16-2010, 06:51 PM
  5. Trying to initialize variables
    By random0munky in forum New To Java
    Replies: 2
    Last Post: 10-14-2009, 10:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •