• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why this Precision Error  RSS feed

 
sopal Pal
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I have this simple program

=====

public class Hello
{

public static void main(String[] args)
{
long size = 123456789l;
int arr[] = new int [size];
}
}
=====

Why does the compiler give the error

Hello.java:7: possible loss of precision
found : long
required: int
int arr[] = new int [size];
^
 
Steve Simon Joseph Fernandez
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I think it is because Java expects all array sizes to be int. Thus, it forces size to be converted to an int, and warns you of the loss in precision.

_steve.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Steve Simon Joseph Fernandez:

I think it is because Java expects all array sizes to be int.


That would explain why it's saying "required: int, found: long"...
 
sopal Pal
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Isn't it strange that array indices cannot exceed the int limit.
So if I need to have an array whose size is greater than int ( max ) my only alternative is to use linked list kind of things - right ?
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Isn't it strange that array indices cannot exceed the int limit.
Not really "strange", per se. The language is specified that way.

So if I need to have an array whose size is greater than int ( max ) my only alternative is to use linked list kind of things - right ?
I'm unaware of any theoretical upper limit on the number of elements in a LinkedList. I would imagine that memory and performance constraints would typically be a problem long before you reached the 2 billion+ limit on an array-backed structure, though.

I'm sure they're out there, but I haven't had the "fortune" to work with an application that required an array approaching Integer.MAX_VALUE size...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!