Introduction
In Java programming, variables are one of the most fundamental concepts. They act as containers that store data values while a program is running. Without variables, it would be impossible to process or manipulate data in Java. If you’re just starting your Java journey, understanding variables is a must!
What is a Variable?
A variable in Java is a name given to a memory location where data is stored. It allows developers to store, update, and retrieve values while the program is being executed. Think of a variable as a labeled box where you can keep information for later use.
Syntax of a Variable in Java
In Java, the syntax for declaring a variable is:
dataType variableName = value;
-
dataType → Type of data (e.g., int, double, char, String).
-
variableName → User-defined name for the variable.
-
value → The initial data assigned (optional).
Example:
int age = 20;
String name = "John";
double salary = 45000.50;
Types of Variables in Java
Java provides different kinds of variables based on their scope and usage:
-
Local Variables
-
Declared inside a method, constructor, or block.
-
Created when the method is invoked and destroyed after it finishes.
-
Example:
void display() { int num = 5; // local variable System.out.println(num); }
-
-
Instance Variables
-
Declared inside a class but outside any method.
-
Belong to an object of the class.
-
Example:
class Student { String name; // instance variable int age; }
-
-
Static Variables (Class Variables)
-
Declared with the keyword
static. -
Shared among all objects of the class.
-
Example:
class Student { static String school = "Gyanarjan School"; // static variable }
-
Rules for Naming Variables in Java
-
Must begin with a letter, underscore
_, or dollar sign$. -
Cannot start with a digit.
-
Java is case-sensitive (
Ageandageare different). -
Cannot use reserved keywords (like
class,int). -
Use meaningful names for better readability.
Example:
✔ int marks;
✔ double totalSalary;
❌ int 123name;
Example Program
public class VariablesExample {
static String school = "Sunrise School"; // static variable
String studentName; // instance variable
public void display() {
int marks = 95; // local variable
System.out.println("Student: " + studentName);
System.out.println("School: " + school);
System.out.println("Marks: " + marks);
}
public static void main(String[] args) {
VariablesExample obj = new VariablesExample();
obj.studentName = "Rahul";
obj.display();
}
}
Output:
Student: Rahul
School: Sunrise School
Marks: 95
Conclusion
Variables are the backbone of any Java program. They allow programmers to store, manipulate, and retrieve data efficiently. By understanding local, instance, and static variables, you’ll be able to write cleaner and more structured Java code. Mastering variables is the first step toward becoming a skilled Java programmer.
Comments
Post a Comment