0

the question is newbie, but i did not understood why primitive types in Java or other OOL can not be casted. What i mean is why you can not do:

    int k = 1;
    String t = (String) k;

I know that primitive types are not classes, but i would like to know about the core of this reason.

4 Answers4

3

You can always cast (implicitly) narrower primitive types to wider primitive types. This is called widening primitive conversion. For example:

int i = 10;
long l = i;

And you can cast wider primitive types to narrower primitive types explicitly. This is called narrowing primitive conversion. In this case you tell the compiler that you know what you are doing, because a narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.

long l = 10;
int i = (int)l;

See the documentation here.

pepe
  • 814
  • 8
  • 12
2

A cast doesn't convert the content in memory. It just changes the view how to access the content. There is no valid way how a 1-byte int can present the 2-byte String "32".

You can of course cast 1 byte primitives, but I guess it's not what you expect:

@Test
public void castTests() {
    assertEquals('7', (char) 55);
    assertEquals(55, (int) '7');
}

The cast won't change the content in the memory. So your int 55 becomes the String representation of the byte 55 which is "7".

Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67
1

Here is the documentation on Java variable conversions including casting.

You might find this discussion on Java casting easier to understand.

As long as you use a cast operator or expression and the specific variable type conversion is allowed by the rules of Java then you can cast primitive types. You do need to follow the conversion rules however.

I am not sure about other object oriented languages however in C++ you can do all kinds of nasty casts if you want to go there using the C style casts. Because you can end up in a world of hurt, the use of C++ style casts are much preferred over C style casts since the compiler will check the cast.

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
1

You can cast primitive types in java. Casting from narrower, smaller memory size, types to wider, larger memory size, types is implicit. Example:

int i= 0 ;
long j = i;   // implicit cast from int to long

Casting from larger types to smaller are explicit. You tell the compiler to cast from wider type to narrower type by specifying the narrower type in parenthesis with the following syntax i = (int) j; Example:

long j = 0;
int i = (int) j;   // explicit cast from long to int
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
Deep
  • 21
  • 2