Java Variables and Data Types – Complete Guide with Examples and Usage
Learn everything about Java variables and data types, including types of variables, primitive and non-primitive types, scope, default values, and examples for beginners.
Variables and Data Types in Java – Complete Detailed Tutorial
In Java, variables are containers used to store data values. Each variable has a type that defines the size and layout of memory, the range of values, and the operations that can be performed on it.
Understanding variables and data types is fundamental to writing Java programs.
1. What is a Variable?
A variable is a named memory location that stores data which can be changed during program execution.
Syntax:
Example:
Explanation:
int→ data typeage→ variable name25→ value assigned
2. Types of Variables in Java
Java supports three types of variables:
2.1 Local Variables
- Declared inside a method or block
- Exist only during method execution
- Not initialized by default
2.2 Instance Variables
- Declared inside a class but outside any method
- Belong to objects
- Initialized with default values
2.3 Static (Class) Variables
- Declared with
statickeyword inside class - Shared among all objects of the class
3. Data Types in Java
Java has two main categories of data types:
- Primitive Data Types
- Non-Primitive (Reference) Data Types
3.1 Primitive Data Types
| TypeSizeDefaultDescription | |||
| byte | 1 byte | 0 | Small integer (-128 to 127) |
| short | 2 bytes | 0 | Integer (-32,768 to 32,767) |
| int | 4 bytes | 0 | Integer (-2^31 to 2^31-1) |
| long | 8 bytes | 0L | Large integer (-2^63 to 2^63-1) |
| float | 4 bytes | 0.0f | Single precision decimal |
| double | 8 bytes | 0.0d | Double precision decimal |
| char | 2 bytes | '\u0000' | Single character (Unicode) |
| boolean | 1 bit | false | true/false values |
Example:
3.2 Non-Primitive (Reference) Data Types
- Examples:
String,Arrays,Classes,Interfaces - Store reference to objects, not actual data
- Can call methods on these objects
Example:
4. Type Casting in Variables
Java allows conversion between data types:
4.1 Implicit Casting (Widening)
- Smaller type → Larger type automatically
- Safe conversion
4.2 Explicit Casting (Narrowing)
- Larger type → Smaller type
- May lose data, requires explicit cast
5. Variable Naming Rules
- Must start with a letter, $, or _
- Cannot start with a number
- Case-sensitive (
age≠Age) - No Java reserved keywords
- Use camelCase convention for readability
Example:
6. Example Program – Variables and Data Types
Output:
7. Summary
- Variables store data; types define size, range, operations.
- Three types: Local, Instance, Static
- Two categories: Primitive and Non-Primitive
- Casting allows type conversion
- Proper naming and type usage ensures error-free code