Q: Can I change the declaration type for a variable in Java?
For e.g.,
public class Tmp{
public static void main(String[] args) {
String s = "Foo";
s = null; //same Error results whether this line included or not
int s = 3;
System.out.println(s);
}
}
But attempted compilation results in the message:
Error: variable s is already defined in method main(java.lang.String[])
Oddly, re-declaring the type of a variable works just fine in an interactive DrJava session:
> String s = "Foo"
> int s = 1
> s
1
What's going on?
Declaring (Creating) Variablestype variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
A constant is a variable whose value cannot change once it has been assigned.
A variable is only a name given to a memory location. All the operations done on the variable affect that memory location. In Java, all variables must be declared before use.
Rules to Declare a VariableA variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and two special characters such as _ underscore and $ dollar sign. The first character must not be a digit. Blank spaces cannot be used in variable names. Java keywords cannot be used as variable names.
Can I change the declaration type for a variable in Java?
No, the compiler knows that s
already exists within the same scope and is declared of type String
.
I've never used DrJava before but as an interactive interpreter, it may be able to de-scope the first variable and replace it with the one declared in the new statement.
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