0% found this document useful (0 votes)
3 views18 pages

Chapter 9

The document provides a detailed explanation of Java packages, interfaces, and exception handling, emphasizing their roles in organizing code, defining contracts for classes, and managing runtime errors. It covers the structure and usage of packages, the implementation of interfaces, and the syntax and types of exceptions, along with examples. Additionally, it discusses string handling and the core classes in the java.lang package, which are essential for Java programming.

Uploaded by

rabbiakhanzadii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

Chapter 9

The document provides a detailed explanation of Java packages, interfaces, and exception handling, emphasizing their roles in organizing code, defining contracts for classes, and managing runtime errors. It covers the structure and usage of packages, the implementation of interfaces, and the syntax and types of exceptions, along with examples. Additionally, it discusses string handling and the core classes in the java.lang package, which are essential for Java programming.

Uploaded by

rabbiakhanzadii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

✅ 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)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}

2. File that Uses the Package

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

🔐 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() {
System.out.println("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() {
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

 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() { System.out.println("Method 1"); }
public void meth2() { System.out.println("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
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)

✅ Handling with try-catch

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!");
}
}
}

🔁 Multiple catch blocks

You can catch multiple types of exceptions:


java
try {
int a = args.length;
int b = 42 / a;
int c[] = {1};
c[42] = 99;
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error: " + e);
}

🧩 Nested try blocks

You can nest try-catch blocks:

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);
}

🎯 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 {
System.out.println("Inside try");
return;
} finally {
System.out.println("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 {
System.out.println("Called compute(" + a + ")");
if (a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}

public static void main(String args[]) {


try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

🔗 Chained Exceptions

Java lets you link exceptions to show the root cause:

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)

📌 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";
System.out.println(s.length()); // 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";
System.out.println(s.charAt(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
s1.equals(s2) // case-sensitive
s1.equalsIgnoreCase(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";
s.indexOf("l"); // returns 2 (first l)
s.lastIndexOf("l"); // returns 3 (last l)

🛠️Modifying Strings

substring(start, end)

Returns a part of the string.

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()

Convert any type to string:

java
CopyEdit
String s = String.valueOf(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");
sb.append(" World");
System.out.println(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 java.lang

🧠 What is java.lang?

 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 java.lang.*; — it's already available.

🔠 Classes in java.lang 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 = Integer.valueOf(a); // Manual boxing
int c = b.intValue(); // 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 = Character.isLetter(ch); // true
boolean isDigit = Character.isDigit(ch); // false

Other methods:

 toUpperCase()
 toLowerCase()
 isWhitespace()

📘 Boolean Class

Used to wrap true or false values:

java
CopyEdit
Boolean b = Boolean.valueOf(true);
System.out.println(b.booleanValue()); // true

🧮 Math Class

The Math class provides static methods for math operations:

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

Provides methods for input/output and exiting the program:

java
CopyEdit
System.out.println("Hello");
System.exit(0); // Exit program

 System.in – standard input (keyboard)


 System.out – standard output (console)
 System.err – standard error output

🧵 Thread Class

Used to run multiple tasks at the same time (multithreading):

java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}

MyThread t = new MyThread();


t.start();

🧰 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 java.lang

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 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

You might also like