Is there any difference between the following two assignment styles?

1174 views java
5

Reading code, I am not if there is any difference between the following two styles?

1

int a = 0;
int b = 0;
int c = 0;

2

int a, b, c;
a = b = c =0;

answered question

In modern coding style ( in terms of clean code practices ), first approach is preferred. From Java perspective, I don't think there is any difference.

2 Answers

8

In this particular case, the results for both of them are the same. They are only syntactically different.

The first one is three variable declaration and initialisation statements whereas the second one is 3 variable declarations and 3 nested assignment statements. In the second one, c = 0 is evaluates first to 0 and c is assigned. Then the expression becomes a = b = 0. Then b = 0 is evaluated to 0 and b is assigned. Finally, a = 0 is evaluated and a is assigned.

Things gets a bit different when you call methods instead of using a constant 0.

First:

int a = someMethod();
int b = someMethod();
int c = someMethod();

someMethod will be called three times. If someMethod returns different things each time it is called, a b c will be all different.

Second:

int a, b, c;
a = b = c = someMethod();

someMethod will only be run once. a, b and c will always be the same value.

posted this
0

Java default int value is 1

So you can define a 1 liner

 int a, b, c;

posted this

Have an answer?

JD

Please login first before posting an answer.