Type Basics
Introduction to Java Types
In Java, type is a fundamental concept that defines the kind of data a variable can hold. Understanding types is crucial for writing robust and error-free code. Java is a statically-typed language, which means that every variable must be declared with a specific type before it can be used.
Primitive Types
Java provides eight primitive types, which are the most basic data types:
Type |
Size (bits) |
Range |
Default Value |
byte |
8 |
-128 to 127 |
0 |
short |
16 |
-32,768 to 32,767 |
0 |
int |
32 |
-2^31 to 2^31 - 1 |
0 |
long |
64 |
-2^63 to 2^63 - 1 |
0L |
float |
32 |
Approximately Âą3.40282347E+38 |
0.0f |
double |
64 |
Approximately Âą1.79769313486E+308 |
0.0d |
char |
16 |
0 to 65,536 |
'\u0000' |
boolean |
1 |
true or false |
false |
Type Hierarchy Visualization
graph TD
A[Object] --> B[Primitive Types]
A --> C[Reference Types]
B --> D[byte]
B --> E[short]
B --> F[int]
B --> G[long]
B --> H[float]
B --> I[double]
B --> J[char]
B --> K[boolean]
C --> L[Class Types]
C --> M[Interface Types]
C --> N[Array Types]
Code Example: Type Declaration
public class TypeBasicsDemo {
public static void main(String[] args) {
// Primitive type declarations
int age = 25;
double salary = 5000.50;
boolean isStudent = true;
char grade = 'A';
// Type inference with var (Java 10+)
var name = "John Doe"; // Inferred as String
var number = 42; // Inferred as int
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Is Student: " + isStudent);
System.out.println("Grade: " + grade);
System.out.println("Name: " + name);
System.out.println("Number: " + number);
}
}
Type Conversion
Java supports two types of type conversion:
- Implicit (Widening) Conversion
- Explicit (Narrowing) Conversion
Implicit Conversion
Occurs automatically when converting to a larger type:
int smallNumber = 100;
long largeNumber = smallNumber; // Automatic conversion
Explicit Conversion
Requires manual casting when converting to a smaller type:
long largeNumber = 1000L;
int smallNumber = (int) largeNumber; // Explicit casting
Best Practices
- Choose the smallest type that can accommodate your data
- Use type inference when possible
- Be cautious with explicit type conversions
- Understand the potential for data loss during conversion
By mastering these type basics, you'll write more efficient and error-resistant Java code. LabEx recommends practicing these concepts to build a strong foundation in Java programming.