Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change declaration type for a variable in Java?

Tags:

java

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?

like image 673
lowndrul Avatar asked Nov 23 '14 17:11

lowndrul


People also ask

How do you declare different types of variables in Java?

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.

Which variable Cannot be changed in Java?

A constant is a variable whose value cannot change once it has been assigned.

Do you have to declare variable type in Java?

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.

What are the rules for declaring variable in Java?

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.


1 Answers

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.

like image 101
M A Avatar answered Sep 28 '22 07:09

M A