Java Variables and Data Types

📘 Java 👁 65 views 📅 Dec 01, 2025
⏱ Estimated reading time: 2 min

Java Variables and Data Types

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.


1. Variables in Java

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.

Types of Variables

  1. Local Variables
    Declared inside methods, constructors, or blocks. They must be initialized before use.

  2. Instance Variables
    Declared inside a class but outside methods. Each object gets its own copy.

  3. Static Variables
    Declared with the static keyword. They belong to the class, not to objects.

Example:

int age = 25;

2. Primitive Data Types

Java provides eight primitive data types, each representing the most basic forms of data. They store simple values and have fixed memory sizes.

List of Primitive Types

TypeSizeRange/Description
byte1 byte-128 to 127
short2 bytes-32,768 to 32,767
int4 bytesCommon integer type
long8 bytesLarge integer values
float4 bytesSingle-precision decimal values
double8 bytesDouble-precision decimals
char2 bytesSingle Unicode character
boolean1 bittrue or false

Characteristics

  • Primitive types are predefined by Java.

  • They store values directly in memory.

  • They do not support methods or behaviors.

Example:

double price = 99.50; boolean isActive = true;

3. Reference Data Types

Reference types store the memory address of objects rather than the actual value.

Examples

  • 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:

String name = "John"; int[] numbers = {1, 2, 3};

4. Type Conversion and Casting

Java automatically performs type conversions when assigning a smaller type to a larger type (widening).

Example:

int a = 10; double b = a; // widening conversion

Casting is required when converting a larger type to a smaller type (narrowing):

double x = 9.5; int y = (int) x; // narrowing conversion

Conclusion

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.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes