xheyhenry
xheyhenry

Reputation: 1069

Redeclaring variables, and scope

I'm currently taking an intro course to CSE and had a question from some material of the class. On one of the slides, the professor defines this method:

public int myMethod()
{
  int retval, itemp = 100;
  retval = itemp;
  {
     int retval, itemp = 75; 
     retval = itemp; 
  }
    return retval;
}

From what the professor said, retval returns/holds a value of 100, but when I opened up Eclipse/Command line and wrote the method, it wouldn't compile. It kept saying that retval was declared twice and therefore would not compile the program. Any guidance for what went wrong here? Also, what's the point of "retval = itemp;" ? They're both initialized to the same value, so is there a purpose for that line?

Upvotes: 2

Views: 6489

Answers (2)

Mateusz Dymczyk
Mateusz Dymczyk

Reputation: 15141

This does not compile because you cannot declare a variable with the same identifier twice in the same scope.

What you can do is to re-declare an existing variable in a given scope:

class MyClass {
  private int myVar = 1;

  public void redeclare() {
    // ...
    int myVar = 2;
    System.out.println(myVar);
    // ...
  }
}

This works because myVar is visible in the scope of redeclare() but wasn't declared in it!

The {} does not create a fully new scope so what your teacher wanted to do fails.

Furthermore:

int retval, itemp = 100;
retval = itemp;

Here the first line declares both retval and itemp but initializes only itemp so retval is uninitialized. That's why the second line assigns the itemp value to it. But since those are primitive values it will copy the value of itemp and put it on the stack so now you have 2 different values. Changing one won't change the other.

No offence to the prof. but if I were you I'd ditch those slides and grab a good book on Java (Core Java or Thinking in Java for instance) and some intro to CS book (since this is is the goal of this course?) like "Structures and interpretations of computer programs".

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Eclipse/Command line and wrote the method, it wouldn't compile. It kept saying that retval was declared twice and therefore would not compile the program.

Better perhaps would be code like so:

public class Foo {
   int retval, itemp = 100;


   public static void main(String[] args) {
      Foo foo = new Foo();
      System.out.println(foo.myMethod());
   }

   public int myMethod() {
      retval = itemp;
      {
         int retval, itemp = 75;
         retval = itemp;
      }
      return retval;
   }
}

Also, what's the point of "retval = itemp;" ?

This sets the retVal variable to hold a value.


They're both initialized to the same value, so is there a purpose for that line?

No they're not. itemp holds a different value in the two locations.

Upvotes: 1

Related Questions