What is a Variable in Java?
A variable is a named memory location used to store data. The value stored in a variable can change during program execution.Syntax:
dataType variableName = value;
Example :
Example :
int age = 25;
In this example:
In this example:
- int is the data type.
- age is the variable name.
- 25 is the value assigned to the variable.
Why Are Variables Important?
The Variables help programmers:- Store user information.
- Perform calculations.
- Manage application data.
- Make programs dynamic and interactive.
Without variables programs would only work with fixed values.
Types of Variables in Java
The Java provides three main types of variables:
1. Local Variables
The Local variables are declared inside methods, constructors or blocks.
public class Example {
public static void main(String[] args) {
int number = 10;
System.out.println(number);
}
}
Output:
10
2. Instance Variables
The Instance variables belong to an object & are declared inside a class but outside methods.
class Student {
String name = "John";
}
Each object gets its own copy of the instance variable.
3. Static Variables
The Static variables belong to the class rather than objects.
class Company {
static String companyName = "Tech Corp";
}
All objects share the same static variable.
Java Data Types Used with Variables
Integer :
int age = 20;
Double :
double price = 99.99;
Character :
char grade = 'A';
Boolean :
boolean isJavaFun = true;
String :
String name = "Vikas";
Practical Examples of Java Variables
Example 1: Simple Calculator
public class Calculator {
public static void main(String[] args) {
int num1 = 15;
int num2 = 10;
int sum = num1 + num2;
System.out.println("Sum = " + sum);
}
}
Output :
Sum = 25
Example 2: Product Price Calculation
public class Product {
public static void main(String[] args) {
double price = 500.50;
int quantity = 2;
double total = price * quantity;
System.out.println("Total Price = " + total);
}
}
Output :
Total Price = 1001.0
Variable Naming Rules in Java
Follow these rules when naming variables:
- The Variable names are case-sensitive.
- Names can start with letters, $ or _.
- Names cannot start with numbers.
- Reserved Java keywords cannot be used.
- Use meaningful names for better readability.
The Java variables are used to store data that programs can use and modify. Understanding variables is essential because they form the foundation of Java programming. By learning local, instance & static variables along with proper naming conventions & data types we can write cleaner and more efficient Java applications.