Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java one line variable declaration? [closed]

Tags:

java

In my Java class i am declaring variable like this

BigDecimal sumFeeBilled = new BigDecimal(0), sumPaid = new BigDecimal(0); 

Or we have to declare like this in multiple line

BigDecimal sumFeeBilled = new BigDecimal(0);
BigDecimal  sumPaid = new BigDecimal(0);

Which one we should follow ?

like image 880
Subodh Joshi Avatar asked Nov 21 '13 09:11

Subodh Joshi


People also ask

How do you declare a line in Java?

To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ( ; ). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).

Is it possible to declare different types of variables on the same line in Java?

Declaring each variable on a separate line is the preferred method. However, multiple variables on one line are acceptable when they are trivial temporary variables such as array indices.

How do you initialize two variables in one line in Java?

int a, b, c; You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b .


1 Answers

The less things that happen on a single line the better. If you choose the second option the code will be easier to debug(you can put a breakpoint on the line where the second initialization happens skipping the first one for instance) and easier to read(IMHO). The only thing that this costs you is a single line. I think it is worth it.

like image 195
Ivaylo Strandjev Avatar answered Oct 01 '22 02:10

Ivaylo Strandjev