0% found this document useful (0 votes)
2 views21 pages

Java Study Materials Regex

The document provides a comprehensive overview of Regular Expressions (Regex) in Java, detailing the java.util.regex package, including the Pattern and Matcher classes, and their respective methods. It covers exception handling in Java, describing various types of exceptions, error handling techniques, and common exception types. Additionally, it includes practical assignments to reinforce learning on regex and exception handling.

Uploaded by

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

Java Study Materials Regex

The document provides a comprehensive overview of Regular Expressions (Regex) in Java, detailing the java.util.regex package, including the Pattern and Matcher classes, and their respective methods. It covers exception handling in Java, describing various types of exceptions, error handling techniques, and common exception types. Additionally, it includes practical assignments to reinforce learning on regex and exception handling.

Uploaded by

galigururaj1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CONTENTS

Regex Introduction
Java
[Link] Package

Study Materials
Pattern Class Methods

Matcher Class Methods

Character Classes

Metacharacters & Quantifiers

MODULE 1 Regex in Java


PatternSyntaxException

MODULE 2 Exception Handling in Java


MatchResult Interface

─────────────────
Each module includes concept review, code examples & a 30-minute assignment

Errors & Exceptions

Checked & Unchecked

Exception Types (12)

try / catch / finally

Multi-catch & Nested try

30-Min Assignments (×2)


TOPICS COVERED

01 Java Regex Overview

02 [Link] Package

MODULE 01

03 Pattern Class Methods

Regex in Java
04 Matcher Class Methods

05 Character Classes

Pattern Matching, Character Classes & Quantifiers 06 Metacharacters

07 Quantifiers

08 PatternSyntaxException

09 MatchResult Interface

10 30-Min Assignment
What is Java Regex?

Regular Expression (Regex) is an API to define patterns for searching, validating, or manipulating strings. Introduced in Java 1.4 via the [Link] package.

🔍
Pattern Matching

Validation
🔄
Find & Replace

Match a string against a pattern — e.g. check if text contains the Validate formats such as email addresses, phone numbers, ZIP Search all occurrences of a pattern in text and replace them
word 'error'. codes, passwords. programmatically.

Key API: [Link] [Link] [Link] MatchResult (interface)


[Link] Package

The package contains 3 classes and 1 interface that work together to process regular expressions.

CLASS Pattern

Compiled representation of a regular expression. Use [Link](regex) to create an instance. Provides methods: matches(), compile(), matcher(), split(), pattern().

CLASS Matcher

Engine that performs match operations on character sequences by interpreting a Pattern. Provides: find(), start(), end(), group(), matches().

CLASS PatternSyntaxException

Thrown when a regex pattern string contains a syntax error. Extends IllegalArgumentException (unchecked).

INTERFACE MatchResult

Represents the result of a match operation. Contains query methods such as start(), end(), group() to inspect the result.
Pattern Class — Methods Overview

01 [Link](regex, input) returns: boolean

Compiles regex and tests if the entire input matches. Best for single-use checks. Returns true/false.

02 [Link](regex) returns: Pattern

Compiles regex into a reusable Pattern object. Use when matching the same pattern multiple times.

03 [Link](input) returns: Matcher

Creates a Matcher for the given input sequence against this compiled pattern.

04 [Link](input) returns: String[]

Splits input string around matches of this pattern. Returns an array of the split tokens.

05 [Link]() returns: String

Returns the regex string from which this Pattern was compiled (the source pattern string).
Pattern Class — Code Examples

[Link]() — single check [Link]() + [Link]()


[Link]() [Link]() + matcher()

String text = "This is the text to be searched"; String text = "Link: [Link]
String pattern = ".*is.*"; String str = ".*[Link]
boolean matches = [Link](pattern, text); Pattern pattern = [Link](str);
[Link]("matches = " + matches); Matcher matcher = [Link](text);
// Output: matches = true [Link]([Link]()); // true

[Link]() — tokenise by separator [Link]() — retrieve source regex


[Link]() [Link]()

String text = "Bond hi James hi Bond"; String patternString = "sep";


Pattern p = [Link]("hi"); Pattern pattern = [Link](patternString);
String[] split = [Link](text); String returned = [Link]();
[Link]([Link]); // 3 [Link](returned);
// tokens: "Bond ", " James ", " Bond" // Output: sep

💡 Tip: Use [Link]() for one-time checks. Use [Link]() when the same regex is needed multiple times — it avoids recompilation overhead.
Matcher Class — find(), start(), end()

The Matcher class searches through text for multiple occurrences of a pattern and retrieves positional info.

Matcher — find(), start(), end() in action


find() — public boolean find()
[Link]() + start() + end()

Finds the next subsequence matching the regex. Returns true if found. Starts
at index 0 by default. String regex = "ACA";
Pattern p = [Link](regex);
String s = "ACb AbR ACA";
Matcher m = [Link](s);
while ([Link]()) {
start() — public int start()
[Link]("start:" + [Link]() + " end:" + [Link]());
}
Returns the start index of the previous match. Throws IllegalStateException // Output: start:8 end:11
if no match has been found yet.

[Link]() — multiple matches


end() — public int end()
String regex = "F*F";
Pattern p = [Link](regex);
Returns the index AFTER the last character of the previous match — i.e., the String text = "FOFOFOFOF";
exclusive end position. Matcher m = [Link](text);
while ([Link]()) {
[Link]([Link]()); // 0,2,4,6,8
}
// * = zero or more of preceding char
Character Classes

A character class is a set of characters inside square brackets [ ]. The regex engine matches ONE character from that set against a single character in the input.

Class Description Example

[abc] Either 'a' or 'b' or 'c' [Link]("[abc]").matcher("Fake").find() → true (a present)

[^abc] Any char EXCEPT 'a', 'b', 'c' Negation — matches any single character not in the set

[a-z] Any lowercase letter a to z [Link]("app[a-z]e").matcher("apple").find() → true

[a-zA-Z] Any upper or lowercase letter Covers entire alphabet — case-insensitive character match

[0-9] Any digit from 0 to 9 [Link]("7[0-9]3").matcher("733").find() → true

[a-zA-Z0-9] Any alphanumeric character [Link]("Te[a-zA-Z0-9]nical").matcher("Te7nical").find() → true


Metacharacters & Quantifiers

Metacharacters have pre-defined meanings. Quantifiers specify how many times a character or group can appear.

METACHARACTERS QUANTIFIERS

\d Digit [0-9] X? Once or not at all

\D Non-digit X* Zero or more times

\s Whitespace character X+ One or more times

\S Non-whitespace X{n} Exactly n times

\w Word char [a-zA-Z0-9_] X{n,} At least n times

\W Non-word character X{n,m} From n to m times

Code Examples — Metacharacters & Quantifiers

[Link]("\\d").matcher("4").matches() → true (digit)


[Link]("\\D").matcher("k").matches() → true (non-digit)
[Link]("[abc]+").matcher("aabc").matches() → true (one-or-more)
[Link]("[abc]?").matcher("aabc").matches() → false (once or not-at-all; 'aabc' has >1)
PatternSyntaxException & MatchResult Interface

PatternSyntaxException MatchResult Interface

What is it? What is it?

Represents the result of a match operation. Implemented by Matcher. Query methods: start(), end(),
group(), groupCount().
Thrown when a regex pattern string has a syntax error. Extends IllegalArgumentException (unchecked
exception). Occurs at [Link]() time.
MatchResult — group() and end()

String regex = "Good";

❌ Invalid Pattern Examples Pattern p = [Link](regex);


MatchResult m = [Link]("Good works");
while (((Matcher)m).find()) {
// Throws PatternSyntaxException [Link]([Link]()); // Good
[Link]("+"); // '+' needs something before it [Link]([Link]()); // 4
}
// Also throws PatternSyntaxException
if ([Link]("\\", text)) { ... }
// single backslash is invalid regex MatchResult — group matching

String regex = "(G*ks)";


Pattern p = [Link](regex);
How to handle it MatchResult m = [Link]("Good works");
while (((Matcher)m).find()) {
[Link]([Link]()); // 10
Wrap [Link]() in try-catch. Check the getMessage() for description of the syntax error. }
⏱ 30-Min Complete the following tasks. Each section has a suggested time. Submit working Java code.

Assignment 10 min 10 min 10 min


Task 1 + 2 Task 3 Task 4
MODULE 01 — Regex in Java

5 min 10 min
01 03

Email Validator Word Frequency Counter

Write a Java program that uses [Link]() to validate whether a given string is a valid email address. Test with: Use [Link]() to count and print every occurrence of the word "the" (case-insensitive) in a given paragraph. Print
"user@[Link]" (valid), "user@.com" (invalid), "[Link]+tag@[Link]" (valid). the start index of each occurrence. Input text: "The quick brown fox. The fox jumped over the lazy dog and the fence."

Regex hint: ^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$ Hint: Use [Link]("the", Pattern.CASE_INSENSITIVE) and call [Link]() in a while(find()) loop.

5 min 10 min
02 04

Phone Number Validator CSV Parser using split()

Given the string: "Alice,30,Engineer,Bangalore,India" — use [Link]() to extract each field. Then validate: (a) age
Validate Indian mobile numbers (10 digits, starting with 6-9). Use [Link]() and Matcher. Test with:
field is exactly 2 digits using \\d{2}, (b) city starts with a capital letter using [A-Z][a-z]+. Print all fields and validation
"9876543210" (valid), "1234567890" (invalid), "98765" (invalid, too short).
results.

Regex hint: ^[6-9][0-9]{9}$ Hint: Split on comma pattern, then run separate [Link]() on the extracted tokens.
TOPICS COVERED

01 Errors in Java

02 Compile-Time & Run-Time Errors

MODULE 02
03 What are Exceptions?

Exception Handling
04 Checked vs Unchecked

05 12 Common Exception Types

in Java 06 ArithmeticException

07 NullPointerException & NumberFormat


Errors, Exception Types, try/catch/finally & Keywords
08 ClassCast & StringIndexOutOfBounds

09 IOException Family

10 try / catch / finally Keywords

11 Multi-catch & Nested try

12 30-Min Assignment
Errors in Java — Types & Overview

An error is anything that makes a program go wrong — producing incorrect output, terminating execution, or crashing.

COMPILE-TIME ERROR RUN-TIME ERROR

Occurs while the program is executing. Compilation succeeds but behaviour is incorrect or the
Detected by the Java compiler before the program runs. No .class file is produced.
program crashes.

Common examples: Common examples:

Missing semicolon (;) Dividing an integer by zero

Missing brackets in class/method Accessing array element out of bounds

Misspelling of identifiers or keywords Accessing string character out of bounds

Missing double quotes in strings Storing incompatible types in an array

Use of undeclared variables Using a negative size for an array


Exceptions — Checked vs Unchecked

An Exception is an abnormal condition at runtime. Java wraps it in an object (extends Throwable) and throws it.

Throwable

Error Exception

RuntimeException Checked Exceptions


(Unchecked) (IOException etc.)

CHECKED EXCEPTIONS UNCHECKED EXCEPTIONS

Must be declared with throws or handled with try-catch. Compiler enforces this. Examples: IOException, Extend RuntimeException. No throws declaration needed. Compiler does NOT enforce. Examples:
ClassNotFoundException, FileNotFoundException, InterruptedException. NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.

public void readFile() throws IOException { int result = 10 / 0;


// Must handle or declare // Compiles fine — throws at runtime!
} // ArithmeticException: / by zero
Common Exception Types — Quick Reference

Java provides many built-in exception classes. The table below covers the 12 most important ones in this module.

Exception Class Type Cause

ArithmeticException Unchecked Division by zero or invalid arithmetic

ArrayIndexOutOfBoundsException Unchecked Array index < 0 or ≥ array length

ClassNotFoundException Checked JVM cannot find a class at runtime ([Link])

FileNotFoundException Checked File at given path does not exist

IOException Checked General I/O failure (reading/writing files/network)

InterruptedException Checked Thread interrupted while in blocked/waiting state

NoSuchFieldException Checked Reflection: specified field not found in class

NoSuchMethodException Checked Reflection: specified method not found in class

NullPointerException Unchecked Calling method / field on a null reference

NumberFormatException Unchecked Parsing string to number fails (e.g. [Link])

ClassCastException Unchecked Illegal type cast between incompatible types

StringIndexOutOfBoundsException Unchecked String index < 0 or ≥ string length


ArithmeticException & NullPointerException

ArithmeticException (Unchecked) NullPointerException (Unchecked)

Cause Cause

Thrown when arithmetic operation fails — most commonly division by zero. Extends RuntimeException. Thrown when calling a method or accessing a field on a null reference. Most common Java runtime error.

ArithmeticException — Example NPE — Incorrect Code

int numerator = 10;


int denominator = 0;
try {
// ❌ Throws NullPointerException
String str = null;
int result = numerator / denominator;
int length = [Link]();
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
}
// Output: Error: / by zero
NPE — Correct Null Check

// ✅ Safe null check


String str = null;
Best Practice
if (str != null) {
int length = [Link]();
Always validate denominators before division. Check user input before arithmetic operations. } else { /* handle null case */ }

Best Practice
Always check if a reference is null before calling methods on it. Use Optional<T> in Java 8+.
NumberFormatException & ClassCastException &
StringIndexOutOfBoundsException
NumberFormatException ClassCastException StringIndexOutOfBoundsException

NumberFormatException ClassCastException StringIndexOutOfBoundsException


String str = "abc123";
try {
int num = [Link](str);
// ❌
Object obj = "Hello, World!";
Wrong — String is not Integer
Integer num = (Integer) obj;
// ❌
String text = "Hello, World!"; // length=13
Index 20 is out of range [0-12]
char ch = [Link](20);
// ✅ Correct — use instanceof
} catch (NumberFormatException e) {
// ✅ Bounds check first
[Link]("Invalid: " +
[Link]()); if (obj instanceof Integer) {
if (index >= 0 && index < [Link]())
} Integer n = (Integer) obj;
char ch = [Link](index);
// Always validate before parsing! }

IOException Family (Checked Exceptions) — always must be caught or declared

ClassNotFoundException FileNotFoundException

[Link]("X") — class not on classpath new FileReader(path) — file does not exist at path

IOException InterruptedException

[Link]() — general I/O failure [Link](ms) — another thread calls interrupt()

NoSuchFieldException NoSuchMethodException

[Link]("x") — field absent via reflection [Link]("f") — method absent via reflection
Exception Handling Keywords

Java provides 5 keywords for structured exception handling. Together they give complete control over error flows.

try catch finally throw throws

Always executes after try/catch, Manually throw an exception object: Declares that a method may throw
Wraps code that might throw an Catches a specific exception type
regardless of whether an exception throw new checked exceptions: public void m()
exception. Must be followed by at thrown by the try block. Multiple
was thrown. Used for cleanup (closing ArithmeticException("msg"). Used to throws IOException. Informs the
least one catch or finally block. catch blocks handle different types.
resources). signal custom errors. caller.
try-catch, Multi-catch & Nested try

try-catch Block Multi-catch Block


try-catch-finally Multi-catch — specific to general order

try {
try { int a[] = new int[5];
int a[] = new int[5]; a[5] = 30 / 0;
int result = a[0] / 0; // ArithmeticException } catch (ArithmeticException e) {
} catch (ArithmeticException e) { [Link]("Task 1 done");
[Link]("Arithmetic error: " + [Link]()); } catch (ArrayIndexOutOfBoundsException e) {
} finally { [Link]("Task 2 done");
[Link]("finally always runs"); } catch (Exception e) { // ← must be LAST
} [Link]("General");
}

Nested try Block ⚠ Key Rules to Remember


Nested try — inner exceptions handled locally
catch blocks must go specific → general. Placing Exception first causes a compile error.

try {
int a = 10 / 2; // outer try — OK finally always runs — even if return is called inside try/catch.
try {
int b = 10 / 0; // inner try — throws!
throw vs throws: throw creates and sends an exception object; throws declares it in the method
} catch (ArithmeticException e) {
signature.
[Link]("Inner catch: " + [Link]());
}
} catch (Exception e) { A try block MUST have at least one catch or finally.
[Link]("Outer catch");
}
// Output: Inner catch: / by zero
Multi-catch (Java 7+): catch (IOException | SQLException e) { } — catches multiple types in one block.
⏱ 30-Min Write complete Java programs for each task. Handle all exceptions explicitly — no uncaught exceptions allowed.

Assignment 8 min 7 min 8 min 7 min


Task 1 Task 2 Task 3 Task 4
MODULE 02 — Exception Handling

8 min 8 min
01 03

Safe Calculator Custom Age Exception

Write a SafeCalculator class with a divide(int a, int b) method. It must catch ArithmeticException and return 0 if Create a custom checked exception InvalidAgeException. Write a method validateAge(int age) that throws this
division by zero is attempted. Also catch NumberFormatException if non-numeric strings are passed via exception if age < 0 or age > 150. In main(), call the method with ages: -5, 25, 200. Catch the exception and print the
[Link](). Print a meaningful error message for each. age and reason.

Use try-catch with two separate catch blocks. Test: divide(10,2)=5, divide(10,0)=0 class InvalidAgeException extends Exception { } — declare it with throws in the method signature

7 min 7 min
02 04

Array Safe Access File Reader with Fallback

Write a program with an int array of 5 elements. Use a loop to try accessing indices 0 to 7. For each valid index, print Write a program that attempts to read from "[Link]". If FileNotFoundException is caught, create the file and write
the value. Catch ArrayIndexOutOfBoundsException for invalid indices and print "Index X is out of bounds." Use a "File created by fallback" to it. If any other IOException occurs, print the error. Use a finally block to close any open
finally block to print "Loop iteration complete" on every step. resources. Use multi-catch syntax (Java 7+) where appropriate.

Put the try-catch-finally inside the for loop body catch (FileNotFoundException e) creates the file. Use try-with-resources or finally to close streams.
What's Next?

─────────

Good Luck! Collections Framework

Review the concepts, attempt the assignments, and run every code example in your IDE. File I/O in Depth

Module 1 Regex in Java Module 2 Exception Handling in Java Multithreading

Generics

ICT Academy | Java Programming Series Lambda & Streams

JDBC & Databases

You might also like