Loading

Interview Questions of data-types

Scenario 1: Choosing the Right Type

Scenario:


You are building a student grading system. You need to store the number of students in a class, the average grade (which can be a decimal), and whether a student has passed or failed.


Question:

Which primitive data types would you choose for each of these variables, and why ?


Answer:

  • Number of students: int (because it’s a whole number)
  • Average grade: double (to store decimal values)
  • Pass/fail: boolean (to represent true/false)


Scenario 2: Memory Matters

Scenario:


You are developing an application for a device with very limited memory. You need to store small whole numbers, such as the age of children in a kindergarten class (ages 3-7).


Question:

Which primitive data type is most memory-efficient for this use case, and why ?


Answer:

byte is the most memory-efficient primitive type for small whole numbers, as it uses only 8 bits and can store values from -128 to 127.


Scenario 3: Type Conversion

Scenario:


You have two variables

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

But when you print percentage, you get 90.0 as expected. Now, you change totalMarks to 451 and print percentage again, but the result is 90.0 instead of 90.2.


Question:

Why does this happen, and how would you fix it ?


Answer:

This happens because totalMarks / 5 performs integer division before assigning the result to the double variable. To fix it, make at least one operand a double:

double percentage = totalMarks / 5.0;


Scenario 4: Reference Vs. Primitive

Scenario:


You are writing a function that updates a student’s grade. You notice that when you pass an int variable to the function, the original value does not change, but when you pass an array, the original array changes.


Question:

Why does this happen in Java ?


Answer:

Primitive data types (like int) are passed by value, so changes inside the function don’t affect the original variable. Arrays are reference types, so the function receives a reference to the original array and can modify its contents.


Scenario 5: Wrapper Classes in Collections

Scenario:


You want to store a list of student roll numbers in a List. You try to use List<int>, but it gives a compilation error.


Question:

Why cannot you use int in a List, and what is the solution ?


Answer:

Java Collections only work with objects, not primitive types. You should use the wrapper class Integer, so declare it as List<Integer>