File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Two Dimensional Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Two Dimensional Array" Watch "Two Dimensional Array" New topic

Two Dimensional Array

Bobby Joseph

Joined: May 29, 2010
Posts: 1

This program generates the following errors..

found : double
required: float
float twoD[][] = { {9*3.2 , 5.2-2 , 7*5},{9*6 , 6-2 , 8*5},{32*6 , 0-2 , 8*5}};
possible loss of precision

Can any one explain the error. I changed the float to double and the error vanishes.

This is the output generated

28.8 3.2 35.0
54.0 4.0 40.0
192.0 -2.0 40.0

But all these are float values. I know it is something related with type casting but can someone tell me exactly what is going wrong.
Sujeet Kumar Jaiswal

Joined: Mar 07, 2010
Posts: 17
Actually, by default a decimal number is double in java. Hence, 9*3.2 & 5.2-2 will result in a double number which cannot be directly casted to float. Try

float twoD[][] = { {9*3.2f , 5.2f-2 , 7*5},{9*6 , 6-2 , 8*5},{32*6 , 0-2 , 8*5}};

This will work as suffixing 'f' with a decimal number makes it float.


float f = 3.2 (compiler error)
float f = 3.2f (compiler happy)
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46412
Welcome to the Ranch

I shall add code tags to your post, so you can see how much easier it is to read (if it is indented).

I shall also go all pedantic and remind you there is no such thing as a 2D array. Java™ only supports arrays; what you have as a float[][] is an array of arrays.
I agree. Here's the link:
subject: Two Dimensional Array
It's not a secret anymore!