Search code examples
javastrong-typingdynamic-typing

How to create dynamic variables in Java?


For example, in Haxe I can create strictly typed variables: var a:Float = 1.1; or var b:String = "hello" and also dynamic, if needed:

var d:Dynamic = true; d = 22; d = "hi";

How do I create this kind of variables in Java?


Solution

  • You can use Object

    Object d = true; 
    d = 22; 
    d = "hi";
    

    and you can use instanceof operator to check which type of data d is holding

    Object d = true; 
    System.out.println(d instanceof Boolean); // true
    d = 22; 
    d = "hi";       
    System.out.println(d instanceof Integer); // false
    System.out.println(d instanceof String);  // true
    

    The Type Comparison Operator instanceof