Variable in Java is a data container that stores the data values during Java program execution. Every variable is assigned data type which designates the type and quantity of value it can hold. Variable is a memory location name of the data.They are declared using the var keyword, followed by the variable name and the data type. Variables can be categorized into instance variables, class variables (static variables), and local variables. Instance variables belong to a specific object, class variables are shared among all instances of the class, and local variables are declared within methods or blocks and have limited scope.
public void Local-variable() { int a = 9; // Locale variable. b = 10; // Locale variable. String s = ”Local Variable”;
System.out.print("a is ="+a +"b is =" +b +"string is="+c);
// Locale Varial is use in a block or Method. } }
Output :- a is = 9 b is = 10 string is = Local Variable
import java.io. * ; class Demo { int height, weight; // Instance Variables Demo(int h, int w) { this.height = h; this.weight = w; } void run() { System.out.println(“Huff Puff”); } void print() { System.out.println(“Now my weight is” + this.weight); } public static void main(String[] args) throws IOException { Demo A = new Demo(170, 65); A.run(); A.print(); } }
Static variable :-Static variables are declared with the static keyword within a class but outside any method, constructor, or block of code. They are associated with the class itself rather than with instances of the class. For example, the following code declares a static variable called counter within the Counter class. A variable that is declared within a class and is shared by all instances of the class.
import java.io. * ;class DataFlair {static int studentCount;DataFlair() {studentCount = 15; } void addStudent() { studentCount++; } public static void main(String[] args) throws IOException { DataFlair java = new DataFlair(); DataFlair python = new DataFlair(); java.addStudent(); python.addStudent(); System.out.println("Total Students " + studentCount); } }
There are particular conventions to be followed when naming variables to enhance the readability of the program.
Declaration of a variable in a computer programming language is a statement used to specify the variable name and its data type. Declaration tells the compiler about the existence of an entity in the program and its location. When we declare a variable, And Initialization is the process of assigning a value to the Variable..
Declaration and Initialization Syntax of variable :-
Data_type variable_Name ; // Declaration of variable.
variable_Name = Value _Of_ Variable; // Initialization of variable.
Note :- We Have Also Declaration and Initialization at once like.
Data_type variable_Name = Value _Of_ Variable; // Declaration and Initialization of variable.
Example :– int Age = 45; // Declaration and Initialization of variable.