Special Offer take any 4 courses for INR 21999.00*

Courses
0

Explain the concept of variables in Java. What are the types of variables?

December 26, 2024

In Java, a variable is a container for storing data values during the execution of a program. Variables are associated with a specific data type, which determines the kind of values they can hold (e.g., integers, characters, etc.). Each variable must have a name and type. Variables act as named memory locations that allow programs to manipulate data.
Types of Variables in Java
Java has three main types of variables:
Local Variables
Defined within a method, constructor, or block.
Only accessible within the scope where they are declared.
Must be initialized before use.
Example:
void show() {
int num = 5; // local variable
System.out.println(num);
}
Instance Variables
Declared inside a class but outside methods or constructors.
Belong to an instance of the class (each object has its own copy).
Default values are assigned if not explicitly initialized (e.g., 0 for int, null for objects).
Example:
class Person {
String name; // instance variable
int age; // instance variable
}
Static Variables
Declared with the static keyword inside a class.
Shared among all objects of the class (single copy).
Useful for constants or data shared across instances.
Example:
class Example {
static int count = 0; // static variable
}

Leave a Comment

Drop a Query

Whether to upskill or for any other query, please drop us a line and we'll be happy to get back to you.

Drop a Query NEW

Request A Call Back

Please leave us your contact details and our team will call you back.

Request A Call Back

By tapping Submit, you agree to Cambridge infotech Privacy Policy and Terms & Conditions

Enquiry Now

Enquiry popup