Variables are used to store data values that can be used and manipulated throughout the program. Each variable has a type that defines what kind of data it can hold.
Declaring Variables
Variables are declared by specifying their type followed by the variable name.
Java
1 |
type variableName = value; |
Where:
- type refers to the data type of the variable.
- variableName is the name of the variable you are declaring.
- value is the initial value assigned to the variable (optional, but common when declaring variables).
Examples of declaring variables
Java
1 2 3 4 5 6 7 8 9 10 11 |
int myInteger = 10; // Declares an integer variable double myDouble = 3.14; // Declares a double variable char myChar = 'A'; // Declares a char variable boolean myBool = true; // Declares a boolean variable byte myByte = 127; // Declares a byte variable short myShort = 30000; // Declares a short variable long myLong = 123456789L; // Declares a long variable (L suffix) float myFloat = 5.75F; // Declares a float variable (F suffix) String myString = "Hello, Java!"; // Declares a String variable int[] myArray = {1, 2, 3}; // Declares an array variable MyClass myObject = new MyClass(); // Declares an object of MyClass |
Types of variables
Local Variables
- Declared inside a method, constructor, or block.
- Only accessible within that specific method or block.
- Lifetime: Exists only while the method or block is executing.
1 2 3 4 |
public void display() { int localVar = 10; // Local variable System.out.println("Local Variable: " + localVar); } |
Instance Variables
- Declared outside methods, but inside a class.
- Belong to an object; each object gets its own copy.
- Lifetime: Exists as long as the object exists.
1 2 3 4 5 6 7 8 9 10 11 |
public class Person { String name; // Instance variable public void setName(String name) { this.name = name; } public void getName() { System.out.println("Name: " + name); } } |
Class (Static) Variables
- Declared with the
static
keyword inside a class. - Belong to the class rather than any specific object.
- Shared by all objects of the class.
1 2 3 4 5 6 7 |
public class Employee { static int companyCode = 12345; // Class variable public void displayCode() { System.out.println("Company Code: " + companyCode); } } |