Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an array contain integers and floats

Somebody asked me: can an array in java contain integers and floats? She got that question from a teacher.

Now my answer was: yes, since you can declare an array of objects and store integers and floats in it.

But now I'm wondering if that is correct, since technically when you store Integer and Float objects in an array, it kind of does contain both types, but if you would "ask" the array he would tell you he contains Objects, and if I don't do bookkeeping or class checks there's no way to tell that there are integers and floats in the array.

On the other hand I still feel it might be the right answer since theoretically the array contains objects of both types.

So I'm asking for a smart opinion: if you were asked (in an interview, a test whatever) wether in java an array can contain integers and floats, yes or no? What would you answer?

like image 962
Samuel Avatar asked Jun 22 '11 09:06

Samuel


People also ask

Can array have float values?

You have to specify the size if you are going to define array float in this way: float array[4]; You can define the array without the size.

Can you add integers and floats?

Yes, an integral value can be added to a float value. The basic math operations ( + , - , * , / ), when given an operand of type float and int , the int is converted to float first. So 15.0f + 2 will convert 2 to float (i.e. to 2.0f ) and the result is 17.0f .

Can an array have integers?

You can use any integer expression for the size of an array, as long as the value is nonnegative.


1 Answers

A int of float does not fit into a Object[] array. However, by autoboxing java will put a Float or Integer into the array instead.

Both Float and Integer extend Number. So you can even make a array of numbers Number[]

Also, you can put a int into a float[], but java will then cast the int into a float. The other way around is also possible, but precision will be lost. (edit: Even from int->float precision can be lost. float->int may lose information about the overall magnitude of the value).

The conclusion would depend on the question. For primitive datatypes a array can not contain the other datatype. If you use a Object array (Integer, Float, Number) the answer would be yes.

like image 90
Dorus Avatar answered Sep 25 '22 10:09

Dorus