A local variable in Java with the same name as a global variable

I am trying to understand scope in Java. In Perl, I can do the following:

my $x = 1;
{
    my $x = 2;
    say $x; # prints 2
}
say $x; # prints 1

In other words, since I declared the variable $ x c mywithin the scope, the variable $ x in this scope is local to that scope (that is, not the same variable as the global variable $ x). Now, in Java, I'm trying to do something like this, but I get an error

The rawURL variable is already defined in the run () method

Here is the code:

// Global rawURL
URI rawURl;
try {
  rawURL = new URI("http://www.google.com");
} catch (Exception e) {
  // Handle later
}

// Some time later
for (Element link : links) {
  // rawURL in this scope
  URI rawURL;
  try {
    rawURL = new URI(link.attr("abs:href"));
  } catch (Exception e) {
    // Handle later
  }
}

So the thing is, I don’t want to have to create declarations for all my variable names, ensuring that each one is different. I just use rawURL to create a normalized URL, so it is essentially a temporary variable. I could just do this:

for (Element link : links) {
  rawURL = new URL(..);
}

, . , ?

+4
3

, : + . , rawURL , "", , for.

java :

{
   String myvar = "";
}

{
   String myvar = "";
}

:

String myvar = "";
{
    String myvar = "";
}

().

+3

java public private access , , , , , . , .

public class abc{
    public int a; //global and accessible by every class outside this class too 
    private int b; //global and accessible only within this class
    private void m(){
        int x; //local and accessible only within this method 
    }
}

public void m(){
    for(;;){
        int a;
    }
    for(;;){
        int a;
    }
}

public void m(){
    int a;
    for(;;){
        int a;
    }
}

, .

+1

Java - ,

rawURL run()

JLS , :

6.4.

, v v, ​​ , v.

, v , .

, Perl, " ", " ".

void method1() {

    int x;
    {
        int y = x; // O.K. - x is in scope.
        int x = y; // Not O.K. - x is in scope and was already declared.
    }
    x = y; // Not O.K. - y is not in scope.
}

, :

void method2() {

    int x;            
    class InsideClass {                             
        {             
            int y = x;
            int x = y;
        }             
    }
}      

, , .

+1

Source: https://habr.com/ru/post/1622518/


All Articles