Variables and Data Types in Java
In Java, variables are used to store data values. Java is a statically-typed language, meaning you must declare the type of a variable before using it. Variables are essential for storing and manipulating data in programs.
Example:
// Variables in Java
int age = 25; // Integer
double height = 5.9; // Double
String name = "Alice"; // String
boolean isStudent = true; // Boolean
Common Data Types in Java:
- int: Whole numbers (e.g., 10, -5).
- double: Decimal numbers (e.g., 3.14, -0.001).
- String: Text data (e.g., "Hello", "Java").
- boolean: True or False values.
- char: Single characters (e.g., 'A', 'b').
Variable Declaration and Initialization
Variables in Java must be declared with a specific data type before they can be used. They can be initialized at the time of declaration or later.
int x; // Declaration
x = 10; // Initialization
double pi = 3.14; // Declaration and initialization
Type Casting
Type casting is the process of converting one data type into another. Java supports both implicit (automatic) and explicit (manual) type casting.
// Implicit Casting (Widening)
int num = 10;
double decimal = num; // Automatically converts int to double
// Explicit Casting (Narrowing)
double decimal = 10.5;
int num = (int) decimal; // Manually converts double to int
Constants
Constants are variables whose values cannot be changed once assigned. In Java, constants are declared using the final
keyword.
final double PI = 3.14159;
// PI = 3.14; // This will cause a compilation error
Variable Scope
The scope of a variable determines where it can be accessed. Variables can have local scope (within a method) or class-level scope (within a class).
public class Main {
static int classVariable = 10; // Class-level variable
public static void main(String[] args) {
int localVariable = 20; // Local variable
System.out.println("Class Variable: " + classVariable);
System.out.println("Local Variable: " + localVariable);
}
}
Primitive vs Reference Types
Java has two categories of data types: primitive types (e.g., int
, double
) and reference types (e.g., String
, arrays, objects).
// Primitive Types
int num = 10;
double decimal = 3.14;
// Reference Types
String name = "Alice";
int[] numbers = {1, 2, 3};
Next: Control Structures