Data Types and Variables
In Java, a variable is a container for storing data values, and each variable has a data type that defines what kind of value it can hold. Understanding data types and variables is essential because they allow you to work with and manipulate data in your programs.
Data Types in Java
Java has two main types of data types:
1. Primitive Data Types: These are the most basic data types, and Java has 8 of them:
Data Type | Size | Default | Range |
---|---|---|---|
byte | 1 byte | 0 | -128 to 127 |
short | 2 bytes | 0 | -32,768 to 32,767 |
int | 4 bytes | 0 | -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | 0 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 4 bytes | 0.0f | 1.4E-45 to 3.4028235E38 |
double | 8 bytes | 0.0d | 4.9E-324 to 1.7976931348623157E308 |
boolean | 1 bit | false | true / false |
char | 8 bytes | \u0000 | 0 to 65535 |
2. Non-Primitive (Reference) Data Types: These are more complex types and include things like:
- String : Holds a sequence of characters (text). Example: String name = "Alice";
- Arrays : More advanced, used for storing collections of data or creating custom data types.
- Classes
- Interfaces
Variables in Java
A variable is a name given to a memory location that stores a specific type of data.
Declaring a Variable
To declare a variable, you need to specify the data type and the variable name. For example:
int age; // Declares an integer variable named age double price; // Declares a double variable named price String name; // Declares a String variable named name
Initializing a Variable
To give a variable a value, you can initialize it at the time of declaration or later in the code:
int age = 25; // Declaration and initialization age = 30; // Reassigning a new value String name = "Alice"; // Declaration and initialization
Examples of Variables
Here is a small program showing different types of variables:
public class DataTypesExample { public static void main(String[] args) { int age = 25; double price = 19.99; char grade = 'A'; boolean isJavaFun = true; String name = "Alice"; System.out.println("Age: " + age); System.out.println("Price: " + price); System.out.println("Grade: " + grade); System.out.println("Is Java fun? " + isJavaFun); System.out.println("Name: " + name); } }