0

I'm trying to understand scope and how to use it to declare two variables of the same name in the same method.

Here is the code I came up with to provide an example of a case where this is possible:

int x = 1;
    
if (x != 1) {
    int legal = 1;
}
else {
    int legal = 0;
}

My teacher said this is not an example, as only one variable is being declared based on the value of x. This makes sense, so I figured back to the drawing board. He recommended looking at our classmate's approved examples to get us back on the right track. One of my classmates used this as an example:

int i = 6
if (i>10) {
  int a = 30;
}
else {
  String a = "Hello Class!";
}

He said this was a good example. The only thing I notice different between our two examples fundamentally is that she change the datatype in each depending on the value of i. Does different datatype = different scope? Thank you in advance for any knowledge, I really am trying to learn the grammar behind the code I use.

Nelco
  • 3
  • 2
  • *"Does different datatype = different scope?"* -- no, the different types don't equal different scope. It's the other way around: Scope allows you to create the two different variables of different types but with the same name. – Hovercraft Full Of Eels Sep 06 '21 at 17:50
  • Your first example did not _distinguish_ both `a`s and ofcourse the compiler probably used the same memory slot on the stack for both variables. Pedagogical the teach is right, but be proud that you were technically right too. – Joop Eggen Sep 06 '21 at 18:06
  • 1
    Well, actually, there is no relation between whether a variable is in scope and their data type; they have nothing to do with eachother. Thus, there is no fundamental difference between those two examples. I would argue that the teacher is wrong at this point, if he really stated that "only one variable is being declared". – MC Emperor Sep 06 '21 at 18:47

0 Answers0