Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Getter and Setter in Java
Next article icon

Getter and Setter in Java

Last Updated : 22 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, Getter and Setter are methods used to protect your data and make your code more secure. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type.

Getter in Java: Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program's convenience, the getter starts with the word "get" followed by the variable name.

Setter in Java: While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs. and starts with the word "set" followed by the variable name. 

Syntax

class ABC{     private variable;          public void setVariable(int x){         this.variable=x;     }          public int getVariable{         return variable;     } }

Note: In both getter and setter, the first letter of the variable should be capital.

Examples of Getter and Setter in Java

Example 1:

Java
// Java Program to Illustrate Getter and Setter  // Importing input output classes import java.io.*;  // Class 1 // Helper class class GetSet {      // Member variable of this class     private String name;      // Method 1 - Getter     public String getName() { return name; }      // Method 2 - Setter     public void setName(String N)     {          // This keyword refers to current instance itself         this.name = N;     } }  // Class 2 // Main class class GFG {      // Main driver method     public static void main(String[] args)     {         // Creating an object of class 1 in main() method         GetSet obj = new GetSet();          // Setting the name by calling setter method         obj.setName("Geeks for Geeks");         // Getting the name by calling getter method         System.out.println(obj.getName());     } } 

Output
Geeks for Geeks 

Getter and Setter give you the convenience of entering the value of the variables of any data type by the requirement of the code. Getters and setters let you manage how crucial variables in your code are accessed and altered. It can be seen in the program discussed below as follows:

Example 2

Java
// Java Program to Illustrate Getter and Setter  // Importing input output classes import java.io.*;  class GetSet {     // Member variable of this class     private int num;      // Method 1 - Setter     public void setNumber(int number)     {         // Checking if number is between 1 to 10 exclusive         if (number < 1 || number > 10) {              throw new IllegalArgumentException();         }         num = number;     }      // Method 2 - Getter     public int getNumber() { return num; } }  // Class 2 // Main class class GFG {     // Main driver method     public static void main(String[] args)     {         GetSet obj = new GetSet();          // Calling method 1 inside main() method         obj.setNumber(5);          // Printing the number as setter above         System.out.println(obj.getNumber());     } } 

Output
5 

Explanation of the above program:

Here we can see that if we take a value greater than 10 then it shows an error, By using the setNumber() method, one can be sure the value of a number is always between 1 and 10. This is much better than updating the number variable directly.

Note: This could be avoided by making the number a private variable and utilizing the setNumber method. Using a getter method, on the other hand, is the sole way to read a number's value.


Next Article
Getter and Setter in Java

S

sachinyadavshiv8
Improve
Article Tags :
  • Java
  • Java Programs
Practice Tags :
  • Java

Similar Reads

    Mutable and Immutable Objects in Java
    Java is a popular object-oriented programming (OOP) language and it's code design revolves around it's objects and their manipulation. One of the key concepts in this OOP paradigm is the classification of objects into mutable and immutable types. These classifications say whether an object's state c
    5 min read
    How to Create a HashSet With a Predefined Capacity in Java?
    In Java, we can create HashSet with a predefined capacity by creating a constructor and passing the capacity as a parameter to it. We have to initialize the capacity using a variable otherwise you can pass a direct value to it. Syntax:HashSet <datatype>myset=new HashSet<>(capacity);Here,
    1 min read
    Java Program to Create an Object for Class and Assign Value in the Object Using Constructor
    Java is one of the most popular programming languages. It is an object-oriented programming language which means that we can create classes, objects, and many more. It also supports inheritance, polymorphism, encapsulation, and many more. It is used in all applications starting from mobile applicati
    3 min read
    Set in Java
    The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of duplicat
    14 min read
    Set add() method in Java with Examples
    The add() method of Set in Java is used to add a specific element into a Set collection. The set add() function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set. Declaration of add() methodbo
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences