Java Topic

Java Regular Expressions

Regular expressions (regex) are patterns used to match character combinations in strings. Java provides support for regular expressions through the java.util.regex package, which includes the Pattern and Matcher classes.

1. Basic Syntax

Regular expressions use special characters to define search patterns. Here are some basic elements:

  • .: Matches any single character except newline.
  • ^: Matches the beginning of a line.
  • $: Matches the end of a line.
  • *: Matches zero or more occurrences of the preceding element.
  • +: Matches one or more occurrences of the preceding element.
  • ?: Matches zero or one occurrence of the preceding element.
  • [abc]: Matches any single character among the specified set (e.g., [a-z] matches any lowercase letter).
  • ( ): Groups expressions.
  • |: Acts as a logical OR.

2. Using Pattern and Matcher

The Pattern class represents a compiled regular expression, and the Matcher class performs matching operations on a character sequence:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        String text = "Hello, World!";
        String regex = "World";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        if (matcher.find()) {
            System.out.println("Match found: " + matcher.group());
        } else {
            System.out.println("No match found.");
        }
    }
}

This example demonstrates how to create a pattern and match it against a string.

3. Common Methods

Here are some commonly used methods in the Pattern and Matcher classes:

  • Pattern.compile(String regex): Compiles the given regular expression into a pattern.
  • Matcher.find(): Attempts to find the next subsequence of the input sequence that matches the pattern.
  • Matcher.group(): Returns the matched subsequence.
  • Matcher.replaceAll(String replacement): Replaces each subsequence of the input sequence that matches the pattern with the given replacement string.
public class RegexReplaceExample {
    public static void main(String[] args) {
        String text = "Hello, World! Hello, Universe!";
        String regex = "Hello";
        String replacement = "Hi";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        String result = matcher.replaceAll(replacement);
        System.out.println("Result: " + result);
    }
}

This example shows how to replace all occurrences of a pattern with a replacement string.

4. Matching Examples

Here are a few examples of regular expressions:

  • \d+: Matches one or more digits.
  • [A-Za-z]+: Matches one or more letters (both uppercase and lowercase).
  • \s+: Matches one or more whitespace characters.
public class RegexMatchExample {
    public static void main(String[] args) {
        String text = "123 abc 456 def";
        String regex = "\d+";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println("Found number: " + matcher.group());
        }
    }
}

This example demonstrates matching all digit sequences in a string.

Java Threads

In Java, a thread is a lightweight process that allows for concurrent execution of code. Threads are used to perform tasks in parallel, which can improve the performance of applications and enable multitasking.

1. Creating Threads

There are two main ways to create a thread in Java:

  • Extending the Thread class: You can create a new thread by extending the Thread class and overriding its run() method.
  • Implementing the Runnable interface: Alternatively, you can implement the Runnable interface and pass an instance of it to a Thread object.

Extending the Thread Class

public class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread running: " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

This example shows how to create a thread by extending the Thread class and overriding its run() method. The start() method begins the execution of the thread.

Implementing the Runnable Interface

public class MyRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Runnable running: " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

This example shows how to create a thread by implementing the Runnable interface and passing an instance of it to a Thread object.

2. Thread Lifecycle

A thread goes through several states during its lifecycle:

  • New: The thread is created but not yet started.
  • Runnable: The thread is ready to run and is waiting for CPU time.
  • Blocked: The thread is blocked waiting for a monitor lock.
  • Waiting: The thread is waiting indefinitely for another thread to perform a particular action.
  • Timed Waiting: The thread is waiting for a specified period.
  • Terminated: The thread has completed execution.

3. Thread Synchronization

When multiple threads access shared resources, you need to synchronize them to avoid conflicts and ensure data consistency. You can use the synchronized keyword to achieve this:

public class SynchronizedExample {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public static void main(String[] args) {
        SynchronizedExample example = new SynchronizedExample();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.increment();
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final count: " + example.count);
    }
}

This example demonstrates how to use the synchronized keyword to ensure that the increment() method is thread-safe.

4. Thread Communication

Threads can communicate with each other using methods such as wait(), notify(), and notifyAll(). These methods must be called from within a synchronized block:

public class ThreadCommunication {
    private boolean flag = false;

    public synchronized void produce() {
        while (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        flag = true;
        System.out.println("Produced");
        notify();
    }

    public synchronized void consume() {
        while (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        flag = false;
        System.out.println("Consumed");
        notify();
    }

    public static void main(String[] args) {
        ThreadCommunication communication = new ThreadCommunication();

        Thread producer = new Thread(() -> {
            communication.produce();
        });

        Thread consumer = new Thread(() -> {
            communication.consume();
        });

        producer.start();
        consumer.start();
    }
}

This example demonstrates basic thread communication using wait() and notify() methods.

 

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?