Loading

Q1. Which primitive data types should be used to store student count, average grade, and pass / fail status?
The choice of primitive data types depends on the nature of the data being stored:

  • int Used to store the number of students because it represents whole numbers without decimals.
  • double Used for the average grade because it can store decimal values with higher precision.
  • boolean Used to represent pass or fail status, as it stores only two values: true or false.
Selecting the correct data type improves memory usage, performance, and code readability.


Q2. While primitive data type is the most memory-efficient for storing small whole numbers ?
The byte data type is the most memory-efficient option for storing small whole numbers.

  • It uses 8 bits (1 byte) of memory.
  • It can store values from –128 to 127.
This makes byte ideal for memory-constrained environments when the values fall within its range, such as storing small ages or counters.


Q3. Why does integer division affect the result when assigning to a double variable ?
In Java, when both operands of a division operation are integers, integer division is performed. This means the decimal part is discarded before the result is assigned to the double variable.

Example

int totalMarks = 451;
double percentage = totalMarks / 5;

Here, totalMarks / 5 is evaluated as integer division, resulting in 90, which is then converted to 90.0.

Solution
Make at least one operand a double to force floating-point division:

double percentage = totalMarks / 5.0;

This ensures accurate decimal results.


Q4. Why do changes to primitive variables not affect the original value, but changes to arrays do ?
Java uses pass-by-value for method calls.

  • Primitive data types store actual values. When passed to a method, a copy of the value is created, so changes inside the method do not affect the original variable.
  • Arrays are reference types. When passed to a method, a copy of the reference is passed, which still points to the same array in memory. Therefore, modifications to the array affect the original data.
This behavior explains the difference in how primitives and arrays behave when passed to methods.


Q5. Why cannot primitve data types be used directly in Java Collections ?
Java Collections framework works only with objects, not primitive data types.

Primitive types like int, double, and boolean are not objects, so they cannot be used directly in collections such as List, Set, or Map.

Solution
Use the corresponding wrapper classes, which are object representations of primitive types.

Example

List<Integer> rollNumbers = new ArrayList<>();

Here, Integer is the wrapper class for int. Java also supports autoboxing, which automatically converts between primitives and their wrapper classes.