✅ Chapter 9: Packages and Interfaces (Detailed Explanation)
📦 Packages in Java
Packages are a way of organizing classes into namespaces. Just like folders on your computer
help you organize files, Java packages group related classes together. This avoids class name
conflicts and improves modularity.
Why Use Packages?
Avoid naming collisions.
Control access with protection levels.
Organize related classes.
Defining a Package
You define a package at the top of a Java file:
java
CopyEdit
package mypackage;
public class MyClass {
// class content
}
When compiled, this class must be saved in a folder named mypackage.
🔍 CLASSPATH and Package Finding
Java needs to know where to find your packages. This is managed by the CLASSPATH
environment variable. If you try to run a program that uses classes from your package, and Java
can’t find it, you’ll get an error.
📌 Example of a Package
Let’s break this example into two files:
1. File in a Package
java
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if (bal < 0)
[Link]("--> ");
[Link](name + ": $" + bal);
}
}
2. File that Uses the Package
java
import [Link];
class TestBalance {
public static void main(String args[]) {
Balance test = new Balance("Ali", 100.0);
[Link]();
}
}
To compile:
bash
javac -d . [Link]
javac [Link]
🔐 Access Protection Levels
Modifier Access Level
public Accessible everywhere
protected Package + subclass access
No modifier Package-only access
Modifier Access Level
private Class-only access
🔌 Interfaces in Java
What is an Interface?
An interface is like a contract. It lists method declarations that classes must implement.
java
interface Animal {
void makeSound(); // no body
}
Implementing an Interface
java
class Dog implements Animal {
public void makeSound() {
[Link]("Bark");
}
}
Now, any Dog object will have the makeSound() method.
✨ Multiple Interface Implementation
java
interface A {
void method1();
}
interface B {
void method2();
}
class C implements A, B {
public void method1() {
[Link]("Method 1");
}
public void method2() {
[Link]("Method 2");
}
}
Unlike classes, interfaces support multiple inheritance — a class can implement more than one
interface.
📊 Interface Variables
All variables in interfaces are implicitly public, static, and final.
java
interface Example {
int x = 10; // treated as: public static final int x = 10;
}
🧬 Extending Interfaces
Interfaces can inherit from other interfaces.
java
interface A {
void meth1();
}
interface B extends A {
void meth2();
}
class MyClass implements B {
public void meth1() { [Link]("Method 1"); }
public void meth2() { [Link]("Method 2"); }
}
✅ Chapter 10: Exception Handling (Detailed Explanation)
🔍 What is an Exception?
An exception is a runtime error—an abnormal condition that disrupts the flow of a program.
Without exception handling:
You had to write manual error checks using if-else logic.
With Java:
Java provides an object-oriented way to handle errors gracefully using exception classes.
📌 Basic Terms:
Throwable: The superclass for all exceptions and errors.
Exception: The class used for exceptions that programs should catch.
Error: Used by JVM to indicate serious problems like memory errors (usually not
handled by user code).
🔤 Syntax of Exception Handling Block
java
try {
// code that may cause an exception
} catch (ExceptionType e) {
// handle exception
} finally {
// code that runs no matter what
}
⚠️Types of Exceptions
1. Checked Exceptions
Must be declared with throws or handled in try-catch.
IOException
ClassNotFoundException
2. Unchecked Exceptions (RuntimeException Subclasses)
Do not need to be declared or caught.
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
📌 Example: Uncaught Exception
java
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d; // ArithmeticException
}
}
Output:
csharp
[Link]: / by zero
at [Link]([Link])
✅ Handling with try-catch
java
class Exc2 {
public static void main(String args[]) {
try {
int d = 0;
int a = 42 / d;
} catch (ArithmeticException e) {
[Link]("Division by zero!");
}
}
}
🔁 Multiple catch blocks
You can catch multiple types of exceptions:
java
try {
int a = [Link];
int b = 42 / a;
int c[] = {1};
c[42] = 99;
} catch (ArithmeticException e) {
[Link]("Divide by 0: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error: " + e);
}
🧩 Nested try blocks
You can nest try-catch blocks:
java
try {
int a = [Link];
int b = 42 / a;
try {
int c[] = {1};
c[42] = 99;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error: " + e);
}
} catch (ArithmeticException e) {
[Link]("Divide by 0: " + e);
}
🎯 The throw keyword
Used to manually throw an exception.
java
throw new ArithmeticException("Demo");
📝 The throws clause
Used in method definitions to declare possible exceptions:
java
void myMethod() throws IOException {
// code that might throw IOException
}
🔄 finally Block
Always executes after try-catch, even if there's a return.
java
try {
[Link]("Inside try");
return;
} finally {
[Link]("Finally runs anyway");
}
🛠️Built-in Exceptions
Unchecked:
ArithmeticException – Division by zero
NullPointerException – Null reference access
ArrayIndexOutOfBoundsException
ClassCastException
Checked:
IOException
ClassNotFoundException
InterruptedException
💡 Creating Your Own Exception
java
class MyException extends Exception {
int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class Test {
static void compute(int a) throws MyException {
[Link]("Called compute(" + a + ")");
if (a > 10)
throw new MyException(a);
[Link]("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
[Link]("Caught " + e);
}
}
}
🔗 Chained Exceptions
Java lets you link exceptions to show the root cause:
java
NullPointerException e = new NullPointerException("Top layer");
[Link](new ArithmeticException("Cause"));
throw e;
Catch block:
java
catch (NullPointerException e) {
[Link]("Caught: " + e);
[Link]("Original cause: " + [Link]());
}
✅ Chapter 13: String Handling (Detailed Explanation)
📌 Overview of Strings in Java
In Java, strings are not just arrays of characters like in C/C++ — they are objects of the class
String.
A String is a sequence of characters.
Once a String object is created, it cannot be changed — it is immutable.
To create changeable strings, Java provides the StringBuffer and StringBuilder classes.
🔷 Creating String Objects
🧱 Using Constructors
java
String s1 = new String(); // empty string
String s2 = new String("Hello"); // from string literal
char chars[] = {'J', 'a', 'v', 'a'};
String s3 = new String(chars); // from char array
📏 String Length
Use .length() method to get the number of characters:
java
String s = "Hello";
[Link]([Link]()); // Output: 5
🧪 Special String Operations
🔡 String Literals
When you write:
java
String s = "Java";
Java creates a String object automatically.
➕ String Concatenation
You can join two strings using +:
java
CopyEdit
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + " " + s2;
Concatenation works with other data types too:
java
CopyEdit
int age = 25;
String text = "Age: " + age; // "Age: 25"
🔄 String Conversion and toString()
Any object can be converted to a string using .toString() method.
🔍 Character Extraction Methods
charAt(index)
Returns character at specified position.
java
CopyEdit
String s = "Java";
[Link]([Link](0)); // J
getChars(start, end, target[], targetPos)
Copies part of string into a char array.
🧵 String Comparison
✅ equals() and equalsIgnoreCase()
Compare content of strings:
java
CopyEdit
[Link](s2) // case-sensitive
[Link](s2) // ignores case
== vs equals()
== compares object references
equals() compares values
compareTo()
Used to compare alphabetically.
🔎 Searching in Strings
indexOf() and lastIndexOf()
Find the position of characters or substrings.
java
CopyEdit
String s = "Hello";
[Link]("l"); // returns 2 (first l)
[Link]("l"); // returns 3 (last l)
🛠️Modifying Strings
substring(start, end)
Returns a part of the string.
java
CopyEdit
String s = "Programming";
[Link]([Link](0, 4)); // "Prog"
concat(), replace(), trim()
java
CopyEdit
[Link](" Test");
[Link]("a", "x");
[Link](); // removes spaces from start and end
🔁 Changing Case
java
CopyEdit
[Link]();
[Link]();
🔄 Data Conversion
valueOf()
Convert any type to string:
java
CopyEdit
String s = [Link](123); // "123"
🔧 New String Methods in Java 2 v1.4
matches()
split()
join() (Java 8+)
🔁 StringBuffer and StringBuilder
These are mutable strings — you can change their contents.
✍️StringBuffer Example:
java
CopyEdit
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link](sb); // "Hello World"
🧪 Useful Methods:
Method Description
append() Add text
insert() Add at specific position
replace() Replace characters
delete() Delete characters
reverse() Reverse content
setCharAt(index, ch) Change character at index
✅ StringBuffer is thread-safe (synchronized), whereas StringBuilder is faster but not thread-
safe.
✅ Chapter 14: Exploring [Link]
🧠 What is [Link]?
It is automatically imported in every Java program.
It contains core classes and interfaces that you use every day.
You don’t need to write import [Link].*; — it's already available.
🔠 Classes in [Link] Package
Some key classes:
Class Purpose
Object The root of all classes
String To work with text
Class Purpose
Math To perform mathematical functions
Integer Wrapper for int type
Character Wrapper for char
System Interacts with system input/output
Thread For multithreading
Throwable For exception handling
Boolean, Byte, Short, Long, Float, Double Other wrappers for primitives
🧱 Wrapper Classes
Java has primitive data types like int, float, char, etc. But you cannot use primitives in
collections, so Java provides wrapper classes:
Primitive Wrapper Class
int Integer
char Character
boolean Boolean
... ...
Example:
java
CopyEdit
int a = 5;
Integer b = [Link](a); // Manual boxing
int c = [Link](); // Manual unboxing
With Java 5+, you can use autoboxing:
java
CopyEdit
Integer i = 10; // Auto-converted from int
int j = i; // Auto-unboxed
🔢 The Number Class and Subclasses
Number is an abstract class for numeric wrappers.
Its subclasses include Integer, Double, Float, Long, etc.
Each subclass provides methods like intValue(), doubleValue() to convert between types.
✏️Character Class
Character wraps a single character (char) and gives useful methods:
java
CopyEdit
char ch = 'A';
boolean isLetter = [Link](ch); // true
boolean isDigit = [Link](ch); // false
Other methods:
toUpperCase()
toLowerCase()
isWhitespace()
📘 Boolean Class
Used to wrap true or false values:
java
CopyEdit
Boolean b = [Link](true);
[Link]([Link]()); // true
🧮 Math Class
The Math class provides static methods for math operations:
java
CopyEdit
[Link](-10) // 10
[Link](2, 3) // 8
[Link](25) // 5.0
[Link](10, 20) // 20
[Link]() // 0.0 to 1.0
💬 System Class
Provides methods for input/output and exiting the program:
java
CopyEdit
[Link]("Hello");
[Link](0); // Exit program
[Link] – standard input (keyboard)
[Link] – standard output (console)
[Link] – standard error output
🧵 Thread Class
Used to run multiple tasks at the same time (multithreading):
java
CopyEdit
class MyThread extends Thread {
public void run() {
[Link]("Thread running");
}
}
MyThread t = new MyThread();
[Link]();
🧰 Throwable, Exception, Error
These are used for exception handling:
Throwable is the parent.
o Exception: problems you can handle (e.g., file not found).
o Error: serious problems (e.g., memory error).
🧩 Important Interfaces in [Link]
Interface Use
Runnable For running code in threads
Cloneable For creating copies of objects
Comparable For sorting and comparing objects
CharSequence Used by String and StringBuilder
🎯 Summary
The [Link] package is the foundation of Java programs. You use it every time you:
Create a string
Print to the console
Perform math
Use exceptions
Work with threads
Wrap primitive values as objects