In Java, data types represent the type of data that can be stored in a variable. Variables, on the other hand, are containers for storing data values. Here's an overview of data types and variables in Java:
Data Types:
- Primitive Data Types:
- Primitive data types are the most basic data types in Java.
- They are predefined by the language and are not objects.
- Java has eight primitive data types:
byte
: 8-bit integer value.short
: 16-bit integer value.int
: 32-bit integer value.long
: 64-bit integer value.float
: 32-bit floating-point value.double
: 64-bit floating-point value.char
: 16-bit Unicode character.boolean
: Represents true or false.
- Reference Data Types:
- Reference data types are used to create objects and arrays.
- They are references to objects in memory and do not hold the actual data.
- Examples include classes, interfaces, arrays, and enums.
Variables:
- Declaration:
- Variables must be declared with a data type before they can be used.
- Syntax:
data_type variable_name;
- Initialization:
- Variables can be initialized with an initial value at the time of declaration.
- Syntax:
data_type variable_name = initial_value;
- Naming Rules:
- Variable names must start with a letter, underscore (_), or dollar sign ($).
- They can contain letters, digits, underscores, and dollar signs.
- They are case-sensitive.
- They cannot be a reserved keyword.
Examples:
// Primitive Data Types
byte byteVar = 127;
short shortVar = 32000;
int intVar = 1000000;
long longVar = 1000000000000L; // Note the 'L' suffix for long literals
float floatVar = 3.14f; // Note the 'f' suffix for float literals
double doubleVar = 3.14159;
char charVar = 'A';
boolean boolVar = true;
// Reference Data Types
String stringVar = "Hello, Java!";
Object objectVar = new Object();
int[] arrayVar = {1, 2, 3, 4, 5};
0 Comments