Java is a strongly typed programming language, which means every variable must be declared with a specific data type. Data types determine the type of data a variable can hold, the amount of memory it requires, and the operations that can be performed on it. Java provides two major categories of data types: primitive data types and reference data types.
A variable is a named memory location used to store data during program execution.
In Java, a variable must be declared before use, specifying its type.
Local Variables
Declared inside methods, constructors, or blocks. They must be initialized before use.
Instance Variables
Declared inside a class but outside methods. Each object gets its own copy.
Static Variables
Declared with the static keyword. They belong to the class, not to objects.
Example:
Java provides eight primitive data types, each representing the most basic forms of data. They store simple values and have fixed memory sizes.
| Type | Size | Range/Description |
|---|---|---|
| byte | 1 byte | -128 to 127 |
| short | 2 bytes | -32,768 to 32,767 |
| int | 4 bytes | Common integer type |
| long | 8 bytes | Large integer values |
| float | 4 bytes | Single-precision decimal values |
| double | 8 bytes | Double-precision decimals |
| char | 2 bytes | Single Unicode character |
| boolean | 1 bit | true or false |
Primitive types are predefined by Java.
They store values directly in memory.
They do not support methods or behaviors.
Example:
Reference types store the memory address of objects rather than the actual value.
Classes (e.g., String, Scanner)
Arrays
Interfaces
Characteristics:
Always created using the new keyword (except String literals).
Can contain methods and properties.
They occupy more memory than primitive types.
Example:
Java automatically performs type conversions when assigning a smaller type to a larger type (widening).
Example:
Casting is required when converting a larger type to a smaller type (narrowing):
Java variables act as storage units, and data types define the nature of data stored in these variables. The eight primitive types provide fundamental building blocks, whereas reference types allow creation of complex objects. Understanding variables and data types is essential for writing efficient and error-free Java programs.
Take quizzes related to this topic and see where you stand!
Start Quiz Now