Variable in Java:
A variable is a named storage location used to hold a value of a particular data type.
For example:
int age = 20;
String name = "Gowtham";
Here:
- int is the data type.
- age is the variable name.
- 20 is the value stored in the variable.
- String is the type used to represent text.
- name is the variable name.
- "Gowtham" is the text value.
Types of Variables in Java
Java has three main categories of variables based on where they are declared.
1. Local Variable
A local variable is declared inside a method, constructor, or block.
void display() {
int age = 20;
System.out.println(age);
}
2. Instance Variable
An instance variable is declared inside a class but outside methods. Each object has its own instance fields.
class Student {
String name = "Gowtham";
int age = 20;
}
3. Static Variable
A static variable belongs to the class rather than to individual objects.
class Student {
static String college = "ABC College";
}
The static variable college is shared at the class level.
Object in Java?
An object is an instance of a class.
A class defines the data and behaviors that its objects can have.
For example, Student can be a class, while individual students can be represented by objects of that class.
Example
`class Student {
String name;
int age;
void display() {
System.out.println(name);
System.out.println(age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Gowtham";
s1.age = 20;
s1.display();
}
}`
Output:
Gowtham
20
Explanation
- Student is the class.
- s1 is a reference variable.
- new Student() creates a new Student object.
- s1.name assigns a name to the object.
- s1.age assigns an age to the object.
- s1.display() calls the object's method.
Top comments (0)