Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define multiple variables in single statement

Tags:

java

arrays

In Python, I can define two variables with an array in one line.

>>>[a,b] = [1,2]
>>>a
1
>>>b
2

How do I do the same thing in Java?

I have a couple of variables in class PCT which type is final. Is there a way to define them in one line in a Python like fashion? The following format clearly does not work in Java. I could define them separately, but it will call the parseFile method twice which I want to avoid.

public class PCT {
    final int start;
    final int stop;
    public PCT (File file) {
        //......
        //......
        // the following statement does not compile
        [start, stop] = parseFile(file);
    }
    public int[] parseFile(File f) {
        int[] aa = new int[2];
        // ....
        // ....
        return aa;
    }
}
like image 600
Nasreddin Avatar asked May 14 '15 22:05

Nasreddin


People also ask

How do you define multiple variables in one line?

When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator.

How do you assign multiple variables to one value?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

How do you #define multiple variables in C?

Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

Can you declare variables in one line?

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.


1 Answers

You can define multiple variables like this :

double a,b,c;

Each variable in one line can also be assigned to specific value too:

double a=3, b=5.2, c=3.5/3.5;

One more aspect is, while you are preparing common type variable in same line then from right assigned variables you can assign variable on left, for instance :

int a = 4, b = a+1, c=b*b;

Noticed, you can also practice arithmetic operations on variable by remaining in the same line.

like image 145
Syed Shaharyaar Hussain Avatar answered Sep 18 '22 21:09

Syed Shaharyaar Hussain