A package in Java is a namespace (folder) that organizes related classes and interfaces into a hierarchical structure.
👉 It helps in:
Provided by Java
Examples:
java.lang → basic classes (String, Math)java.util → utilities (Scanner, ArrayList)java.io → input/outputCreated by programmer
package mypackage;
package mypackage;
public class Hello {
public void show() {
System.out.println("Hello from package");
}
}
Hello.javajavac -d . Hello.java
java mypackage.Hello
importimport mypackage.Hello;
OR
import mypackage.*;
import mypackage.Hello;
class Test {
public static void main(String[] args) {
Hello h = new Hello();
h.show();
}
}
| Modifier | Same Class | Same Package | Different Package |
|---|---|---|---|
| public | ✔ | ✔ | ✔ |
| protected | ✔ | ✔ | ✔ (via inheritance) |
| default | ✔ | ✔ | ✘ |
| private | ✔ | ✘ | ✘ |
📊 Package Structure Diagram:
An exception is an error or abnormal condition that occurs during program execution and disrupts normal flow.
👉 Example:
Examples:
IOExceptionSQLExceptionExamples:
ArithmeticExceptionNullPointerException| Keyword | Purpose |
|---|---|
try |
Code that may cause exception |
catch |
Handles exception |
finally |
Always executes |
throw |
Explicitly throw exception |
throws |
Declare exception |
try {
// risky code
} catch (Exception e) {
// handling code
} finally {
// always runs
}
public class Test {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Done");
}
}
}
10 / 0 → causes exceptioncatchfinally always executesthrowthrow new ArithmeticException("Error occurred");
throwsvoid readFile() throws IOException {
// code
}
try {
int a[] = new int[5];
a[10] = 30;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index Error");
}
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
finally blockcatch allowedfinally always executes (except system crash)📊 Exception Flow Diagram:
package and importtry, catch, finally, throw, throwsOpen this section to load past papers