Java Variables

Java Variables

A variable in Java is a container used to store data values.
It allows us to reuse and manipulate data in a program.

Example:

int age = 25;
String name = "John";

⭐ Why Variables?

  • To store data (number, text, etc.)

  • To use the value later in the program

  • To perform calculations


🧱 Syntax of Variable

dataType variableName = value;

Examples:

int number = 10;
double price = 59.99;
String message = "Hello";

πŸ“Œ Rules for Naming Variables

Rule Example
Can’t start with a number ❌ 1age βœ” age1
Only letters, numbers, _, $ allowed totalAmount, _value, $data
Case-sensitive Age and age are different
Must not use keywords ❌ class, while, static

Best Practice β†’ Use camelCase:

βœ” studentName
βœ” totalMarks


πŸ§ͺ Declaring & Assigning Variables

1️⃣ Declare and assign later:

int x;
x = 10;

2️⃣ Declare and assign together:

int x = 10;

πŸ“Œ Updating Variables

int num = 5;
num = 20; // updated value
System.out.println(num); // Output: 20

🎯 Multiple Variable Declaration

int a = 10, b = 20, c = 30;
System.out.println(a + b + c);

Output:

60

πŸ”’ Final Variables (Constants)

Use final keyword to create a constant value β€” it cannot be changed.

final int YEAR = 2025;

If you try to change it:

YEAR = 2026; // ❌ Error

πŸ“Š Variable Types

Type Example Description
Local Variable inside a method Temporary, must be initialized
Instance Variable inside a class, outside method Non-static variable
Static Variable declared with static keyword Shared among all objects

Example:

class Example {

static int count = 0; // static variable
int id; // instance variable

public void show() {
int number = 10; // local variable
System.out.println(number);
}
}


πŸ“Œ Example Program

class VariableExample {
public static void main(String[] args) {

String name = "Vipul";
int age = 21;
double height = 5.8;
final String country = "India"; // constant

System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Country: " + country);
}
}


⭐ Summary

Feature Example
Declare Variable int x;
Assign Value x = 10;
Declare + Assign int x = 10;
Constant final int PI = 3;
Naming camelCase recommended

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *