Java Foundations 6 Flashcards
What is implicit (widening) type casting in Java?
Automatically converting a smaller type to a larger type (e.g., int to long).
Give an example of implicit type casting.
int a = 5;
double b = a;
// int to double (widening)
What is explicit (narrowing) type casting in Java?
Manually converting a larger type to a smaller type using parentheses (e.g., double to int).
Give an example of explicit type casting.
double d = 9.7;
int i = (int) d; // i becomes 9
Why can narrowing conversion cause data loss?
Because the destination type may not be able to hold all the values of the original type (e.g., decimal is truncated).
What are Java’s 8 primitive types?
byte, short, int, long, float, double, char, boolean
What are wrapper classes in Java?
Object representations of primitive types (e.g., Integer for int, Double for double).
Why use wrapper classes?
For collections (List, Map), nullability, and using utility methods (e.g., Integer.parseInt()).
What is autoboxing in Java?
Automatic conversion of a primitive to its corresponding wrapper object (e.g., int → Integer).
What is unboxing in Java?
Automatic conversion of a wrapper object to its corresponding primitive (e.g., Integer → int).
Example: What does this line do?
List<Integer> list = new ArrayList<>();
list.add(5);</Integer>
Autoboxes the int 5 into an Integer object and adds it to the list.
Can you cast between unrelated wrapper classes (e.g., Integer to Double)?
No, wrapper classes are final and don’t extend each other. You must unbox and then cast primitives.