Lesson 1

Variables/data types and expressions

<p>Learn about Variables/data types and expressions in this comprehensive lesson.</p>

AI Explain — Ask anything

Why This Matters

Imagine you're building with LEGOs. You need a way to store different kinds of bricks – maybe a box for red bricks, another for blue, and a special container for wheels. In computer programming, **variables** are like those storage containers, holding different pieces of information. **Data types** tell the computer what kind of information is inside each container, like saying 'this box holds numbers' or 'this box holds words'. When you combine these pieces of information, like adding two numbers together or putting words side-by-side, you're creating an **expression**. It's like following a recipe to bake a cake – you combine ingredients (data) using instructions (operators) to get a result. Understanding these basics is super important because almost every computer program, from your favorite game to the apps on your phone, uses variables, data types, and expressions to work its magic. Learning this now will make everything else in computer science much easier, just like knowing your ABCs helps you read and write stories. It's the foundation for telling the computer exactly what you want it to do with information.

Key Words to Know

01
Variable — A named storage location in a computer's memory that holds a piece of data.
02
Data Type — A classification that specifies what kind of value a variable can hold (e.g., whole number, decimal number, text).
03
Expression — A combination of values, variables, and operators that the computer evaluates to produce a single result.
04
Integer (`int`) — A data type used to store whole numbers (positive, negative, or zero) without any decimal points.
05
Double (`double`) — A data type used to store numbers that can have decimal points, allowing for more precise values.
06
Boolean (`boolean`) — A data type that can only hold one of two values: `true` or `false`.
07
String (`String`) — A data type used to store sequences of characters, such as words, sentences, or names.
08
Assignment Operator (`=`) — Used to assign a value to a variable, placing the value on the right into the variable on the left.
09
Arithmetic Operators — Symbols like `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), and `%` (modulo) used in expressions to perform calculations.
10
Declaration — The process of creating a variable by giving it a name and specifying its data type.

What Is This? (The Simple Version)

Think of your brain as a super-fast computer. When you remember your friend's name, your age, or the color of your bike, your brain is storing those pieces of information. In computer science, we need computers to do the same thing!

  • Variables: Imagine a variable as a labeled box or a cubbyhole in a classroom. You can put something inside it, like your favorite toy or a specific book. The label on the box tells you what's inside or what it's for. In programming, we give these 'boxes' names (like score or userName) and they hold pieces of data.
  • Data Types: Now, what kind of stuff can you put in those boxes? You wouldn't put a pet fish in a box meant for LEGOs, right? Data types tell the computer what kind of information a variable can hold. Is it a whole number (like 10 or 500)? Is it text (like 'Hello' or 'Bob')? Is it a number with a decimal (like 3.14)? Knowing the data type helps the computer understand how to use and store that information correctly.
  • Expressions: An expression is like a math problem or a phrase that the computer figures out to get a single answer. It's a combination of variables, values (like the number 5), and operators (like + for addition or - for subtraction). For example, score + 10 is an expression. The computer looks at the current score, adds 10 to it, and then gets a new single value as the result.

Real-World Example

Let's imagine you're playing a video game where you collect coins. Your game needs to keep track of a few things:

  1. Your Score: This is a whole number, like 0, 100, 250. We'd use a variable named playerScore for this, and its data type would be an integer (a whole number).
  2. Your Player Name: This is text, like 'NinjaMaster' or 'SuperGamer'. We'd use a variable named playerName, and its data type would be a string (a sequence of characters/text).
  3. Time Remaining: This might be a number with decimals, like 59.5 seconds. We'd use a variable named timeRemaining, and its data type would be a double (a number with a decimal point).

Now, let's say you just collected 50 coins. The game needs to update your score. It would do something like this:

  • It takes the current value in the playerScore variable (let's say it was 100).
  • It uses an expression: playerScore + 50. This means 'take what's in playerScore and add 50 to it'.
  • The computer calculates 100 + 50, which equals 150.
  • Finally, it puts this new value, 150, back into the playerScore variable, replacing the old 100. So now playerScore holds 150.

See how variables hold different types of data, and expressions help us change or combine that data?

How It Works (Step by Step)

Let's break down how a computer handles a simple instruction like int age = 12 + 1;

  1. Declare the Variable: The computer sees int age. This tells it, "Okay, I need to create a new storage box. Its label will be age, and it's going to hold an integer (a whole number)."
  2. Evaluate the Expression: Next, it looks at 12 + 1. This is an expression. The computer calculates the result of 12 + 1, which is 13.
  3. Assign the Value: The = sign means "put the result of the right side into the variable on the left side." So, the computer takes the calculated 13 and places it inside the age storage box.
  4. Variable Holds Value: Now, the variable age officially holds the value 13. If you ask the computer for age, it will tell you 13.

Common Data Types (The Main Ones)

Just like you have different containers for different kinds of food (a jar for jam, a bag for bread), computers have different data types for different kinds of information. Here are the most common ones you'll see in AP Computer Science A:

  • int (Integer): This is for whole numbers – numbers without any decimal points. Think of counting apples: 1, 5, 100, -3. You can't have half an apple with an int.
    • Analogy: Like the number of siblings you have (you can't have 2.5 siblings!).
  • double (Double-precision floating-point number): This is for numbers with decimal points. Think of measuring things precisely: 3.14, 98.6, 0.5. These are called 'floating-point' because the decimal point can 'float' to different positions.
    • Analogy: Like your height in meters (1.52 meters) or the price of an item ($19.99).
  • boolean (Boolean): This is for values that can only be one of two things: true or false. It's like an on/off switch or a yes/no question.
    • Analogy: Is the light on? (True/False). Did you finish your homework? (True/False).
  • String (String of characters): This is for text – words, sentences, names, or any combination of characters. In Java, String starts with a capital 'S' because it's a special kind of data type called an object (we'll learn more about objects later!).
    • Analogy: Your name, a tweet, or the title of a book.

Common Mistakes (And How to Avoid Them)

Even experienced programmers make these sometimes! Here's how to steer clear:

  • Mistake 1: Mismatched Data Types (Putting a square peg in a round hole)

    • Why it happens: Trying to put a double (number with decimal) into an int (whole number) variable, or vice-versa, without thinking. The computer might get confused or lose information.
    • How to avoid it: Always make sure the type of data you're trying to store matches the variable's declared data type. If you have double price = 10.99; you can't just say int wholePrice = price; without telling the computer you're okay with losing the .99 part. You'd have to cast it (force it to change type) like int wholePrice = (int) price;.
    • int age = 12.5; (Computer will complain!)
    • double age = 12.5; or int age = 12;
  • Mistake 2: Forgetting to Initialize (Leaving the box empty)

    • Why it happens: You declare a variable (int score;) but then try to use it in an expression (score + 10;) before you've given it an initial value. The computer doesn't know what score is yet!
    • How to avoid it: Always give your variables a starting value when you declare them, or at least before you try to use them in a calculation or print them out.
    • int num; System.out.println(num); (Error! num hasn't been given a value.)
    • int num = 0; System.out.println(num); (Now num has a starting value.)
  • Mistake 3: Confusing = with == (Assignment vs. Comparison)

    • Why it happens: In math, = means 'equals'. In programming, = means assignment (put the value on the right into the variable on the left). To check if two things are equal, we use == (two equal signs).
    • How to avoid it: Remember: single = is for giving a variable a value. Double == is for asking a question: "Are these two things the same?" (which will give you a true or false answer).
    • if (score = 100) (This tries to set score to 100, not check if it IS 100.)
    • if (score == 100) (This correctly checks if score is equal to 100.)

Exam Tips

  • 1.Always declare a variable's data type before using it (e.g., `int x;` not just `x;`).
  • 2.Initialize variables with a starting value to avoid errors, especially if you use them in calculations right away (e.g., `int count = 0;`).
  • 3.Pay close attention to data type compatibility; a `double` can hold an `int`'s value, but an `int` cannot directly hold a `double`'s value without potential data loss (and a specific 'cast').
  • 4.Understand the difference between the assignment operator (`=`) and the equality operator (`==`); this is a very common source of errors on the exam.
  • 5.Practice evaluating complex expressions step-by-step, following the order of operations (PEMDAS/BODMAS), just like in math class.