0

I'm wondering how I do the following. Make 10 int variables called, var_0, var_1, var_2, etc. All holding 0. I'm picturing something like this...

for(int i=0;i>10;i++){
   int var_i = 0;
}

But of course it doesn't work. How do I make this work without doing every single variable manually?

It's intended for an arbitrary amount of variables.

2
  • If they're all holding 0, why do you need 10 of them?? Commented Sep 12, 2012 at 17:22
  • I dont know the amount, I see know that int was a bad example. I'll do an array with Objects. Commented Sep 12, 2012 at 17:25

4 Answers 4

3

It's impossible in Java, there are no macros that would let you do it. Usually if you need 10 variables with same name you just use array.

int vars[] = new vars[10];

It will be initialized to zeroes by default.


If you don't know number of elements in advance you can declare array and construct it later:

int vars[];
...
int numVars = 10;
vars = new int[numVars];
Sign up to request clarification or add additional context in comments.

Comments

1

That is not possible, even if it creates it would be local to loop, so why not populate a List there

List<Integer> numbers = new ArrayList<Integer>();
for(int i=0;i>10;i++){
   numbers.add(0);
}

Comments

1

Thats not possible, so better go with arrays.....

int[] arr = new int[10];

for(int i=0 ; i<10 ; i++){


      int[0] = 0;

 }

Comments

1

It's intended for an arbitrary amount of variables.

It sounds like you really want an array of 10 int:

int vars[] = new int[10];

The elements will be initialized to 0. If you need to initialize to something specific, besides zero:

for (int i = 0; i < vars.length; i++)
{
    int vars[i] = 7;
}

You could also declare 10 int, and initialize them in a single statement:

int var1, var2, var3, ...;
var1 = var2 = var3 = ... = 0;

2 Comments

Re: "Note that an int in java is initialized to 0 by default": That's not exactly true. When an int in Java is initialized by default (because it's an element of an array, or it's a non-final field, or a final field that you've hacked around the initialization requirements for), it's initialized to 0, but it's not always true that any default initialization takes place: with local variables, the language requires you to perform the initialization, and issues a compile-error if it can't prove that you've done so.
instance variable int will initialize by 0, but not local.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.