Casting

This lesson includes interview questions on casting in Java.

We'll cover the following...

Question # 1

What is casting?

Type casting or simply casting is used to convert an object or variable of one type into another. There are two types of casting:

  • Casting primitives

  • Casting objects

Question # 2

Explain how casting of primitive types works in Java.

When casting between primitive types if the destination can hold a larger value than the source, the cast is implicitly done by the compiler without complaining. There's no loss of information or precision when the destination can comfortably hold the value in the source. This is called a widening cast. For example:

...