Results 1 to 13 of 13
  1. #1
    diggitydoggz is offline Member
    Join Date
    Dec 2008
    Posts
    55
    Rep Power
    0

    Default declaring fields without assigning values to them

    I've noticed that a lot of code I've been looking at doesn't initialize global variables when they are first declared. I have been doing my own code this way just to model what I've seen in textbooks:

    public class JavaPad {
    public static void main(String[] args) {
    JavaPad pad = new JavaPad();
    }

    JFrame frame;
    JPanel north;
    JPanel south;
    JPanel uSouth;
    JPanel dSouth;
    JButton bNew;
    JButton bSave;
    JButton bOpen;
    JButton bQuit;
    JButton fGround;
    JButton bGround;
    JLabel tSize;
    JTextField tSizeField;
    JTextArea area;

    public JavaPad() {
    frame = new JFrame("JavaPad");
    frame.setSize(400, 300);
    frame.setLayout(new BorderLayout());

    bNew = new JButton("New");
    bSave = new JButton("Save");
    bOpen = new JButton("Open");
    bQuit = new JButton("Quit");
    fGround = new JButton("Foreground");
    bGround = new JButton("Background");
    tSize = new JLabel("Text Size:");
    tSizeField = new JTextField(3);

    etc...
    Thinking about it, this seems to be very inefficient because you have to write a lot of extra lines. Is there any particular reason that people code this way? Or maybe it's just the sources I've been looking at?

  2. #2
    PatoDB is offline Member
    Join Date
    Dec 2008
    Posts
    14
    Rep Power
    0

    Default

    Sometimes there's methods where you can't initialice variables inside that method. So, yo must declared it outside, and then, inside the method you asigned the value to that variable.

    Another example will be:
    Java Code:
    public int squareRoot(int y)
    {int x;
       if(y>0)
          x=Math.sqrt(y);
      
      return x;}
    If x it's not declared outside the if body, the compiler will say "cannot find symbol". Because there's a chance, to the if condition, to be false.

    ------------------------------------------------

    Now im going to ask something:

    What is exactly the diference between this two Codes:

    Java Code:
    for(int i=0;i<3;i++)
    {...Here I enter some values to create an object...
        MyObject oj = new MyObject(value1, value2);
        arrayOfMyObject[i]=oj;}
    Java Code:
    MyObject oj;
    for(int i=0;i<3;i++)
    {...Here I enter some values to create an object...
        oj = new MyObject(value1, value2);
        arrayOfMyObject[i]=oj;}
    Because i cant understand that diference quite well


    P.D: Sorry for my english... u.u
    Last edited by PatoDB; 12-24-2008 at 06:38 AM.
    ..:: abretumundo.wordpress.com ::..

  3. #3
    diggitydoggz is offline Member
    Join Date
    Dec 2008
    Posts
    55
    Rep Power
    0

    Default

    thanks for the input. any other thoughts , guys?

  4. #4
    BeholdMyGlory is offline Member
    Join Date
    Dec 2008
    Posts
    8
    Rep Power
    0

    Default

    Quote Originally Posted by PatoDB View Post
    Sometimes there's methods where you can't initialice variables inside that method. So, yo must declared it outside, and then, inside the method you asigned the value to that variable.

    Another example will be:
    Java Code:
    public int squareRoot(int y)
    {int x;
       if(y>0)
          x=Math.sqrt(y);
      
      return x;}
    If x it's not declared outside the if body, the compiler will say "cannot find symbol". Because there's a chance, to the if condition, to be false.

    ------------------------------------------------

    Now im going to ask something:

    What is exactly the diference between this two Codes:

    Java Code:
    for(int i=0;i<3;i++)
    {...Here I enter some values to create an object...
        MyObject oj = new MyObject(value1, value2);
        arrayOfMyObject[i]=oj;}
    Java Code:
    MyObject oj;
    for(int i=0;i<3;i++)
    {...Here I enter some values to create an object...
        oj = new MyObject(value1, value2);
        arrayOfMyObject[i]=oj;}
    Because i cant understand that diference quite well


    P.D: Sorry for my english... u.u
    Well, with the first example, the object is declared inside of the for loop, and will therefore not be visible outside the loop. That is; if you try to read from "oj" outseide of the for loop, you will get a "cannot find symbol".
    But in the second example, you only declare "oj" once. And you do it outside of the for loop, and therefore it will also exist outside of the for loop. But it won't really matter since you place it in an array anyway. So I'd use the first example, since I won't need the object "oj" outside of the loop.

  5. #5
    LifeWithJava is offline Member
    Join Date
    Dec 2008
    Posts
    7
    Rep Power
    0

    Default

    What is exactly the diference between this two Codes:
    Java Code:
    Code:
    
    for(int i=0;i<3;i++) {
    ...Here I enter some values to create an object... 
    MyObject oj = new MyObject(value1, value2); 
    arrayOfMyObject[i]=oj;}
    
    Code:
    
    MyObject oj; for(int i=0;i<3;i++) {
    ...Here I enter some values to create an object... 
    oj = new MyObject(value1, value2); 
    arrayOfMyObject[i]=oj;}

    While I agree with BeholdMyGlory's explanation, I would like to put forward another way to understand the difference better:

    When we declare an object, regardless of within or outside loops, in this manner:

    Java Code:
    MyObject oj;
    //continue coding
    This means that we have created an object of the name oj that has data attributes of the class 'MyObject'. However, oj has no reference to anything in the computer's memory.

    It is only when we do this...

    Java Code:
    oj= new MyObject(argument 1, argument 2);
    ...that a reference to the object 'oj' is created in the memory. By that, I mean there is now a specific memory address allocated to this object.

    The benefits of doing this are:

    1) You can create references to the object several times in your code, while only declaring it once, thereby saving you some effort, albeit just a little.
    But for example, if you are using more than one constructor, than it makes sense to declare the object globally, and create references to it as required in your code subsequently. We can do it the other way too, over here, it becomes a matter of preference.

    2) As BeholdMyGlory explained, you will be able to use the object outside of any loops.

    Hope that helps create a clearer picture :)

  6. #6
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Wink exhausting heap space...

    Actually, a good question. Last night I was trying to make some improvements in code, I decided to move a call to new inside a loop:
    Java Code:
    first_message_digest =  MessageDigest.getInstance("SHA-1");
    which ran on dozens of individual strings. The machine bogged so badly that I had to go shutting down programs just to get a controlled shutdown.

    I moved the MessageDigest to a static, class variable. That put's it .... sorta have to think about this several minutes but you are thinking anyway so let's get into some details.

    Take the String class for the example:
    Java Code:
    String someString;
    someString = new String("example:");//
    can be coded, as your thinking will first discover:
    Java Code:
    String someString = "example:";
    below this simplification, several things happen:
    Java Code:
    char[] characterArray = {'e','x','a','m','p','l','e',':'};
    String someString = new String(characterArray);//
    which, if you read the documentation, is supposed to be that strings are immutable.

    LOL

    Try this:
    Java Code:
    // as above, plus...
    characterArray[6] = 'l';
    System.out.println(someString);
    should print exampll:, not what you thought.

    Okay, short version is that you may code something along the lines of JSomething = new JSomething(); in the outer scope, aka class variables.

    Then, we get into some finess. The machine will not let one do
    Java Code:
    private static transient MessageDigest first_message_digest = new MessageDigest();//
    because the construtor is protected:
    Java Code:
    protected MessageDigest(String algorithm)
    After spending hundreds on books and perhaps a hundred hours studying, you arrive at:
    Java Code:
    public static MessageDigest getInstance(String algorithm)
    throws NoSuchAlgorithmException
    but you cannot put a try block there so I just moved it to the inner loop of the method call as one message digest was already being used after the loop finished. That's when the machine bogged.

    Reading the docs several times, I decided to try the idea that:
    Java Code:
    // Completes the hash computation by performing final
    // operations such as padding. The digest is reset after this call is made.
    public byte[] digest()
    actually does what the docs say. To do that, I have to accomodate the try catch block. We can put that in an init() as there is no easy way to propogate a failed call to new, in this example done as getInstance() rather than with the keyword new.

    That is called static factory method, I use them copiously now in first design having drug the Ocean bottom on the issue you are raising. In fact, though it seems tedious and needlessly complex, I have a boolean init() in any code that is not for newbies......

    In that init(), I set a global Boolean and do:
    Java Code:
        *****_Reporting wjwr = new *****_Reporting();
        if(wjwr.validInstance())
        {
            // code goes here...
        }
        else
        {
            return;//
    proprietary blotted for posting, that is from code I wrote last night on my own work that will ship.

    code for valid instance is:
    Java Code:
        //
        boolean validInstance()
        {
            return *****_Reporting.this.isValid.booleanValue();
        }
    the comment, if you fill it in, should read: "Always do this."
    When you do:
    Java Code:
    MyObject oj; for(int i=0;i<3;i++) {
    ...Here I enter some values to create an object... 
    oj = new MyObject(value1, value2); 
    arrayOfMyObject[i]=oj;}
    that moves the call to new inside the loop, oj is only a label in the code and an example of correct array initialization. For my code, I placed the label inside the loop, and did
    Java Code:
    MessageDigest madDog = MessageDigest.getInstance("SHA");
    MessageDigest.getInstance("SHA");
    which brought the machine to a sludge like crawl. A $295 toy computer from the toy department would have been more powerful right that moment.

    So I tried moving the variable outside the loop, calling new inside the loop and doing:
    Java Code:
    MessageDigest madDog = null;
    System.gc();
    .... at that point is when I had to be reasonably patient just to get to a vulcan choke hold.

    Screwy part of all this is that commercial software is even worse, requiring a complete re-install of the entire software suite ( along with ignorant questions about your "rotating gradient of the hour selection preferences" ) hooking the machine with Tabby The Cat's claws which have recently been somewhere we do not usually visit.
    Last edited by Nicholas Jordan; 12-25-2008 at 05:30 PM. Reason: code tags
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  7. #7
    diggitydoggz is offline Member
    Join Date
    Dec 2008
    Posts
    55
    Rep Power
    0

    Default

    Thanks for the reply guys. Makes more sense now.

  8. #8
    PatoDB is offline Member
    Join Date
    Dec 2008
    Posts
    14
    Rep Power
    0

    Default

    Ok.... I think im understandig it better...

    One more question:

    If i do this:
    Java Code:
    for(...)
    {...
    MyObject oj = new MyObject(p1, p2);
    ...}
    It means that, when the program go into the for, I'm going to have "n" objects dispersed for all the memory? And if I do this:

    Java Code:
    MyObject oj;
    for(...)
    {...
    oj = new MyObject(p1, p2);
    ...}
    I'm going to have only One object that it's going to be like a "container", of all the diferents values assigned to it in the for?
    ..:: abretumundo.wordpress.com ::..

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You need to be careful about confusing objects and references to objects. "oj" is a reference, and no matter how you declare it, each call of "new" creates a new object whether or not a new reference points to it or not.

  10. #10
    PatoDB is offline Member
    Join Date
    Dec 2008
    Posts
    14
    Rep Power
    0

    Default

    Oks... I always get trouble with references.. xD

    Now I understand much better, but one last question to get it :P

    If I put inside the for:

    Java Code:
    MyObject oj = new MyObject(p1, p2);
    I'm going to be switching the "value" of the oj reference for every cicle of the for?

    But if I declared
    Java Code:
    My Object = oj;
    outside the for, it will work with only one reference?
    ..:: abretumundo.wordpress.com ::..

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    The main difference that I see is if you declare a new oj from within the loop, once you exit the loop, oj will not exist, and objects that it referred to may be garbage collectible (if there are no other dangling references to them). On the other hand if you declare oj before the loop, when the loop is over, the last object that oj was referenced to will remain associated with oj and will not be available for gc until you leave the scope of where oj was declared. This usually is not be a big deal but in some instances it can be.

  12. #12
    PatoDB is offline Member
    Join Date
    Dec 2008
    Posts
    14
    Rep Power
    0

    Default

    Ok!

    Thx a lot! And sorry if I ask a lot.. :P

    But i want to make the Java Certificated in 2009, so i need to study and leave all the doubts..

    Thx!
    ..:: abretumundo.wordpress.com ::..

  13. #13
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    Not too much to ask, it much worse if do not ask these questions.

    Neither form create " a bunch of objects " as Object MyObject; is just like a mailbox or cubby hole. Each new puts the new object in the same place, it is one of the fundamental notions of computer science: All that one can do is set location y from location x. And do some compare x to y in the processor, including a rather short set of logical gates.

    All arithmetice and moves and everything else is some descendent of a rather limited instruction set.

    Rich instruction set platforms just have combinations of the these hardwired into the processor.

    if you do

    List someList = new List();
    for(;;)
    {someList.add( new MyObject();)}

    then you get a machine that is slowing down and of little value in real settings.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

Similar Threads

  1. Declaring variables
    By Flashmatix in forum New To Java
    Replies: 12
    Last Post: 01-20-2009, 04:43 PM
  2. Replies: 3
    Last Post: 11-24-2008, 08:01 PM
  3. Assigning a string value to a char
    By coffeebean in forum New To Java
    Replies: 4
    Last Post: 06-15-2008, 07:30 AM
  4. Assigning Threads on Multiprocessor?
    By DrRufus in forum Advanced Java
    Replies: 1
    Last Post: 08-08-2007, 11:55 PM
  5. Replies: 1
    Last Post: 08-07-2007, 12:10 AM

Posting Permissions

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