declaring a var inside a loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JavaJon
    New Member
    • Mar 2009
    • 2

    declaring a var inside a loop

    Hello, I'm Jon.

    I've recently picked up Java after using a "gimmick" programming language called GML ( Game Maker Language ). I've read a lot of tutorials and even a Java for Dummies *.pdf book. The basics are similar to what I'm accustomed to but there's still some confusion.

    I'm currently playing around with how the static, public, protected etc things work and I stumbled upon a problem.

    In the following copypasted code ( a tutorial I slightly modified ) the problem occurs inside the main(Strings args[]) thingy near the end.

    Code:
    public class ThisPointerExample {
    
      public static void main(String[] args) {
        HumanBeing me = new HumanBeing("Brown");
        
        
        while(true)
        {
            HumanBeing your = new HumanBeing("Blue"); /* *** noteworthy line *** */
            break;
        }
    
        System.out.println(me.isEqual(your)); /* *** problem is here with "your" It seems the variable "your" is not declared - that's what the error says anyways. I would have thought it woul be declared inside the while() loop *** */
      }
    }
    
    class HumanBeing {
    
      private String eyeColor;
    
      public HumanBeing(String color) {
        this.eyeColor = color;
    
      }
    
      public String getEyeColor() {
        return eyeColor;
      }
    
      public boolean isEqual(HumanBeing your) {
        return this.eyeColor.equals(your.getEyeColor());
      }
    }
    Could someone explain to me why the your variable isn't declared. And if it is declared, where is it? Since it seems the main() thingy doesn't recognize it.

    Here are some of my thoughts:
    1. A variable declared inside a loop will be discarded after the loop ends and the memory of this variable is freed because the variable is local to the loop and not the class.
    2. However, adding a "this." inside the variable declaration doesn't fix this problem. I'm thinking this would tell java to store the variable with the class and not the loop - why doesn't this work? And what would be the proper way to declare a variable to a class inside a loop?

    Thanks in advance.

    - Jon
    Last edited by pbmods; Mar 14 '09, 09:52 PM. Reason: Added CODE tags.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Indeed, that variable is declared in the body of that while loop and when that loop has finished your variable has gone out of scope as well and therefore doesn't exist anymore (you can't use it anymore). Also at every iteration of that loop a new variable is defined and any previously declared variable (from a previous pass through the loop if applicable) is gone.

    kind regards,

    Jos

    Comment

    Working...