Java Variables

Java Tutorial

Java Variables

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

Example:


 Why Variables?

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

  • To use the value later in the program

  • To perform calculations


 Syntax of Variable

Examples:


 Rules for Naming Variables

RuleExample
Can’t start with a number1ageage1
Only letters, numbers, _, $ allowedtotalAmount, _value, $data
Case-sensitiveAge and age are different
Must not use keywordsclass, while, static

Best Practice → Use camelCase:

  • studentName
  • totalMarks

 Declaring & Assigning Variables

 Declare and assign later:

 Declare and assign together:


 Updating Variables


 Multiple Variable Declaration

Output:

60

Final Variables (Constants)

Use final keyword to create a constant value — it cannot be changed.

If you try to change it:


 Variable Types

TypeExampleDescription
Local Variableinside a methodTemporary, must be initialized
Instance Variableinside a class, outside methodNon-static variable
Static Variabledeclared with static keywordShared among all objects

Example:


 


 Example Program


 


 Summary

FeatureExample
Declare Variableint x;
Assign Valuex = 10;
Declare + Assignint x = 10;
Constantfinal int PI = 3;
NamingcamelCase recommended

You may also like...