-3

Why it is not allowed to declare Array with 2 identifiers like the below mentioned syntax: -

int []a,[]b;

in java.I know it throws compile time error but I need to know why it is prevented to declare array with above Syntax?

Srikanth R
  • 13
  • 2

4 Answers4

2

int []a,[]b; is invalid because [] should be with a type name like int[]. Variables declared after int[] will be arrays of type int.

You could either do

int []a,b;

or

int []a;
int []b;
Yousaf
  • 27,861
  • 6
  • 44
  • 69
1

You could try it like this:

int[] a, b;

int[] means that the following variables will be arrays of int.

int means that the following variables will be ints.

So:

int[] a, b;

means that a and b will be arrays of int. However:

int a[], b;

means that a will be an array of ints, b will just be an int.

int []a; runs fine. int []a, b; is illegal

Try putting those brackets after the type or variable names.

SlumpA
  • 882
  • 12
  • 24
  • Thanks for the response but would like to know the possible decleration instead can you tell why declaring with such syntax is prevented int []c,[]d ? – Srikanth R Jan 21 '17 at 09:58
0

Look at array syntax

int[][] a = new int[1][2];

You can also initialize it like so:

int[][] a = new int[2][2]{
{1,2} // first row
{3,4}, // second row
};
Beri
  • 11,470
  • 4
  • 35
  • 57
0

When you declare array in java, The JVM creates a class for the declared array. For example int[] sampleArray; will have a class int[].class so the type of the sampleArray will be int[].class

why it is prevented to declare array with above Syntax?

int[] is a different type than int. So its is more appropriate to write int[] a,b; than int a[],b[]

Refer This SO

Community
  • 1
  • 1
mahesh
  • 1,311
  • 1
  • 13
  • 26