Quick Summary
- Java has 8 primitive data types (byte → double).
- Non-primitive types include String, arrays, classes, etc.
- Variables must be declared with a type.
- Widening casting happens automatically; narrowing requires explicit casting.
- Use
finalto create constants.
1. What Are Data Types in Java?
Java is a statically typed language, which means every variable must have a defined data type before use. Data types tell Java what kind of values a variable can store and how much memory it needs.
A. Primitive Data Types (Built-in)
Java provides 8 primitive types:
| Type | Size | Description |
|---|---|---|
| byte | 1 byte | Whole numbers (−128 to 127) |
| short | 2 bytes | Whole numbers (−32768 to 32767) |
| int | 4 bytes | Default integer type |
| long | 8 bytes | Very large whole numbers |
| float | 4 bytes | Decimal numbers (6–7 digits) |
| double | 8 bytes | Precise decimal numbers (~15 digits) |
| boolean | 1 bit | true or false |
| char | 2 bytes | Single character |
B. Non-Primitive Data Types (Reference Types)
These are created by programmers and store references, not values. Examples include:
StringArraysClassesInterfaces
2. Declaring and Initializing Variables
Try this example with
public class VariableDemo {
public static void main(String[] args) {
int count = 10;
double price = 199.99;
boolean active = true;
char grade = 'A';
String tool = "VINAR TECH";
System.out.println("Count: " + count);
System.out.println("Price: " + price);
System.out.println("Active: " + active);
System.out.println("Grade: " + grade);
System.out.println("Tool Name: " + tool);
}
} 3. Type Casting in Java
Type casting means converting one data type into another. Java supports two kinds of casting.
A. Widening Casting (Automatic)
Small → large. No extra code required.
Try example:
public class WideningDemo {
public static void main(String[] args) {
int num = 25;
double result = num; // automatic conversion
System.out.println("Converted value: " + result);
}
} B. Narrowing Casting (Manual)
Large → small. Requires explicit casting.
Try example:
public class NarrowingDemo {
public static void main(String[] args) {
double value = 99.99;
int result = (int) value; // manual conversion
System.out.println("Converted value: " + result);
}
} 4. Constants in Java
Use the final keyword to create unchangeable variables (read-only).
Try example:
public class ConstantDemo {
public static void main(String[] args) {
final int MAX_USERS = 100;
System.out.println("Max supported users: " + MAX_USERS);
}
}