Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring 2-Dimensional arrays in Java

Tags:

javac

Following are the legal array declarations:

int i[][];
int []j[];
int [][]k;
int[][] l;

But if we declare the arrays in a single line we we are getting a SYNTAX error

int [] []i, []j[], k[], l[][];

ERROR: Syntax Error.

Why is this behavior being displayed?

like image 688
Shubhankar Raj Avatar asked Mar 29 '26 23:03

Shubhankar Raj


1 Answers

problem is here

int [] []i, []j[], k[], l[][];
            ^^

In Java after , in declaration section you are allowed to declare new variable with new additional dimensions after it, not before it, so

int a, b[], c[][];

is possible and it is the same as

int a;
ing[] b;
int[][] c;

but

int a, []b; 

is incorrect.

From jls-8.3

More than one field may be declared in a single field declaration by using more than one declarator; the FieldModifiers and Type apply to all the declarators in the declaration.

The declared type of a field is denoted by the Type that appears in the field declaration, followed by any bracket pairs that follow the Identifier in the declarator.

Additional informations are available in 10.2. Array Variables

like image 96
Pshemo Avatar answered Apr 02 '26 19:04

Pshemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!