CREATE VARIABLE DYNAMICALLY IN JAVA AND WHAT ARE DATA TYPES OF VARIABLE

Allen Scott

Total Post:46

Points:324
Posted by  Allen Scott
 1008  View(s)
Ratings:
Rate this:

As we know variables are of different data types, but which data type are their names of?
As it seems they are String, but if they are String then this should be allowed:

int i=6;

String [] arr+i;

...as we can add an int to a String.
So if these are not String then what are they?
And if we want to create variable names dynamically how can we create it? By dynamically I mean whenever the user clicks on a specific JComponent, a new variable is created, like:

int i=0;

//on first click

String str+i; ///str0

i++;

///on 2nd click

String str+i;   ////str1

///i++;

How can I do it?

  1. Kamlakar Singh

    Post:28

    Points:196
    Re: Create variable dynamically in java and what are data types of variable

    You can not create dynamic variables in Java because Java isn't a scripting language. YOu need to create variables in source code. But Java provides other ways to do this. You can use arrays or Map<String, String> etc for this purpose.

    Map<String, String> map= new HashMap<>();

    int i=0;

    while(true) {

    // you can use whatever condition you need

        details.put("key" + i, "val: "+i);

    i++

    // some condition to break the loop

    }    

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!