👁 Preview — Study, Practice and Revise are open; mock tests and the rest of the syllabus unlock on subscription. Unlock all · ₹4,999
← Back to Programming Fundamentals
Study mode

Variables and Data Types

Introduction

In programming, a variable is like a labeled storage box in a computer's memory that holds data. Just as you might label a box "Books" to know what's inside, a variable has a name that helps the program remember and use the data stored in it. But not all data is the same - some are whole numbers, some are decimal numbers, some are characters like letters, and so on. This is where data types come in. They tell the computer what kind of data a variable can hold, ensuring the right amount of memory is allocated and the correct operations are performed.

Understanding variables and data types is fundamental to programming because they form the building blocks for storing and manipulating information.

Variables

Let's start by understanding how variables work in programming.

Declaration and Initialization

Declaration means telling the computer that you want to create a variable and specify what type of data it will hold. Initialization means assigning an initial value to that variable.

For example, in many programming languages, you might write:

int age;          // Declaration of an integer variable named ageage = 20;          // Initialization with value 20

Or combine both steps:

int age = 20;     // Declaration and initialization together

Variable Naming Rules

Variable names must follow certain rules to be valid:

  • Start with a letter (A-Z, a-z) or an underscore (_)
  • Can contain letters, digits (0-9), and underscores
  • No spaces or special characters like @, #, $, etc.
  • Should not be a reserved keyword in the programming language (like int, if, while)

Using meaningful names helps make your code easier to read. For example, priceInINR is clearer than just p.

Memory Allocation

When a variable is declared, the computer sets aside a specific amount of memory to store its value. The size of this memory depends on the data type. For example, an int might use 4 bytes, while a char uses 1 byte.

age Memory Location Value: 20

In this diagram, the variable name age points to a memory location that holds the value 20.

Data Types

Data types define the kind of data a variable can store. They determine the size of the memory allocated and the operations that can be performed on the data.

Primitive Data Types

These are the basic data types commonly used in programming:

Primitive Data Types Comparison
Data Type Size (Bytes) Value Range Example Usage
int 4 -2,147,483,648 to 2,147,483,647 Storing whole numbers like age = 25 or priceInINR = 1500
float 4 Approximately ±3.4e-38 to ±3.4e+38 (with decimals) Storing decimal numbers like heightInMeters = 1.75
double 8 Approximately ±1.7e-308 to ±1.7e+308 (more precise decimals) Storing precise decimal values like currency calculations
char 1 Single character (e.g., 'A', 'Rs.') Storing letters or symbols like grade = 'A'
boolean 1 (conceptual) true or false Storing logical values like isAvailable = true

Derived Data Types

These are data types built from primitive types:

  • Arrays: A collection of elements of the same data type stored in contiguous memory locations. For example, an array of integers to store daily temperatures.
  • Strings: A sequence of characters used to represent text, such as names or addresses.

Type Conversion and Casting

Sometimes, you need to convert data from one type to another. This is called type conversion. It can be:

  • Implicit Conversion (Type Coercion): Automatically done by the compiler when it is safe, e.g., converting an int to a float.
  • Explicit Conversion (Type Casting): Done manually by the programmer to convert between types, especially when there is a risk of data loss.
graph TD    A[Start with int value] --> B{Implicit Conversion?}    B -- Yes --> C[Convert int to float automatically]    B -- No --> D{Explicit Casting?}    D -- Yes --> E[Programmer casts float to int]    D -- No --> F[No conversion]

Why is this important? Because converting from a larger data type to a smaller one (like from float to int) can lead to loss of information (decimal part gets truncated). Hence, explicit casting warns the programmer to handle this carefully.

Worked Examples

Example 1: Declaring and Initializing Variables Easy
Declare variables to store a student's age (integer), height in meters (float), and grade (character), and initialize them with appropriate values.

Step 1: Choose data types based on the data:

  • Age is a whole number -> int
  • Height can have decimals -> float
  • Grade is a single letter -> char

Step 2: Declare and initialize variables:

int age = 20;float heightInMeters = 1.75;char grade = 'A';

Answer: Variables declared and initialized successfully.

Example 2: Using Variables with Metric Units Medium
Store the weight of a person in kilograms and the distance they run in meters. Calculate the total distance after running 3 times the stored distance.

Step 1: Choose data types:

  • Weight in kilograms: can be decimal -> float
  • Distance in meters: whole number -> int

Step 2: Declare and initialize variables:

float weightInKg = 65.5;int distanceInMeters = 400;

Step 3: Calculate total distance after running 3 times:

int totalDistance = distanceInMeters * 3;  // 400 * 3 = 1200 meters

Answer: Total distance run is 1200 meters.

Example 3: Currency Calculation Using Variables Medium
Calculate the total price in INR for buying 5 items, each costing Rs.299.75.

Step 1: Choose data types:

  • Price per item: decimal -> float
  • Quantity: whole number -> int
  • Total price: decimal -> float

Step 2: Declare and initialize variables:

float pricePerItem = 299.75;int quantity = 5;

Step 3: Calculate total price:

float totalPrice = pricePerItem * quantity;  // 299.75 * 5 = 1498.75

Answer: Total price is Rs.1498.75.

Example 4: Type Casting Between Integer and Float Medium
Convert a float value 9.87 to an integer explicitly, and convert an integer 7 to float implicitly.

Step 1: Explicit casting from float to int truncates the decimal part:

float floatValue = 9.87;int intValue = (int) floatValue;  // intValue becomes 9

Step 2: Implicit conversion from int to float happens automatically:

int intNumber = 7;float floatNumber = intNumber;  // floatNumber becomes 7.0

Answer: After casting, intValue = 9 and floatNumber = 7.0.

Example 5: Common Errors in Variable Usage Hard
Identify and fix errors in the following code snippet:
int price;float discount = 5.5;price = discount;char 1grade = 'B';

Step 1: price = discount; assigns a float to an int without casting - causes type mismatch.

Fix: Use explicit casting or assign to a float variable.

price = (int) discount;  // Cast float to int, value becomes 5

Step 2: Variable name 1grade starts with a digit - invalid.

Fix: Rename variable to start with a letter or underscore:

char grade1 = 'B';

Answer: Corrected code:

int price;float discount = 5.5;price = (int) discount;char grade1 = 'B';

Constants

Constants are like variables but their values cannot change once set. For example, the value of π (pi) is always approximately 3.14159. In programming, constants are declared using keywords like const or final, depending on the language.

Constants help prevent accidental changes to important fixed values and make programs more reliable.

Scope and Lifetime of Variables

Scope refers to the part of the program where a variable is accessible. Variables can be:

  • Local: Declared inside functions or blocks and accessible only there.
  • Global: Declared outside all functions and accessible throughout the program.

Lifetime is how long the variable exists in memory during program execution. Local variables exist only while the function runs, while global variables exist throughout the program.

Data Type Selection

Choosing the right data type is important for efficient memory use and performance. For example, if you only need to store whole numbers within a small range, use int instead of float. Using larger data types unnecessarily wastes memory.

Key Concept

Variables and Data Types

Variables store data in memory with specific data types that define the kind and size of data. Proper declaration, initialization, and type selection are essential for correct and efficient programming.

Formula Bank

Type Casting
\text{intValue} = (\text{int}) \text{floatValue}
where: floatValue is a floating-point number, intValue is the integer after truncation
Arithmetic Operation with Variables
\text{total} = \text{variable1} \times \text{variable2}
where: variable1, variable2 are numeric variables, total is the result

Tips & Tricks

Tip: Remember that int is for whole numbers and float or double are for decimal numbers.

When to use: When choosing data types for numeric variables.

Tip: Use meaningful variable names that reflect the data they hold, such as priceInINR or heightInMeters.

When to use: While declaring variables to improve code readability.

Tip: Always initialize variables before use to avoid unexpected behavior.

When to use: Before performing operations on variables.

Tip: Use explicit type casting when converting from a larger to a smaller data type to prevent data loss.

When to use: During type conversions in calculations.

Tip: Keep track of variable scope to avoid naming conflicts and unintended value changes.

When to use: When working with local and global variables.

Common Mistakes to Avoid

❌ Using variables without initialization.
✓ Always assign an initial value to variables before using them.
Why: Uninitialized variables may contain garbage values leading to unpredictable results.
❌ Assigning a float value to an int variable without casting.
✓ Use explicit type casting or assign to a float variable.
Why: Implicit conversion may cause data truncation or errors.
❌ Using invalid variable names starting with numbers or special characters.
✓ Follow naming rules: start with a letter or underscore, no spaces or special characters.
Why: Invalid names cause syntax errors.
❌ Confusing data types leading to incorrect operations, e.g., adding a number to a character variable.
✓ Ensure compatible data types are used in operations.
Why: Type incompatibility causes compilation or runtime errors.
❌ Ignoring variable scope, causing unexpected value changes.
✓ Understand and use local and global variables appropriately.
Why: Scope confusion can lead to bugs that are hard to trace.
✨ AI exam tools — try them free (included in every plan)
Tip: select any text above to Explain / Example / Simplify it.
Curated videos per subtopic
Top YouTube explainers, AI-ranked for your exam and language. Unlocks with subscription.
Unlock

Try Practice next.

Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.

Go to practice →
Ask a doubt
Variables and Data Types · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.