Advertisement
Google Ad Slot: content-top
Java Variables
In Java, variables are used to store data values that can be referenced and manipulated in a program. Every variable in Java has a data type, a name, and a value.
Primitive Data Types:
- Directly store values (e.g., numbers, characters).
- Default Values: Automatically initialized for instance/static variables.
Type |
Size |
Default Value |
Description |
Example |
|---|---|---|---|---|
byte |
8 bits |
0 |
Small integer range (-128 to 127). |
byte b = 10; |
short |
16 bits |
0 |
Medium integer range (-32,768 to 32,767). |
short s = 3000; |
int |
32 bits |
0 |
Standard integer range (-2^31 to 2^31-1). |
int age = 25; |
long |
64 bits |
0L |
Large integer range (-2^63 to 2^63-1). |
long distance = 100000L; |
float |
32 bits |
0.0f |
Decimal with 6-7 digits of precision. |
float pi = 3.14f; |
double |
64 bits |
0.0d |
Decimal with 15-16 digits of precision. |
double e = 2.71828; |
char |
16 bits |
\u0000 |
A single character (Unicode). |
char grade = 'A'; |
boolean |
8 bits |
false |
Logical true/false. |
boolean isActive = true; |
Reference Data Types
- Definition: Reference variables store the memory address (reference) of an object instead of the actual value.
- Characteristics:
- Used to reference objects (like arrays, strings, or user-defined objects).
- Default value is
null. - You can call methods on reference types.
Type |
Description |
Default Value |
Example |
|---|---|---|---|
String |
Stores a sequence of characters. Immutable in nature. |
null |
String name = "John"; |
Array |
Stores a fixed-size collection of elements of the same data type. |
null |
int[] numbers = {1, 2, 3}; |
Class/Object |
Represents an instance of a user-defined class or an object. |
null |
MyClass obj = new MyClass(); |
Variable Naming Rules:
- Must start with a letter,
_, or$. - Cannot start with a number.
- Cannot use reserved keywords.
- Should be descriptive and use camelCase.