Chapter 9
Chapter 9
📦 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.
Defining a Package
java
CopyEdit
package mypackage;
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
1. File in a Package
java
package MyPack;
java
import MyPack.Balance;
class TestBalance {
public static void main(String args[]) {
Balance test = new Balance("Ali", 100.0);
test.show();
}
}
To compile:
bash
javac -d . Balance.java
javac TestBalance.java
🔌 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() {
System.out.println("Bark");
}
}
java
interface A {
void method1();
}
interface B {
void method2();
}
class C implements A, B {
public void method1() {
System.out.println("Method 1");
}
public void method2() {
System.out.println("Method 2");
}
}
Unlike classes, interfaces support multiple inheritance — a class can implement more than one
interface.
📊 Interface Variables
java
interface Example {
int x = 10; // treated as: public static final int x = 10;
}
🧬 Extending Interfaces
java
interface A {
void meth1();
}
interface B extends A {
void meth2();
}
🔍 What is an Exception?
An exception is a runtime error—an abnormal condition that disrupts the flow of a program.
With Java:
Java provides an object-oriented way to handle errors gracefully using exception classes.
📌 Basic Terms:
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
IOException
ClassNotFoundException
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
java
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d; // ArithmeticException
}
}
Output:
csharp
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
java
class Exc2 {
public static void main(String args[]) {
try {
int d = 0;
int a = 42 / d;
} catch (ArithmeticException e) {
System.out.println("Division by zero!");
}
}
}
java
try {
int a = args.length;
int b = 42 / a;
try {
int c[] = {1};
c[42] = 99;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error: " + e);
}
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
java
throw new ArithmeticException("Demo");
🔄 finally Block
java
try {
System.out.println("Inside try");
return;
} finally {
System.out.println("Finally runs anyway");
}
🛠️Built-in Exceptions
Unchecked:
Checked:
IOException
ClassNotFoundException
InterruptedException
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 {
System.out.println("Called compute(" + a + ")");
if (a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
🔗 Chained Exceptions
java
NullPointerException e = new NullPointerException("Top layer");
e.initCause(new ArithmeticException("Cause"));
throw e;
Catch block:
java
catch (NullPointerException e) {
System.out.println("Caught: " + e);
System.out.println("Original cause: " + e.getCause());
}
✅ Chapter 13: String Handling (Detailed Explanation)
In Java, strings are not just arrays of characters like in C/C++ — they are objects of the class
String.
🧱 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
java
String s = "Hello";
System.out.println(s.length()); // Output: 5
🔡 String Literals
java
String s = "Java";
Java creates a String object automatically.
➕ String Concatenation
java
CopyEdit
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + " " + s2;
java
CopyEdit
int age = 25;
String text = "Age: " + age; // "Age: 25"
charAt(index)
java
CopyEdit
String s = "Java";
System.out.println(s.charAt(0)); // J
java
CopyEdit
s1.equals(s2) // case-sensitive
s1.equalsIgnoreCase(s2) // ignores case
== vs equals()
compareTo()
🔎 Searching in Strings
java
CopyEdit
String s = "Hello";
s.indexOf("l"); // returns 2 (first l)
s.lastIndexOf("l"); // returns 3 (last l)
🛠️Modifying Strings
substring(start, end)
java
CopyEdit
String s = "Programming";
System.out.println(s.substring(0, 4)); // "Prog"
concat(), replace(), trim()
java
CopyEdit
s.concat(" Test");
s.replace("a", "x");
s.trim(); // removes spaces from start and end
🔁 Changing Case
java
CopyEdit
s.toLowerCase();
s.toUpperCase();
🔄 Data Conversion
valueOf()
java
CopyEdit
String s = String.valueOf(123); // "123"
matches()
split()
join() (Java 8+)
✍️StringBuffer Example:
java
CopyEdit
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // "Hello World"
🧪 Useful Methods:
Method Description
🧠 What is java.lang?
Class Purpose
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:
int Integer
char Character
boolean Boolean
... ...
Example:
java
CopyEdit
int a = 5;
Integer b = Integer.valueOf(a); // Manual boxing
int c = b.intValue(); // Manual unboxing
java
CopyEdit
Integer i = 10; // Auto-converted from int
int j = i; // Auto-unboxed
🔢 The Number Class and Subclasses
Each subclass provides methods like intValue(), doubleValue() to convert between types.
✏️Character Class
java
CopyEdit
char ch = 'A';
boolean isLetter = Character.isLetter(ch); // true
boolean isDigit = Character.isDigit(ch); // false
Other methods:
toUpperCase()
toLowerCase()
isWhitespace()
📘 Boolean Class
java
CopyEdit
Boolean b = Boolean.valueOf(true);
System.out.println(b.booleanValue()); // true
🧮 Math Class
java
CopyEdit
Math.abs(-10) // 10
Math.pow(2, 3) // 8
Math.sqrt(25) // 5.0
Math.max(10, 20) // 20
Math.random() // 0.0 to 1.0
💬 System Class
java
CopyEdit
System.out.println("Hello");
System.exit(0); // Exit program
🧵 Thread Class
java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
Interface Use
🎯 Summary
The java.lang 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