Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.

For example, for a member variable:

Integer x;

You might have methods:

Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }

chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.

Answer from Justin Ethier on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_set.asp
Java Set
close() delimiter() findInLine() ... ... The Set interface is part of the Java Collections Framework and is used to store a collection of unique elements....
Top answer
1 of 16
58

Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.

For example, for a member variable:

Integer x;

You might have methods:

Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }

chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.

2 of 16
22

I want to add to other answers that setters can be used to prevent putting the object in an invalid state.

For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:

private String taxId;

public void setTaxId(String taxId) {
    this.taxId = taxId;
}

However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:

private String taxId;

public void setTaxId(String taxId) throws IllegalArgumentException {
    if (isTaxIdValid(taxId)) {
        throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
    }
    this.taxId = taxId;
}

The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.

private final TaxId taxId = new TaxId()

public void setTaxId(String taxIdString) throws IllegalArgumentException {
    taxId.set(taxIdString); //will throw exception if not valid
}

Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:

public String getTaxId() throws IllegalStateException {
    return taxId.get(); //will throw exception if not set
}
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ set-in-java
Set in Java - GeeksforGeeks
The HashSet stores "B", "C", and "A". When "B" is added a second time, it is ignored because a Set does not allow duplicate elements. After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(). ... import java.util.*; class Geeks { public static void main(String[] args) { Set<String> h = new HashSet<String>(); h.add("A"); h.add("B"); h.add("C"); h.add("A"); System.out.println("Set is " + h); String s = "D"; System.out.println("Contains " + s + " " + h.contains(s)); } }
Published: 2 weeks ago
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ Set.html
Set (Java Platform SE 8 )
3 weeks ago - Method ยท compact1, compact2, compact3 ยท java.util ยท Type Parameters: E - the type of elements maintained by this set ยท
๐ŸŒ
Oracle
docs.oracle.com โ€บ en โ€บ java โ€บ javase โ€บ 11 โ€บ docs โ€บ api โ€บ java.base โ€บ java โ€บ util โ€บ Set.html
Set (Java SE 11 & JDK 11 )
January 20, 2026 - Returns an array containing all of the elements in this set. If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
๐ŸŒ
Simplilearn
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ set in java: the methods and operations you can perform
Set in Java: The Methods and Operations You Can Perform
August 3, 2026 - The set in Java is an interface available in the java.util package. In this article, you will learn everything about set, its operations, methods and more.
Address: 5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java collections โ€บ set operations in java
Set Operations in Java | Baeldung
May 5, 2026 - Since a Set doesnโ€™t provide an index-based get(i) method, we have to use different strategies. Itโ€™s important to remember that these strategies work best with ordered implementations, such as LinkedHashSet or TreeSet, to ensure the resulting subset contains a predictable sequence of elements. The most modern and readable way to create a subset in native Java is using the Stream API.
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ watch
Set and Get Methods in Java - YouTube
In this video we focus on writing set and get methods(also known as accessor and mutator methods) in Java. These methods are often used in OOP. Please know I...
Published: July 27, 2022
๐ŸŒ
Software Testing Help
softwaretestinghelp.com โ€บ home โ€บ java โ€บ set interface in java: java set tutorial with examples
Set Interface In Java: Java Set Tutorial With Examples
May 14, 2025 - The set interface allows for unique values. It can have at most one null value. Java 8 provides a default method for the set interface โ€“ Spliterator.
๐ŸŒ
Scientech Easy
scientecheasy.com โ€บ home โ€บ blog โ€บ set in java
Set in Java - Scientech Easy
May 12, 2025 - A set interface in Java has provided various useful methods such as add, remove, clear, size, etc. to enhance the usage of a set interface in the collections framework.
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ set
Java Set Interface
The Java Set interface allows us to perform basic mathematical set operations like union, intersection, and subset.
๐ŸŒ
Redisson
redisson.pro โ€บ glossary โ€บ java-set.html
What is a Java set? | Redisson
In Java, sets are implemented by the java.util.Set interface. The most important methods of Java sets include:
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-set
Java Set โ€“ Set in Java | DigitalOcean
Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ java collections โ€บ java set
Java Set
February 13, 2025 - Java Streams provide a powerful way to work with collections, including Sets, using concise and expressive operations. With Streams, you can: ... Now, let's see how to convert a Set into a Stream and unleash its full potential. Converting a Set to a Stream is super easy! Just call the stream() method on a Set instance.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 9 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ Set.html
Set (Java SE 9 & JDK 9 )
This method acts as bridge between array-based and collection-based APIs. ... Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array. If the set fits in the specified array, it is returned therein.
Top answer
1 of 5
2

First, this site is to be used more for questions that can be concretely answered; not so much for theoretical questions.

Anyways, the first part with the 'get' and 'set' you understand fine. Now when you said that you do not need to explicitly set the employee number because you do 'new Employee ...' is not quite true. That would work if you had explicitly defined a constructor that takes an integer for an argument and then sets 'empNum' equal to the argued integer value.

Getters and setters are usually used in conjunction with the 'private' modifier. Setters can be used to control the input. For example, you can check if the provided value is greater than zero, where as you cannot if you give direct access. Getters just allow values to be retrieved, but to make changes you force the use of the corresponding setter (if any).

You are right about how if a value is not supplied you should set one by default. Consider that the value that you retrieve (if any) is to be used in a different class. What if the user never set a value? What if it's not something you expected? The different class, whatever it may be, still requires a value and you still need to pass something. By setting a default value, the different class can recognize that, "oh, this is a default value - this means that the user probably did not supply the correct input." By doing so, you create a relatively fail-safe application; you can keep on working even if the input is not what it is expected to be.

2 of 5
2

The point of using public accessors for private variables is to control how those variables are accessed and to insure that all of the internal state is kept consistent. For example, a class might have both an age and a birthdate variable. Setting the birthdate also implicitly sets the age. If direct access was given to these variables, then it would be possible to set them to inconsistent values (i.e. birthday says they are 30, but age set to 35). By using setters, we can insure that setting the birthdate will reset the age to be correct.

In this example, using setters would also allow us to convert the age variable into a generated property. Since age can be directly determined using the birthdate, you can create a getter for age and have it directly calculate and return the age without needing to store it anywhere.

If we use getters and setters to expose these object properties, we are free to switch out the implementations (such as removing the age variable and calculating it on the fly) without the users of our object needing to worry about it.

๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_arraylist_set.asp
Java ArrayList set() Method
The set() method replaces an item at a specified position in the list and returns the item that was previously at that position.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ java_set_interface.htm
Java - Set Interface
Following is an example to explain Set functionality using HashSet โˆ’ ยท import java.util.HashSet; import java.util.Set; public class SetDemo { public static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new HashSet<>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set); } catch(Exception e) {} } }
Top answer
1 of 8
7

Some benefits of using getters and setters (known as encapsulation or data-hiding):

1. The fields of a class can be made read-only (by only providing the getter) or write-only (by only providing the setter). This gives the class a total control of who gets to access/modify its fields.

Example:

class EncapsulationExample {
    private int readOnly = -1;  // this value can only be read, not altered
    private int writeOnly = 0;    // this value can only be changed, not viewed
    public int getReadOnly() {
        return readOnly;
    }
    public int setWriteOnly(int w) {
        writeOnly = w;
    }
}

2. The users of a class do not need to know how the class actually stores the data. This means data is separated and exists independently from the users thus allowing the code to be more easily modified and maintained. This allows the maintainers to make frequent changes like bug fixes, design and performance enhancements, all while not impacting users.

Furthermore, encapsulated resources are uniformly accessible to each user and have identical behavior independent of the user since this behavior is internally defined in the class.

Example (getting a value):

class EncapsulationExample {
    private int value;
    public int getValue() {     
        return value; // return the value
    }
}

Now what if I wanted to return twice the value instead? I can just alter my getter and all the code that is using my example doesn't need to change and will get twice the value:

class EncapsulationExample {
    private int value;
    public int getValue() {
        return value*2; // return twice the value
    }
}

3. Makes the code cleaner, more readable and easier to comprehend.

Here is an example:

No encapsulation:

class Box {
    int widthS; // width of the side
    int widthT; // width of the top
    // other stuff
}

// ...
Box b = new Box();
int w1 = b.widthS;  // Hm... what is widthS again? 
int w2 = b.widthT;  // Don't mistake the names. I should make sure I use the proper variable here!

With encapsulation:

class Box {
    private int widthS; // width of the side
    private int widthT; // width of the top
    public int getSideWidth() {
        return widthS;
    }
    public int getTopWIdth() {
        return widthT;
    }
    // other stuff
}

// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!

Look how much more control you have on which information you are getting and how much clearer this is in the second example. Mind you, this example is trivial and in real-life the classes you would be dealing with a lot of resources being accessed by many different components. Thus, encapsulating the resources makes it clearer which ones we are accessing and in what way (getting or setting).

Here is good SO thread on this topic.

Here is good read on data encapsulation.

2 of 8
1

As the above comment states, getters and setters encapsulate (i.e. hide) inner details of your class. Thus other classes that interact with yours, do not need to know about the implementation details.

For example, in the simple case you describe, instance variables are exposed via getters and setters. But what if you wanted to change your class so that you no longer used instance variables, but rather you persisted the values to disk. You could make this change to your class without affecting the users of your class.

Keep in mind also that getters and setters need not always be provided. If you do not want your class to provide a way to set or read these properties, then don't. Simply make them private.