Java Instance Variables Fields

Class Notes for High School Computer Science

1. What Are Instance Variables?

In Java, instance variables are variables that belong to an object.

They are also called fields because they describe the data or characteristics stored inside a class.

private String name;
private int score;
private double balance;

These variables store information that each object needs to remember.

Key Idea: Instance variables store the data inside an object.

2. Why Are They Called Instance Variables?

An instance means an object created from a class.

Student s1 = new Student();
Student s2 = new Student();

Here, s1 and s2 are two different instances of the Student class.

Each object gets its own copy of the instance variables.

3. Example Class With Instance Variables

public class Student
{
    private String name;
    private int gradeLevel;
    private double gpa;
}
Instance Variable Data Type What It Stores
name String The student's name
gradeLevel int The student's grade level
gpa double The student's GPA

4. Where Are Instance Variables Declared?

Instance variables are declared inside the class, but outside all methods and constructors.

public class Dog
{
    private String name;
    private int age;

    public Dog(String dogName, int dogAge)
    {
        name = dogName;
        age = dogAge;
    }
}

The variables name and age are instance variables. They are declared at the top level of the class.

5. Instance Variables vs. Local Variables

Feature Instance Variable Local Variable
Where declared? Inside class, outside methods Inside a method or constructor
Belongs to? Object Method or block
How long does it last? As long as the object exists Only while the method or block runs
Default value? Yes No
Usually private? Yes Not usually
public class GamePlayer
{
    private String username;   // instance variable
    private int score;         // instance variable

    public void addPoints(int points)
    {
        int bonus = 5;         // local variable
        score = score + points + bonus;
    }
}

username and score belong to the object. points and bonus only exist inside the method.

6. Default Values

Instance variables automatically receive default values if they are not assigned.

Data Type Default Value
int 0
double 0.0
boolean false
char '\u0000'
Object references like String null
public class Player
{
    private int score;
    private boolean active;
    private String name;
}

If no constructor assigns values:

score   // 0
active  // false
name    // null

7. Why Are Instance Variables Usually Private?

Instance variables are usually marked private.

private int score;

This protects the data from being changed directly by outside classes. This idea is called encapsulation.

public int getScore()
{
    return score;
}

public void addPoints(int points)
{
    if (points > 0)
    {
        score += points;
    }
}
Good Programming Practice: Make fields private and use methods to access or change them.

8. Constructors Set Up Instance Variables

A constructor often gives starting values to instance variables.

public class BankAccount
{
    private String owner;
    private double balance;

    public BankAccount(String accountOwner, double startingBalance)
    {
        owner = accountOwner;
        balance = startingBalance;
    }
}

When an object is created:

BankAccount acct = new BankAccount("Maria", 100.00);

The object stores:

owner = "Maria"
balance = 100.00

9. Methods Use Instance Variables

Methods inside the class can read and modify instance variables.

public class Counter
{
    private int count;

    public Counter()
    {
        count = 0;
    }

    public void increase()
    {
        count++;
    }

    public int getCount()
    {
        return count;
    }
}

Example use:

Counter c = new Counter();

c.increase();
c.increase();

System.out.println(c.getCount());

Output:

2

The object remembers the value of count.

10. Each Object Has Its Own Values

public class Player
{
    private String name;
    private int score;

    public Player(String playerName)
    {
        name = playerName;
        score = 0;
    }

    public void addPoints(int points)
    {
        score += points;
    }

    public String getName()
    {
        return name;
    }

    public int getScore()
    {
        return score;
    }
}

Example:

Player p1 = new Player("Alex");
Player p2 = new Player("Jordan");

p1.addPoints(10);
p2.addPoints(25);

System.out.println(p1.getName() + ": " + p1.getScore());
System.out.println(p2.getName() + ": " + p2.getScore());

Output:

Alex: 10
Jordan: 25

Even though both objects come from the same class, each object has its own name and score.

11. Using this With Instance Variables

Sometimes a parameter has the same name as an instance variable.

public class Student
{
    private String name;

    public Student(String name)
    {
        this.name = name;
    }
}

this.name means the instance variable. name by itself means the parameter.

public class Rectangle
{
    private int width;
    private int height;

    public Rectangle(int width, int height)
    {
        this.width = width;
        this.height = height;
    }
}
Remember: this refers to the current object.

12. Complete Example

public class Book
{
    private String title;
    private String author;
    private int pages;

    public Book(String bookTitle, String bookAuthor, int numberOfPages)
    {
        title = bookTitle;
        author = bookAuthor;
        pages = numberOfPages;
    }

    public String getTitle()
    {
        return title;
    }

    public String getAuthor()
    {
        return author;
    }

    public int getPages()
    {
        return pages;
    }

    public void addPages(int extraPages)
    {
        if (extraPages > 0)
        {
            pages += extraPages;
        }
    }
}

Example use:

Book b = new Book("The Hobbit", "J.R.R. Tolkien", 310);

System.out.println(b.getTitle());
System.out.println(b.getAuthor());
System.out.println(b.getPages());

b.addPages(5);

System.out.println(b.getPages());

Output:

The Hobbit
J.R.R. Tolkien
310
315

13. Common Student Mistakes

Mistake 1: Declaring the Variable Inside the Constructor Only

Incorrect:

public class Student
{
    public Student(String studentName)
    {
        String name = studentName;
    }
}
Problem: name is a local variable. It disappears after the constructor finishes.

Correct:

public class Student
{
    private String name;

    public Student(String studentName)
    {
        name = studentName;
    }
}

Mistake 2: Forgetting private

Not recommended:

public int score;

Better:

private int score;

Mistake 3: Confusing Class Name and Object Name

Student s1 = new Student("Ava");
Student s2 = new Student("Noah");

Student is the class. s1 and s2 are objects.

Mistake 4: Forgetting That Instance Variables Keep Their Values

public void addOne()
{
    count++;
}

If count is an instance variable, it remembers its value after the method ends.

14. AP Computer Science A Connection

On the AP Computer Science A exam, instance variables are important because they appear in many classes and FRQs.

You may be asked to:

public class ScoreCard
{
    private String playerName;
    private int score;

    public ScoreCard(String name)
    {
        playerName = name;
        score = 0;
    }

    public void addScore(int points)
    {
        if (points > 0)
        {
            score += points;
        }
    }

    public int getScore()
    {
        return score;
    }
}

15. Key Vocabulary

Term Meaning
Class A blueprint for creating objects
Object An instance of a class
Instance Variable A variable that belongs to an object
Field Another name for an instance variable
Constructor A special method used to create and initialize an object
Encapsulation Protecting data by making fields private
Getter A method that returns the value of a field
Setter A method that changes the value of a field
this Refers to the current object

16. Quick Check Questions

  1. Where are instance variables declared?
    Inside the class, but outside all methods and constructors.
  2. What keyword is usually used to protect instance variables?
    private
  3. What is another name for an instance variable?
    Field
  4. Does each object get its own copy of instance variables?
    Yes
  5. What does a constructor usually do with instance variables?
    It gives them starting values.
  6. What does this.name refer to?
    The instance variable named name in the current object.

17. Practice Exercise

Create a class called VideoGamePlayer.

Your class should have these instance variables:

private String username;
private int level;
private int health;

Your class should include this constructor:

public VideoGamePlayer(String name)

This constructor should set:

username = name;
level = 1;
health = 100;

Add these methods:

public void levelUp()
public void takeDamage(int amount)
public String getUsername()
public int getLevel()
public int getHealth()
Goal: Practice creating fields, initializing them in a constructor, and using methods to change them.

18. Big Idea Summary

Instance variables are the data stored inside an object.

They allow an object to remember information between method calls.

A good Java class usually has:

private instance variables
a constructor
methods that use or change the variables
getter methods when outside classes need information
Final Thought: Instance variables are one of the most important building blocks of object-oriented programming in Java.