Search code examples
javadynamic-bindingstatic-binding

Can Java have dynamic type binding for variables?


Can variables have dynamic type binding in Java? I know that methods can, but I don't think that variables can since every variable has to have a type declaration when it is created such as int, double, or float. If they can, how would that be done? Thanks.


Solution

  • Starting with Java 10, the var keyword was introduced to allow local variable type inference, which means the type for the local variable will be inferred by the compiler, so you don’t need to declare that. For example,

    var myNum=0;// At this moment, compiler interprets as an integer
    

    So if later on you attempt to assign a String value to it, it will throw an error. Notice that I emphasize this to be true only of local variables.