Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 652
shal Avatar asked Mar 09 '17 16:03

shal


People also ask

How do I create a dynamic variable name?

In programming, dynamic variable names don't have a specific name hard-coded in the script. They are named dynamically with string values from other sources.

How do you create 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.

How do you define a dynamic variable?

A dynamic variable is a variable you can declare for a StreamBase module that can thereafter be referenced by name in expressions in operators and adapters in that module. In the declaration, you can link each dynamic variable to an input or output stream in the containing module.

What is dynamic initialization of variables in Java?

If any variable is not assigned with value at compile-time and assigned at run time is called dynamic initialization of a variable. Basically, this is achieved through constructors, setter methods, normal methods and builtin api methods which returns a value or object.


1 Answers

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

like image 51
Pavneet_Singh Avatar answered Oct 16 '22 19:10

Pavneet_Singh