What is type casting in Java?
A
Changing variable types permanently B
Assigning one type of value to a variable of another type C
Copying values from one variable to another D
None of the above
Analysis & Theory
Type casting is converting one data type into another.
Which of the following is an example of implicit casting in Java?
A
int x = (int) 5.5; B
double d = 10; C
char c = (char) 65; D
float f = (float) 5;
Analysis & Theory
Assigning an `int` to a `double` is implicit casting because it happens automatically.
What is required for explicit type casting in Java?
A
The `new` keyword B
An assignment operator C
A type cast operator like (int), (double), etc. D
A loop
Analysis & Theory
Explicit casting uses a type cast operator like `(int)` to manually convert data types.
What will the output be?
`int x = (int) 5.9; System.out.println(x);`
A
5 B
6 C
5.9 D
Error
Analysis & Theory
Casting from double to int truncates the decimal part. Output is `5`.
Which type of casting is also called narrowing conversion?
A
Implicit casting B
Widening casting C
Explicit casting D
Reference casting
Analysis & Theory
Explicit casting (e.g., `double` to `int`) is narrowing because you're converting to a smaller type.
Which of the following is a valid example of widening casting?
A
int x = (int) 3.5; B
double d = 10; C
byte b = 1000; D
int i = 'A';
Analysis & Theory
`double d = 10;` is widening (int to double) and done automatically.
What will the output be?
`char c = (char) 66; System.out.println(c);`
A
B B
66 C
Error D
C
Analysis & Theory
Casting 66 to char gives 'B' because 66 is the ASCII code for 'B'.
Which of the following conversions can cause data loss?
A
int to long B
float to double C
double to int D
byte to short
Analysis & Theory
Casting `double` to `int` can result in loss of fractional data.
What will the output be?
`byte b = (byte) 130; System.out.println(b);`
A
130 B
-126 C
Error D
0
Analysis & Theory
`byte` ranges from -128 to 127. Casting 130 causes overflow and results in -126.
Which type of casting is safe and does not cause loss of data?
A
Narrowing casting B
Explicit casting C
Widening casting D
Downcasting
Analysis & Theory
Widening casting (like `int` to `double`) is safe and does not lose data.