Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Whats the difference between int[]a=new a[4]; and int a[]=new a[4];

 
midhuna peru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys is there a difference between
int[]a=new a[4];
and
int a[]=new a[4];
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
midhuna peru wrote:Hi guys is there a difference between
int[]a=new a[4];
and
int a[]=new a[4];


They'll both give compiler errors because "a" is not a recognized type, or, if you've declared a class called "a", it's not assignment-compatible with int. Presumably you meant "... = new int[4]".

As far as the compiler is concerned, there's no difference in that particular case. There can be differences when declaring multiple variables on one line, but you should never do that anyway, so it's a non-issue.

The first one is generally preferred as a matter of convention, though with some whitespace:

 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, there is no difference. They are the same. Both fail. But they are the same.

int[] a and int a[] both define a variable named a which holds an int array. And in both cases, = new a[4]; would fail because that creates a new array of the class a and attempts to assign it the array or ints, which fails because an array of class a is not an array of ints


[edit]: dang too slow on the draw
 
midhuna peru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeff Verdegan wrote:
They'll both give compiler errors because "a" is not a recognized type, or, if you've declared a class called "a", it's not assignment-compatible with int. Presumably you meant "... = new int[4]".


Yah my mistake....what i meant was int[] a=new int[4]
 
Campbell Ritchie
Sheriff
Posts: 48431
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler will interpret them like this. It interprets one as meaning, “I want an array of ints called …”
and the other as, “I want an int, oh no, make that into an array and call it …”
Both versions will produce the same result.

A human reader will understand that the type of a is int[], so the version with the [] before a is preferred.
The type of a is not int, so the version with[] after a is not recommended.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic