1.

Variables in Java

Answer»

In Java, a variable is a data container that stores data values during the execution of a Java program. A data type is allocated to each variable, indicating the type and quantity of data it may store. It is a program’s fundamental storage unit. All variables in Java must be defined before they may be used.

Syntax of declaring a variable:-

datatype variable_name;

Here, datatype refers to the type of data that can be stored in the variable. variable_name refers to the name of the variable being declared.

In the above image, we can see that a variable named ‘age’ has been declared of type ‘int’ and has been initialised with the value ‘20’.

Types of variables:-



  • Local variable - A local variable is a variable defined within a block, method, or constructor. These variables have a scope that is limited to the block in which they are defined. i.e., these variables are only accessible within that block.


  • Instance variable - Variables that are declared inside a class without the ‘static’ keyword are referred to as instance variables. Instance variables are replicated for every object of the class being created.


  • Static variable - Variables that are declared inside a class with the ‘static’ keyword are referred to as static variables. Static variables are shared by all the objects of the class and are not replicated. Static variables are created at the start of program execution and automatically destroyed when the program is finished. It is not necessary to initialise a static variable. It has a value of 0 by default.




Discussion

No Comment Found