Instance variable in java program

In this blog, we will discuss on instance variable. Variable has many types like final, static, const and instance. This all are declare in class body. So we can say properties of class.

Here we will see how to access instance variable from main class.


Let’s see example on instance variable.

import java.util.*;

class B                         // Class


int x,y;  // instance variable [ class variable ]


class clEx2


public static void main(String args[])


            Scanner in1 = new Scanner(;

            B obj = new B();           // Create obj as object

            System.out.print(“Enter X : ”);

            obj.x = in1.nextInt();     // instance variables have to access from object

            System.out.print(“Enter Y : ”);

            obj.y = in1.nextInt();


            if(obj.x > obj.y)


            System.out.println(“X is Max”);




            System.out.println(“Y is Max”);






Enter X: 56

Enter Y: 67

Y is Max


In this example, we can see instance variables x and y can access from main class using of class object.


Simple Class Examples

1Declare one array in Class and create ascending order of that array in main class
2Declare 6 subject variable in Subject class and find total and percentage in main class
3Create Employee class with EmpNo, Name , address , BasicSal , SaleAmount and netsalary instance variable. Display all data in main class. Netsalary = [BasicSal + SaleAmount*15%]

Video available on YouTube.




If you have query about this blog, you can directly post comment or subscribe on website.



857total visits,1visits today


Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Comments are closed.