TYPES OF VARIABLE

VARIABLE:

In Java, variables serve as storage containers for data types like numbers, text, and objects.

TYPES OF VARIABLES IN JAVA: (3 types)

  • Local variable
  • Instance variable
  • Static variable

Local variable

  • A local variable is one that is declared inside the method body. Only that method may utilize this variable, and none of the other methods in the class are even aware that it exists.
  • A local variable cannot be defined with “static” keyword.

Instance variable:

  • An instance variable is created when an Object class is generated and it gets destroyed when the same object class is destroyed
  • Programmers can use access specifiers for instance variables
  • It is not mandatory to initialize instance variables

Static Variable:

  • A variable that is declared as static is called a static variable.
  • It cannot be local.
  • You can create a single copy of the static variable and share it among all the instances of the class.

STATIC VS NON-STATIC:

FEATURESTATIC VARIABLENON-STATIC VARIABLE
DefinitionA static variable is a variable that is declared using the static keyword.A non-static variable is a variable that is not declared using the static keyword.
AccessCan be accessed using class name.Can be accessed using object reference.
ScopeScope is limited to the class.Scope is limited to the object.
InitializationInitialized only once when the class is loadedInitialized each time an object is created.
UsageUsed to represent class-level data.Used to represent object-level data.
Example
static int count = 0;
public int age;
private String name;
InheritanceCan be inherited by the subclass.
Cannot be inherited by the subclass.

Life Cycle
It is created when the class is loaded and destroyed when the class is unloaded.It is created when the object is created and destroyed when the object is garbage collected.
SCOPE: Scope determines the accessibility of variables, objects, and functions from different parts of the code.

Static variables:

  • Static variables in Java are class-level variables that are shared among all objects of a class.
  •  They are declared using the “static” keyword and are stored in the class area.
  • They are also known as class variables.

SYNTAXaccessSpecifier static dataType variableName;

Example: public static int age=12;

Non-static variables:

Non-static (also known as an instance) variables in Java are specific to a single instance of a class and can hold different values for each object of the class.

SYNTAXaccessSpecifier dataType variableName;

Example: private int age;
public String name;
float mark; //default

Output

Advertisements

Comments

Popular posts from this blog

"Don't Believe Everything You Think"-Joseph Nguyen

HOW JAVA WORKS

How Java Works (Interview Question Answers)