Home / Programs / Instance Variable in Java Programming
🚀 Programming Example

Instance Variable in Java Programming

👁 5,096 Views
💻 Practical Program
📘 Step Learning
Instance variable in java is used by Objects to store their states. Variables which are defined without the STATIC keyword and are Outside any method declaration are Object specific and are known as instance variables. They are called so because their values are instance specific and are not shared among instances.

📌 Information & Algorithm

💻 Program Code

 class InstanceVariable {
int data=50;//instance variable

public static void main(String []args) {
      /* In this example if you want to access instanec variable'data' then you 
      have to create an instane of InstancVariable class like this*/
      InstanceVariable iv = new InstanceVariable();
      /* here iv is the name of the object or instance of the
	   InstanceVariable class */
      System.out.println(iv.data);
      /* to access the instance variable 'data' you have to write iv.data

   }
}

                        

🖥 Program Output

50
Press any key to continue . . .
                            

📘 Explanation

Rules for Instance variable in Java

  • Instance variables can use any of the four access levels
  • They can be marked final
  • They can be marked transient
  • They cannot be marked abstract
  • They cannot be marked synchronized
  • They cannot be marked strictfp
  • They cannot be marked native
  • They cannot be marked static

Cheatsheet

  • Public, Private, Protected?all 3 access modifiers can be applied to Instance Variable(Default?also).
  • Instance variable will get default value means instance variable can be used without initializing it. Same is not true for?Local Variable.
  • Instance Variable?can be marked?final.
  • Instance Variable?can be marked?transient.
  • Instance Variable?cannot be?abstract.
  • Instance Variable?can not?have?synchronized?modifier.
  • Instance Variable?can not?have?strictfp?modifier.
  • Instance Variable?can not?have?the native?modifier.
  • Instance Variable?can not have?Static?modifier as it will become Class level variable.
INSTANCE VARIABLE TYPE DEFAULT VALUE
boolean false
byte (byte)0
short (short) 0
int 0
long 0L
char u0000
float 0.0f
double 0.0d
Object null
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.