Sam Seekamp
Sam Seekamp

Reputation: 5

Initialize multiple variables at the same time after a type has already been defined in Java?

Need a little bit of help with syntax here. I'm trying to re-initialize multiple variables after the type has already been defined. So for example

int bonus, sales, x, y = 50; 

This works fine... however I want to put a different value into some of those variables later on in my program, but I'm getting a syntax error.

bonus = 25, x = 38, sales = 38;

Compiler is saying I need

another semicolon for bonus and x.

Is there a way to change the values in a single line of code? Or would I have to put a semicolon after each value??

Upvotes: 0

Views: 188

Answers (3)

David
David

Reputation: 1

Method: you can use it, this way.

int bonus=50; sales=50; x=50; y = 50;

In your code only y has been initialized.

if any help visit: http://wwww.logic4code.blogspot.in/

Upvotes: -1

lumo
lumo

Reputation: 800

int bonus = 25;
int x = 38; // or any other value you prefer
int sales = 38;

later you can access the variables

bonus = 35; // and so on...

Upvotes: 0

Andreas
Andreas

Reputation: 159086

I think you are confused as to be behavior of int bonus, sales, x, y = 50;. It initializes y to 50 and leaves the rest uninitialized.

To initialize all of them to 50, you have to:

int bonus = 50, sales = 50, x = 50, y = 50;

You can then change their values:

bonus = 25;
x = 38;
sales = 38;

// or compact
bonus = 25;   x = 38;   sales = 38;

// or to same value
bonus = x = sales = 42;

Unlike the C language where you can use the comma syntax anywhere, in Java you can only use that when declaring the variables, or in a for loop: for (i=1, j=2; i < 10; i++, j+=2)

Upvotes: 2

Related Questions