Java Data Types - Detailed
Java me data types do prakar ke hote hain: Primitive aur Non-Primitive (Reference Types).
Primitive types fixed size ke hote hain aur directly variable ke value ko store karte hain.
Primitive Data Types
Data Type | Size | Default Value | Range / Description |
---|---|---|---|
byte | 1 byte | 0 | -128 to 127 |
short | 2 bytes | 0 | -32,768 to 32,767 |
int | 4 bytes | 0 | -2^31 to 2^31-1 |
long | 8 bytes | 0L | -2^63 to 2^63-1 |
float | 4 bytes | 0.0f | Single precision decimal |
double | 8 bytes | 0.0d | Double precision decimal |
char | 2 bytes | '\u0000' | Unicode character |
boolean | 1 bit | false | true or false |
Non-Primitive Data Types
Classes, Interfaces, Arrays, Strings aise types hote hain jinka size fixed nahi hota. Inhe reference types bhi kaha jata hai kyunki variable object ka reference store karta hai, value nahi.
String name = "Rahul";
int[] numbers = {1, 2, 3, 4};
List list = new ArrayList<>();
Java Exception Handling - Detailed Explanation
Exception handling Java me runtime errors ko handle karne ka process hai taaki program crash naa kare. Exception kisi bhi error situation ko refer karta hai jo program ki normal flow ko rokta hai.
Exception Hierarchy Overview
Java ke exceptions do prakar ke hote hain: Checked aur Unchecked (Runtime) exceptions.
java.lang.Throwable
├── java.lang.Error
└── java.lang.Exception
├── Checked Exceptions (Compile-time)
└── Runtime Exceptions (Unchecked)
Checked vs Unchecked Exceptions
Attribute | Checked Exceptions | Unchecked Exceptions |
---|---|---|
Handled at | Compile time | Runtime |
Examples | IOException, SQLException, ClassNotFoundException | ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException |
Mandatory handling | Yes (try-catch or throws) | No |
Try-Catch-Finally Example
public class ExceptionDemo {
public static void main(String[] args) {
try {
int a = 50 / 0; // ArithmeticException
System.out.println(a);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Throw & Throws Keywords
throw
keyword se manually exception throw kar sakte hain.
throws
keyword methods ki declaration me use hota hai taaki caller ko exception handle karna pade.
public void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Age must be at least 18");
}
}
Custom Exception Example
class MyException extends Exception {
MyException(String message) {
super(message);
}
}
public class TestCustomException {
public static void main(String[] args) {
try {
throw new MyException("Custom Exception Occurred!");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}