Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
instanceof Keyword in Java
Next article icon

Instance Methods in Java

Last Updated : 10 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Instance Methods are the group of codes that performs a particular task. Sometimes the program grows in size, and we want to separate the logic of the main method from other methods. A  method is a function written inside the class. Since java is an object-oriented programming language, we need to write a method inside some classes. 

The important points regarding instance variables are:

  1. Instance methods can access instance variables and instance methods directly and undeviatingly.
  2. Instance methods can access static variables and static methods directly.

Instance Method without parameter 

Syntax:

modifier return_type method_name( )  {          method body ;  }
  • modifier: It defines the access type of the method, and it is optional to use.
  • return_type: Method may return a value. Ex:- int, void, String, char, float, etc.
  • method_name: This is the method name you can write anything as you write the variable name.
  • method body: The method body describes what the method does with statements.

Example:

public void disp( )  {         int a= 10;      System.out.println(a);  }

Calling Instance Method:

You can not call an instance method in the static method directly, so the Instance method can be invoked using an object of the class. We know that the java program's execution starts from the main method and the main method is static, so we can not directly call the instance method. We have to create the class object; then, we can call the instance method in the main method.

Let's see how we can call the Instance method:

Example 1:

Java
// Java program to see how can we call // an instance method without parameter  import java.io.*;  class GFG {       // static method     public static void main (String[] args) {                    // Creating object of the class         GFG obj = new GFG();                            // Calling instance method         obj.disp();                  System.out.println("GFG!");     }              // Instance method     void disp()                                       {           // Local variable         int a = 20;                                       System.out.println(a);     } } 

Output
20  GFG!

Example 2:

Java
// Java program to see how can we call // an instance method without parameter  import java.io.*;  // Different class class class1 {                // Instance method in different class      void add()                     {        int a= 2;       int b= 3;       System.out.println("The sum of 2 and 3 is :" + (a+b));     } } class GFG {       // Static method     public static void main (String[] args) {                          // creating object of the class         class1 obj = new class1();                                 // calling instance method         obj.add();                      System.out.println("GFG!");     } } 

Output
The sum of 2 and 3 is :5  GFG!

Instance Method With Parameter 

Instance method with parameter takes the argument when it is called in the main method. Now let's see Examples for better understanding.

Syntax:

 modifier return_type method_name( parameter list)  {      method body ;  }
  • Parameter List: The list of parameters separated by a comma. These are optional; the method may contain zero parameters.

Example:

public void disp(int a, int b)  {        int x=a ;        int y=b;        int z = x+y;       System.out.println(z);  }
Java
// Java program to see how can we call // an instance method with parameter  import java.io.*;  class GFG {       // static method     public static void main (String[] args) {                   // creating object         GFG obj = new GFG();                              // calling instance method by passing value         obj.add(2,3);                    System.out.println("GFG!");     }      // Instance method with parameter   void add(int a, int b)             {      // local variables     int x= a;                         int y= b;                         int z= x + y;                       System.out.println("Sum : " + z);   } } 

Output
Sum : 5  GFG!

Types of Instance Methods:

There are two types of Instance methods in Java:

  1. Accessor Method   (Getters)
  2. Mutator Method    (Setters)

The accessor method is used to make the code more secure and increase its protection level, accessor is also known as a getter. Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the convenience of the program, getter starts with the word "get" followed by the variable name.

 The mutator method is also known as the setter. It sets the value for any variable which is used in the programs of a class. and starts with the word "set" followed by the variable name. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type. In both getter and setter, the first letter of the variable should be capital.

Accessor and mutator are mainly used to access or set the value for the private member of the class in the main method.

Let's get understand by some examples:

Java
// Java program to demonstrate the // types of instance methods  import java.io.*;  class account {          // private variable-balance     private int balance = 50;               // accessor method (getter)     public int getBalance()     {          return balance;     }            // Mutator method (setter)       public void setBalance(int a)     {            // return balance + a;         balance += a;     } } class GFG {     public static void main(String[] args)     {         account obj = new account();                  // setting new value for balance         obj.setBalance(50);                   // calling the Mutator (accessor)         System.out.println("Your Balance : "+ obj.getBalance());                                            System.out.println("GFG!");     } } 

Output
Your Balance : 100  GFG!

Next Article
instanceof Keyword in Java
author
sachinyadavshiv8
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • instanceof Keyword in Java
    In Java, instanceof is a keyword used for checking if a reference variable contains a given type of object reference or not. Following is a Java program to show different behaviors of instanceof. Henceforth it is known as a comparison operator where the instance is getting compared to type returning
    4 min read
  • Static Method vs Instance Method in Java
    In Java, methods are mainly divided into two parts based on how they are associated with a class, which are the static method and the Instance method. The main difference between static and instance methods is: Static method: This method belongs to the class and can be called without creating an obj
    4 min read
  • Integer intValue() Method in Java
    intValue() of Integer class that is present inside java.lang package is an inbuilt method in java that returns the value of this integer as an int which is inherited from Number Class. The package view is as follows: --> java.lang Package --> Integer Class --> intValue() Method Syntax: publ
    3 min read
  • Inheritance in Java
    Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
    14 min read
  • Using Instance Blocks in Java
    The instance block can be defined as the name-less method in java inside which we can define logic and they possess certain characteristics as follows. They can be declared inside classes but not inside any method. Instance block logic is common for all the objects. Instance block will be executed o
    3 min read
  • Java Methods
    Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects. Example: Java program to demonstrate how to cre
    8 min read
  • Class isInstance() method in Java with Examples
    The isInstance() method of java.lang.Class class is used to check if the specified object is compatible to be assigned to the instance of this Class. The method returns true if the specified object is non-null and can be cast to the instance of this Class. It returns false otherwise. Syntax: public
    2 min read
  • Private and Final Methods in Java
    Methods in Java play an important role in making the code more readable, support code reusability, and defining the behaviour of the objects. And we can also restrict the methods based on requirements using the keywords and modifiers such as final and private. These two have different, distinct purp
    5 min read
  • Java Unnamed Classes and Instance Main Methods
    Java has introduced a significant language enhancement in Java Enhancement Proposal (JEP) 445, titled "Unnamed Classes and Instance Main Methods". This proposal aims to address the needs of beginners, making Java more accessible and less intimidating. Let's delve into the specifics of this proposal
    7 min read
  • Instant now() Method in Java with Examples
    In Instant class, there are two types of now() method depending upon the parameters passed to it. now() now() method of a Instant class used to obtain the current instant from the system UTC clock.This method will return instant based on system UTC clock. Syntax: public static Instant now() Paramete
    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