Sunday, 26 March 2023

Integrity constraints in SQL

Integrity constraints in SQL are rules that are applied to ensure the accuracy and consistency of the data stored in a database. There are four types of integrity constraints in SQL:

NOT NULL Constraint: This constraint ensures that a column cannot have a NULL value. For example, the following query creates a table with a NOT NULL constraint on the 'id' column:

Example:

CREATE TABLE employee (
   id INT NOT NULL,
   name VARCHAR(50),
   age INT
);
 

UNIQUE Constraint: This constraint ensures that a column or a group of columns have unique values in each row. For example, the following query creates a table with a UNIQUE constraint on the 'email' column:

Example:

CREATE TABLE customer (
   id INT,
   name VARCHAR(50),
   email VARCHAR(50) UNIQUE
);
 

PRIMARY KEY Constraint: This constraint ensures that a column or a group of columns uniquely identifies each row in a table. For example, the following query creates a table with a primary key on the 'id' column:

Example:

 CREATE TABLE product (
   id INT PRIMARY KEY,
   name VARCHAR(50),
   price DECIMAL(8,2)
);

FOREIGN KEY Constraint: This constraint ensures that the values in a column or a group of columns of one table match the values in a column or a group of columns of another table. For example, the following query creates two tables with a foreign key constraint on the 'category_id' column of the 'product' table:

Example:

CREATE TABLE category (
   id INT PRIMARY KEY,
   name VARCHAR(50)
);

CREATE TABLE product (
   id INT PRIMARY KEY,
   name VARCHAR(50),
   price DECIMAL(8,2),
   category_id INT,
   FOREIGN KEY (category_id) REFERENCES category(id)
);
 

The above query ensures that the 'category_id' column of the 'product' table matches the 'id' column of the 'category' table.

CHECK Constraint 

The SQL CHECK constraint is used to restrict the values that can be inserted into a column in a table. It allows you to specify a condition that must be satisfied for the data to be valid. If the condition is not met, an error is returned and the data is not inserted into the table.

The syntax for the CHECK constraint is as follows:

CREATE TABLE table_name (
    column1 datatype CHECK (condition),
    column2 datatype CHECK (condition),
    ...
);

Here, the CHECK keyword is followed by a condition in parentheses that specifies the allowable values for the column. The condition can use operators such as =, >, <, >=, <=, <>, BETWEEN, LIKE, IN, and IS NULL, as well as logical operators such as AND, OR, and NOT.

Let's look at an example. Suppose we have a table called employees with columns id, name, age, and salary. We want to ensure that the age column only accepts values between 18 and 65. We can add a CHECK constraint to the age column as follows:

CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    age INT CHECK (age BETWEEN 18 AND 65),
    salary DECIMAL(10,2)
);

Now, any attempt to insert a row into the employees table with an age value outside the range of 18 to 65 will fail with an error.

Note that the CHECK constraint can also be added to an existing table using the ALTER TABLE statement. For example, to add a CHECK constraint to the age column of the employees table, you can use the following statement:

ALTER TABLE employees
ADD CONSTRAINT age_check CHECK (age BETWEEN 18 AND 65);
 

DEFAULT Constraint

In SQL, the DEFAULT constraint is used to specify a default value for a column when no value is specified during an INSERT operation. The default value is automatically assigned to the column if a value is not provided.

The syntax for adding a DEFAULT constraint to a column when creating a table is as follows:

CREATE TABLE table_name (
    column1 datatype DEFAULT default_value,
    column2 datatype DEFAULT default_value,
    ...
);
 

Here, the DEFAULT keyword is followed by the default value to be assigned to the column if no value is specified during an INSERT operation.

Let's look at an example. Suppose we have a table called orders with columns order_id, customer_id, and order_date. We want to specify a default value of the current date for the order_date column when no value is provided. We can add a DEFAULT constraint to the order_date column as follows:

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    order_date DATE DEFAULT CURRENT_DATE
);

Now, any INSERT operation that does not provide a value for the order_date column will automatically use the current date as the default value.

Note that the DEFAULT constraint can also be added to an existing table using the ALTER TABLE statement. For example, to add a DEFAULT constraint to the order_date column of the orders table, you can use the following statement:

 ALTER TABLE orders
ALTER COLUMN order_date SET DEFAULT CURRENT_DATE;

These constraints help maintain data consistency and accuracy in a database.

Monday, 13 March 2023

String Tokenizer in java

 In Java, the StringTokenizer class is used to break a string into tokens (substrings) based on a specified delimiter. It is part of the java.util package and is widely used for parsing text data.

Here's an example of how to use StringTokenizer:

String Tokenizer Example program in java

import java.util.StringTokenizer;

public class StringTokenizerExample {
    public static void main(String[] args) {
        String input = "Hello, world! This is a test.";
        StringTokenizer tokenizer = new StringTokenizer(input, ",.! ");

        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            System.out.println(token);
        }
    }
}

In this example, the input string is "Hello, world! This is a test." The StringTokenizer object is created with the input string and the delimiters are specified as ,.! (comma, exclamation mark, period, and space). The hasMoreTokens() method is used to check if there are more tokens to be extracted, and the nextToken() method is used to extract the next token. The extracted token is then printed to the console.

The output of this program will be:

Hello
world
This
is
a
test
 

In this example, the delimiters are specified as a string of characters. However, it is also possible to specify the delimiters as individual characters using the StringTokenizer constructor that takes a second argument of type String or char.

It is important to note that StringTokenizer is a legacy class and has been largely replaced by the split() method of the String class introduced in Java 1.4. The split() method provides a more flexible way of splitting strings using regular expressions. However, StringTokenizer is still useful in situations where a simple delimiter-based approach is sufficient.

String split() Method in java

In Java, the split() method is used to split a string into substrings based on a specified delimiter. It is a method of the String class and is used extensively in text processing and data parsing.

Here's an example of how to use the split() method:

public class SplitExample {
    public static void main(String[] args) {
        String input = "Hello, world! This is a test.";
        String[] tokens = input.split("[,!. ]+");

        for (String token : tokens) {
            System.out.println(token);
        }
    }
}

In this example, the input string is "Hello, world! This is a test." The split() method is called with a regular expression pattern as the delimiter. The regular expression pattern [,.! ]+ specifies that the delimiter can be any combination of commas, exclamation marks, periods, and spaces. The + sign indicates that the delimiter can appear one or more times consecutively. The split() method returns an array of substrings (tokens) that are separated by the delimiter.

The output of this program will be:

Hello
world
This
is
a
test
 

It is important to note that the split() method returns an array of substrings, and that the delimiter is not included in the returned substrings. If the delimiter is not found in the input string, the split() method returns an array with a single element that contains the original string.

The split() method is a powerful tool for text processing and data parsing in Java. It provides a flexible way of splitting strings based on a wide range of delimiters and can be used in a variety of applications.

 split() method in java using regular expressions

In Java, the split() method can be used to split a string into substrings based on a regular expression pattern. Regular expressions are a powerful tool for pattern matching and can be used to specify complex patterns for splitting strings.

Here's an example of how to use the split() method with a regular expression:

public class SplitRegexExample {
    public static void main(String[] args) {
        String input = "John,Paul,George,Ringo";
        String[] tokens = input.split("[,]");

        for (String token : tokens) {
            System.out.println(token);
        }
    }
}



In this example, the input string is "John,Paul,George,Ringo". The split() method is called with the regular expression pattern [,], which specifies that the delimiter is a comma. The split() method returns an array of substrings that are separated by commas.

The output of this program will be:

 John
Paul
George
Ringo

Regular expressions can be used to specify complex patterns for splitting strings. For example, the following regular expression can be used to split a string based on any combination of commas, semicolons, and spaces:

String[] tokens = input.split("[,;\\s]+");
 

In this regular expression, the [] characters are used to specify a character class, which matches any one of the characters inside the class. The + sign indicates that the character class can appear one or more times consecutively. The \\s character class matches any whitespace character, including spaces, tabs, and newlines.

Regular expressions can be a bit tricky to use at first, but they are a powerful tool for text processing and data parsing in Java. They can be used to specify complex patterns for splitting strings, and can be customized to match almost any pattern you can imagine.

Inter thread communication in java

 Inter thread communication can be defined as the exchange of messages between two or more threads. The transfer of messages takes place before or after the change of state of a thread.

For example, an active thread may notify to another suspended thread just before switching to the suspended state. 

In Java, inter-thread communication can be achieved through the use of the wait(), notify() and notifyAll() methods. These methods are part of the Object class, which is the base class for all Java objects.

1. wait(): The wait() method is used to suspend the current thread and wait for a notification from another thread. The thread that calls the wait() method must own the object's monitor. If the thread does not own the monitor, an IllegalMonitorStateException is thrown.

    The object class deceleration of wait() method is  shown below 

                       final void wait()

2. notify(): The notify() method is used to wake up a single thread that is waiting on the object's monitor. The thread that calls the notify() method must own the object's monitor. If the thread does not own the monitor, an IllegalMonitorStateException is thrown.

 The object class deceleration of notify() method is  shown below                        

                                    final void notify()


3. notifyAll(): The notifyAll() method is used to wake up all threads that are waiting on the object's monitor. The thread that calls the notifyAll() method must own the object's monitor. If the thread does not own the monitor, an IllegalMonitorStateException is thrown.

The object class deceleration of notifyAll() method is  shown below                        

                                    final void notifyAll()

To use these methods for inter-thread communication, the following steps should be followed:

  1. Create a shared object between the threads
  2. Synchronize the methods that access the shared object
  3. Use wait(), notify(), and notifyAll() to signal between threads.

Here's an example of how inter-thread communication can be achieved in Java:

public class InterThreadCommunicationExample {
    public static void main(String[] args) {
        SharedObject sharedObject = new SharedObject();

        Thread thread1 = new Thread(() -> {
            synchronized (sharedObject) {
                try {
                    sharedObject.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 1 notified");
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (sharedObject) {
                System.out.println("Thread 2 sending notification");
                sharedObject.notify();
            }
        });

        thread1.start();
        thread2.start();
    }
}

class SharedObject {}

 In this example, the main method creates a shared object (SharedObject). Two threads are created - thread1 and thread2. Thread1 waits for a notification from thread2 by calling the wait() method on the shared object within a synchronized block. Thread2 sends the notification by calling the notify() method on the shared object within a synchronized block. When thread1 receives the notification, it prints "Thread 1 notified" to the console.

Find Us On Facebook

Computer Basics

More

C Programming

More

Java Tutorial

More

Data Structures

More

MS Office

More

Database Management

More
Top