📊 Data Types & Variables
Understand how data is stored, represented, and manipulated using Java's strong typing system.
Primitive Data Types
Java is a strongly typed language. Every variable must have a declared type. Java defines 8 primitive data types:
| Type | Size | Range / Values | Default |
|---|---|---|---|
| byte | 1 byte | -128 to 127 | 0 |
| short | 2 bytes | -32,768 to 32,767 | 0 |
| int | 4 bytes | -231 to 231-1 | 0 |
| long | 8 bytes | -263 to 263-1 | 0L |
| float | 4 bytes | Fractional, up to 7 decimal digits | 0.0f |
| double | 8 bytes | Fractional, up to 15 decimal digits | 0.0d |
| char | 2 bytes | 0 to 65,535 (Unicode characters) | '\u0000' |
| boolean | 1 bit (varies) | true or false | false |
DataTypesDemo.java
Java
public class DataTypesDemo { public static void main(String[] args) { byte b = 100; short s = 10000; int i = 1000000; long l = 10000000000L; // 'L' suffix for long literal float f = 3.14f; // 'f' suffix for float literal double d = 3.14159265359; char c = 'A'; boolean isJavaFun = true; System.out.println("Integer: " + i); System.out.println("Double: " + d); } }
Reference Types
Unlike primitives which store raw values, reference types store memory addresses referencing an object. Examples include Strings, Arrays, and Classes. The default value of any reference variable is null.
Type Casting
Type casting is when you assign a value of one primitive data type to another type.
- Widening Casting (Implicit): Converting a smaller type to a larger type size. Done automatically.
byte → short → char → int → long → float → double - Narrowing Casting (Explicit): Converting a larger type to a smaller size type. Must be done manually by placing the type in parentheses.
double → float → long → int → char → short → byte
TypeCastingDemo.java
Java
public class TypeCastingDemo { public static void main(String[] args) { // Widening (Implicit) int myInt = 9; double myDouble = myInt; // Automatic casting: int to double // Narrowing (Explicit) double exactValue = 9.78; int truncatedInt = (int) exactValue; // Manual casting: double to int System.out.println(truncatedInt); // Outputs 9 } }
Constants and var
Use the final keyword to declare constants (values that cannot change). Java 10 introduced the var keyword for local variable type inference.
final double PI = 3.14159; // Cannot be reassigned var message = "Hello"; // Compiler infers type as String
Variable Scope
Scope refers to the region of the program where a variable is accessible:
- Local Scope: Variables declared inside methods or blocks. Only accessible within that block.
- Instance Scope: Variables declared in a class but outside methods. Each object gets its own copy.
- Static/Class Scope: Variables declared with the
staticmodifier. Shared across all instances of the class.