I'm 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 with my
within the scope, the $x variable in that scope is local to that scope (i.e., not the same variable as the global $x variable). Now, in Java I am trying to do something similar, but I am getting the error
Variable rawURL is already defined in method run()
Here's 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
}
}
Now, the thing is, I don't want to have to get creative for all of my variable names, ensuring each one is different. I am simply using rawURL to build a normalized URL, so it's essentially a temporary variable. I could just do this:
for (Element link : links) {
rawURL = new URL(..);
}
But then that will change the contents of my global variable, and I really don't want that. Is there any way to use the same name for the local variable as I am using for the global variable?
You must define a new local variable with a new name because scope of variable is like: current block + subblocks. So in your case, rawURL is defined for what you called "global" and it is visible to subblocks, ie into the for block.
In java, you can do :
{
String myvar = "";
}
{
String myvar = "";
}
because here, there are two different blocks at same level
but you can't do :
String myvar = "";
{
String myvar = "";
}
because there is conflict with same name for two variables in same block (the subblock).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With