Tuesday, July 30, 2024

Instance Variables (Global Variables)

 

Instance Variables (Global Variables)

Instance Variables:

  • These are variables declared inside a class but outside any method, constructor, or block.
  • Instance variables are also known as global variables as they are accessible across the class.
  • Each object of the class has its own copy of the instance variables.
  • They are initialized to default values if not explicitly initialized.
  • We can access instance variable inside the instance method.

Instance Methods (Non-Static Methods)

Instance Methods:

  • Methods defined without the static keyword are called instance methods or non-static methods.
  • These methods can access instance variables and other instance methods directly
  • To call the instance method, we need to create an object of the class.
  • Syntax:

ObjeRefvar.InstanceMethod();

We cannot call instance methods directly from static method.

Ex:   IM1(); // invalid

We cannot call instance variables directly from static method

Ex: InstanceVar;

ex:

package OOPSBasics;

public class Dog

{             

               //  instance var

               int did;

               String name;

               String color;

               //  Instance method //

               //  Define Display()   and access instance variable did, name

                public  void display() //  non static method (or) Instance Method

                {

                               System.out.println("d id ="+ did + ", d name="+ name);                                               

                }                     

               public static void main(String[] args) //  static  method    

               {             

//                           System.out.println("d id ="+ did + ", d name="+ name);

                               //CE: we cannot access Instance vraibles directly inside static method

                               

                              //  create object for Dog-class

                              Dog d1 = new Dog();

                              //did= 101;

                              d1.did =101;

                              //name = "Dolly";

                              d1.name = "Dolly";

                              //

                              //color = "Black";

                              d1.color = "Black";

                              // call instance method -Display();

                              d1.display();

                              // creating one more obj of dog class with ref variable d2

                              Dog d2 = new Dog();

                              //did =102;

                              d2.did = 102;

                              //name = "Dolly-2";

                              d2.name = "Dolly-2";

                              //color = "White";

                              d2.color = "White";

                              // call Display();

                              d2.display();

               }

}

o/p:

d id =101, d name=Dolly

d id =102, d name=Dolly-2

--------------------------------------

package OOPSBasics;

public class A

{

               // Instance Variables

                              String name;

                              int id;

                             

               //  define playCricket - instance Method

                              //  Instance method--    with out static k/w

                              public  void playCricket() // Non static method or Instance method

                              {

                                             // access instance variable inside Instance method

                                             System.out.println("name= "+ name + ",id="+ id);

                              }

                                            

                              public static void main(String[] args)  //  static method

                              {             

                                            

                                             //  accces  instance variable  +  Instance Method -- first we have to create obj for the class

                                             // Create obj for class -A

                                             A a1ref =  new A();

                                                            // playCricket();

//                                          playCricket();// error

                                             a1ref.playCricket();

                                            

                              }

               }

o/p:

----------

name= null,id=0

---------------------

HW write the o/p for below program ?

package OOPsBasics1;

public class A {

               // Instance Varaibles

               String name;

               int id;

              

               void display() //  Instance method--    with out static k/w

               {

                              // can access instance variable

                              System.out.println("name= "+ name + ",id="+ id);

               }

              

               public static void main(String[] args) {

                             

                             

                              //  acces  instance variable  +  Instance Method -- first we ahve to create obj for the class

                              // Create obj for class -A

                             

                              //call display();

                             

//                           name = "Ramu"; and .id = 101;

              

                             

               //call display();

                             

                             

               }

}

o/p:

FAQ Diff b/w Instance variable and Local Variable:?

Instance Variables (Global Variables):

1.     Definition:

    • The variables which are declared inside a class but outside of any method are called instance variables.

2.     Default Values:

    • Instance variables will have some default values based on their data type (e.g., 0 for integers, null for objects, etc.).

3.     Initialization:

    • It is not compulsory/mandatory to assign values to instance variables. They get default values automatically.

4.     Access:

    • Instance variables can be accessed inside both instance methods and static methods.

 

Local Variables

1.     Definition:

    • Variables declared inside a method are called local variables.

2.     Default Values:

    • Local variables do not have default values based on their data type. They must be initialized before use.

3.     Initialization:

    • It is compulsory to assign values to local variables before accessing them. Otherwise, it throws a compile-time error: "The local variable res may not have been initialized".

4.     Access:

    • Local variables can be accessed only within the method where they are declared and cannot be accessed outside of that method.

 

Feature

Instance Variables

Local Variables

 

Definition

Declared inside a class but outside any method

Declared inside a method

 

Default Values

Have default values based on their data type (e.g., 0 for int, null for objects)

Do not have default values, must be explicitly initialized

 

Initialization

Not mandatory to initialize; they get default values automatically

Must be initialized before use, otherwise a compile-time error occurs

 

Scope

Accessible anywhere in the class, including all methods

Accessible only within the method where they are declared

 

Memory Allocation

Allocated in the heap memory when an object is created

Allocated on the stack during method execution

 

Lifetime

Exists as long as the object exists

Exists only during the execution of the method

 

Access

Can be accessed by instance methods and static methods

Can only be accessed within the method where they are declared

 

Examples

String name; int age;

int result; String message;

 

package OOPSBasics;

public class LocalVaraible

{

               // Instance variable name, id

               String name; //def val -> null

               int id; //-->  def val  --> 0  

              

               // Instance variable  -- def val : null

               // Instance variable  --->               0

               //Define add()  -- non static method

               public void add() // Instance method

               {

                              System.out.println("name="+ name + ", id="+ id);

                              //define local variable , c, d

                              int c, d;

                              //check  local variable defined in side main()- cannot be accessed here

//                           System.out.println("a="+a + ",b="+b);//Error a cannot be resolved to a variable               

               }

               public static void main(String[] args)

               {

                              // defining /declaring local variable a,b

                              int a,b; // local variable

                             

                              // check local variable will not have any default values

//                           System.out.println("a="+a);// 0 or Error --> error

                              //// Error : The local variable a may not have been initialized

                              //check   we must assign some value to  local var

                              // local var

                                a =10;

                                b =20;

                                System.out.println("a="+a);

                                //                     10            

                               

                              //local can be accessed inside method where we declare only

                              //  local variable  can not be accessed in other method i.e add()

               }

}

    Data type                Default values to "Instance variables"

-----------------------------------------------------------------------

    int       -->    

    long        -->     

    byte   -->                       

   short  -->                       

    float       -->   

    double              -->

   char   -->    

  boolean             -->          FAQ (What is the default value for Boolean variable )

  String -->

Class var// ref variable  --> null

Interface variable                 -->  null

No comments:

Post a Comment

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...