
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Class Variables, Instance Variables, and Local Variables in Java
A variable provides us with named storage that our programs can manipulate. Java provides three types of variables.
Class variables ? Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Instance variables ? Instance variables are declared in a class, but outside a method. When space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
Local variables ? Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
Example
public class VariableExample{ int myVariable; static int data = 30; public static void main(String args[]){ int a = 100; VariableExample obj = new VariableExample(); System.out.println("Value of instance variable myVariable: "+obj.myVariable); System.out.println("Value of static variable data: "+VariableExample.data); System.out.println("Value of local variable a: "+a); } }
Output
Value of instance variable myVariable: 0 Value of static variable data: 30 Value of local variable a: 100