Chapter 2: Java Storing and Manipulating Data
By Ali Naqi ⢠December 19, 2025
š¦ Chapter 2: Java Storing and Manipulating Data
1. What is a Variable? (The "Box" Analogy)
In the simplest terms, a variable is a container for storing data. Imagine you are moving to a new house. You have several boxes. One box is labeled "Books," another is labeled "Kitchenware," and a third is labeled "Clothes."
In Java, a variable works the same way:
- Label (Name): You give the variable a name so you can refer to it later.
- Type (Category): You decide what kind of stuff can go inside the box (you wouldn't put soup in a cardboard box!).
- Value (Content): You put the actual data inside.
Java is a strongly typed language. This means once you decide a "box" is for integers (whole numbers), you cannot suddenly try to stuff a sentence or a decimal number into it. This strictness is actually your best friend; it helps the compiler catch errors before you ever run your program.
Variable Declaration and Initialization
To use a variable, you must do two things: declare it and initialize it.
- Declaration: Telling Java the name and the type.
- int age;
- Initialization: Putting a value into it for the first time.
- age = 25;
You can also do both on one line:
int age = 25;
2. Java Data Types: The Primitive Eight
Java has two categories of data types: Primitives and References. For now, we will focus on the Primitive Types. These are the most basic, built-in types that represent simple values.
Think of primitives as the "atoms" of Java. There are exactly eight of them.
The Whole Numbers (Integers)
- byte: The smallest. It uses only 8 bits of memory and can store values from -128 to 127. Use this if you are extremely short on memory (rare in modern apps).
- short: 16 bits. Ranges from -32,768 to 32,767.
- int: The "gold standard." It's 32 bits and ranges from about -2.1 billion to 2.1 billion. This is the one you will use 99% of the time for whole numbers.
- long: 64 bits. Used for massive numbers (like the distance to stars or world population).
- Note: When writing a long, you usually add an 'L' at the end: long debt = 3000000000L;
- Note: When writing a long, you usually add an 'L' at the end: long debt = 3000000000L;
The Fractional Numbers (Floating Point)
- float: 32 bits. Good for decimals but less precise. You must add an 'f' at the end: float pi = 3.14f;
- double: 64 bits. Much more precise. This is the standard for decimal numbers in Java.
The Logic and Text Basics
- boolean: The simplest of all. It can only hold two values: true or false. This is the foundation of all computer logic.
- char: Stores a single character (letter, digit, or symbol). It uses single quotes: char grade = 'A';.
Wait, where are Strings? You might be looking for "String" (like "Hello World"). In Java, a String is NOT a primitive. It is a Reference Type (a complex object), which we will cover in the next chapter. However, you can use it just as easily: String name = "John";.
3. Naming Your Variables: The Rules of the Road
In Java, we use a naming convention called lowerCamelCase.
- Always start with a lowercase letter.
- If the name has multiple words, capitalize the first letter of each subsequent word.
- Good: userAge, accountBalance, isGameOver.
- Bad: user_age, Accountbalance, 123name.
Rules:
- Names are case-sensitive (age is different from Age).
- Names cannot start with a number.
- Names cannot be "Reserved Keywords" (you can't name a variable public or class).
4. Operators: Making Your Variables Do Work
Data is boring if you canāt change it. Operators are the symbols that perform operations on your variables.
A. Arithmetic Operators
These are your basic math tools:
- + (Addition): 10 + 5 = 15
- - (Subtraction): 10 - 5 = 5
- * (Multiplication): 10 * 5 = 50
- / (Division): 10 / 3 = 3 (Note: In integer division, Java drops the decimal!)
- % (Modulus): 10 % 3 = 1. This gives you the remainder. Itās incredibly useful for checking if a number is even or odd (number % 2 == 0).
B. Relational (Comparison) Operators
These always return a boolean (true or false).
- == (Equal to): 5 == 5 is true.
- != (Not equal to): 5 != 3 is true.
- > and < (Greater than / Less than).
- >= and <= (Greater/Less than or equal to).
C. Logical Operators
Used to combine multiple conditions.
- && (AND): Returns true if both sides are true.
- || (OR): Returns true if at least one side is true.
- ! (NOT): Reverses the value. !true becomes false.
D. Increment and Decrement
- ++: Adds 1 to the variable.
- --: Subtracts 1 from the variable.
- int score = 0; score++; // score is now 1
5. Type Casting: Changing Shapes
Sometimes you need to convert a value from one type to another.
Widening (Implicit) Casting
This happens automatically when you move from a smaller type to a larger type. Itās like pouring water from a small cup into a large bucketānothing is spilled.
Java
int myInt = 9; double myDouble = myInt; // Automatic casting: 9.0
Narrowing (Explicit) Casting
This must be done manually because you might lose data. Itās like pouring a large bucket of water into a small cupāsome will overflow!
Java
double myDouble = 9.78; int myInt = (int) myDouble; // Manual casting: myInt becomes 9 (the .78 is chopped off!)
6. Putting it All Together: A Practical Example
Letās write a small program that calculates the area of a circle. This uses variables, constants, and math operators.
Java
public class CircleCalculator {
public static void main(String[] args) {
// Variable declaration and initialization
double radius = 5.5;
final double PI = 3.14159; // 'final' means the value cannot be changed later (a constant)
// Using an operator to calculate area (PI * r^2)
double area = PI * radius * radius;
// Using a comparison operator
boolean isLargeCircle = area > 50;
// Outputting results
System.out.println("The radius is: " + radius);
System.out.println("The area is: " + area);
System.out.println("Is it a large circle? " + isLargeCircle);
}
}
Pro-Tips for Clean Code
- Use Meaningful Names: Don't name a variable a if it represents accountBalance. Clear names make comments almost unnecessary.
- Initialize Variables: Java doesn't like it when you try to use a "box" before you've put anything in it. Always give your variables an initial value.
- Be Mindful of Precision: Never use float or double for money! Because of how computers handle binary math, these can have tiny rounding errors. For money, professional Java developers use a class called BigDecimal.
š Chapter Summary
In this chapter, we covered:
- Variables as named containers for data.
- The 8 Primitive Data Types: byte, short, int, long, float, double, boolean, char.
- Naming Conventions using lowerCamelCase.
- Operators for math, comparison, and logic.
- Type Casting to convert between data types.
You now know how to store data and manipulate it. But a program that just runs from top to bottom is very limited. Real programs need to make decisions and repeat tasks.