MySQL: Remove characters from string

In this article we are going to discuss how to remove characters from string in MySQL table.

MySQL: Remove characters from string

Here we are going to discuss three methods to remove characters from a database table in MySQL

Lets first make a database table in MySql,

CREATE TABLE student_data (
student_id INT,
student_name VARCHAR(50),
enroll_date DATE,
student_roll_no BIGINT,
fee_submitted DECIMAL(10,2)
);

Insert values in student_data,

INSERT INTO student__data(student_id,student_name,enroll_date,student_roll_no,fee_submitted) 
VALUES(1,"DShr-tht-ee,",'2020-12-02',1147483782,12378.90),
(2,"SShy-tht-am,",'2020-10-03',1147483788,14578.90),
(3,"RRi-tht-iky,",'2020-11-13',1147483789,22378.90),
(4,"JAb-tht-ir," ,'2020-12-04',1147483790,12378.90),
(5,"AAust-tht-gya,",'2020-11-12',1147483791,12378.90),
(6,"GPi-tht-hu,",'2020-10-10',1147483792,12788.90),
(7,"VPar-tht-nica,",'2020-02-14',1147483793,12378.90);

Output:

Remove chara from string in sql

Remove characters from string using REPLACE()

Here we are going to remove unwanted character from string using REPLACE() function.

Syntax:

UPDATE tableName SET columnName = REPLACE(columnName, 'charactersToBeReplaced', 
'charactersToBeReplacedWith');

Explanation:

tableName- Name of the given table

columnName: Column name whose value has to chnage

charactersToBeReplaced:Characters which we want to replaced

charactersToBeReplacedWith:New characters which we want to put instead of replaced one

Now we are going to remove “tht” from our string in column “student_name”,

UPDATE student_enroll_data SET student_name = REPLACE(student_name, '-tht-', '');

In above code you can see that we have given “-tht-” in place of characterToBeReplaced,which replaced the character and give us below output.

Output:

Remove char from string2

Remove characters from string using TRIM()

Here we are going to remove unwanted character from string using TRIM() function.TRIM() function are very helpful in removing char from string.It deletes special characters  or any characters given in start or end of table,

Syntax:

UPDATE tableName SET columnName = TRIM([{BOTH | LEADING | TRAILING} [charactersToBeRemoved] FROM ] columnName);

Explanation:

tableName- Name of the given table

columnName: Column name whose value has to chnage

charactersToBeRemoved:Characters which we want to replaced

BOTH,:When we want to remove char from start and end.

LEADING: Remove character from starting.

TRAILING: Remove characters from the end.

Now we are going to remove character ‘,’  from end for this will use below query;

UPDATE student_enroll_data SET student_name = TRIM(TRAILING ',' FROM student_name);

Output:

Remove char from string3png

So you can see that all “,” removed from end in Table student__data.

Remove characters from string using SUBSTRING()

Here we are going to remove unwanted character from string using SUBSTRING() function.It will remove substring from table in MySql.

Syntax:

UPDATE tableName SET columnName = SUBSTRING(columnName,pos);

Explanation:

tableName- Name of the given table

columnName: Column name whose value has to chnage

pos:position from where the substring will start.

Here I am going to remove first character of column “student_name”,

UPDATE student_enroll_data SET student_name = SUBSTRING(student_name,2);

Output:

Remove char from string4
Conclusion:

In this article we have discussed how to remove characters from string in MySQL table.Thank You!

Java Program to Insert an Element in Array at Given Position

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Java Program to Insert an Element in Array at Given Position

  • Write a java program to insert an element in array at any given index using for loop.

In this java program, given an array of N elements, we have to insert an element at index i (0 <= i <= N-1) without using extra memory space. After insertion, the number of elements in array will increase by one. To insert an element at index i in array we have to shift all elements from index i to N-1 to next index.

For Example,
Input Array : [2 5 3 4 6 1 7]
Inserting 9 at index 4
Output Array : [2 5 3 4 9 6 1 7]
Algorithm to insert an element in an array
Let inputArray is an integer array of length N, which contains M (M<N) elements and S is the element that we want to insert at index I.

  • Move all elements between index I to M-1 to next index(including index I and M-1).
  • Move inputArray[j] to inputArray[j + 1], I <= j <= M-1.
  • Insert S at inputArray[I].
  • Now, inputArray contains M+1 elements from index 0 to M.

Time Complexity : O(n)

Java program to insert an element in array at given index

In this java program, we first take number of elements in array as input fro user and store it in variable “count”. Then we ask user to enter “count” numbers and store it in integer array “input”. Then we ask user to enter number to be inserted(num) and at what position(index). By implementing above mentioned algorithm we insert “num” at “index” and print the array on screen using a for loop.
Java program to insert an element in array at given index

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to insert an element in array
 */
public class InsertArrayElement {
 
    public static void main(String[] args) {
        int count, i, num, index;
        int input[] = new int[100];
 
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Number of Elements in Array");
        count = scanner.nextInt();
 
        /*
         * Take array input from user
         */
        System.out.println("Enter " + count + " Numbers");
        for (i = 0; i < count; i++) {
            input[i] = scanner.nextInt();
        }
 
        System.out.println("Enter Number to be Inserted");
        num = scanner.nextInt();
        System.out.println("Enter Index of Insertion");
        index = scanner.nextInt();
 
        /*
         * Insert "num" at index. First shift all element right of index by one
         * position
         */
        for (i = count; i > index; i--) {
            input[i] = input[i - 1];
        }
        // inserting num at position "index"
        input[index] = num;
        // increment size of array
        count++;
 
        System.out.println("Final Array");
        for (i = 0; i < count; i++) {
            System.out.print(input[i] + " ");
        }
    }
}

Output

Enter Number of Elements in Array
7
Enter 7 Numbers
1 2 3 4 5 6 7
Enter Number to be Inserted
9
Enter Index of Insertion
4
Final Array
1 2 3 4 9 5 6 7

Python Program to Set nth Bit of a Number

Program to Set nth Bit of a Number

In the previous article, we have discussed Python Program to Get nth Bit of a Number

Given a number and the bit position, the task is to set the nth bit of the given Number.

For example:

Let the number = 5

Bit position=1

To set the 1st-bit position(0 indexing):

Its binary form = 101

When we set the 0 at the 1st index becomes 1 that is 111 which is equal to the number 7.

Bitwise or (|) operator:

If one of two bits is 1, sets each bit to 1.

Examples:

Example1:

Input:

Given Number = 5 
Bit position(in range 0-31)= 1

Output:

The given number { 5 } after set the { 1 } bit position =  7

Example2:

Input:

Given Number = 8
Bit position(in range 0-31)= 2

Output:

The given number { 8 } after set the { 2 } bit position = 12

Program to Set nth Bit of a Number in Python

Below are the ways to set the nth bit of the given Number in Python:

Method #1: Using Bitwise |(or) Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the bit position as static input and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply bitwise | operation for the given number and the above result and store it in another variable say set_numb
  • Print the given number after set the nth bit of the given Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 5
# Give the bit position as static input and store it in another variable.
bitpositin = 1
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply bitwise | operation for the given number and the above result and
# store it in another variable say set_numb.
set_numb = gvn_numb | numbr_bit
# Print the given number after set the nth bit of the given Number.
print("The given number {", gvn_numb,
      "} after set the {", bitpositin, "} bit position = ", set_numb)

Output:

The given number { 5 } after set the { 1 } bit position =  7

Method #2: Using Bitwise |(or) Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the bit position as user input using the int(input()) function and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply bitwise | operation for the given number and the above result and store it in another variable say set_numb
  • Print the given number after set the nth bit of the given Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and 
# store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Give the bit position as user input using the int(input()) function and 
# store it in another variable.
bitpositin = int(input("Enter some random number = "))
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply bitwise | operation for the given number and the above result and
# store it in another variable say set_numb.
set_numb = gvn_numb | numbr_bit
# Print the given number after set the nth bit of the given Number.
print("The given number {", gvn_numb,
      "} after set the {", bitpositin, "} bit position = ", set_numb)

Output:

Enter some random number = 8
Enter some random number = 2
The given number { 8 } after set the { 2 } bit position = 12

Practice Python Program Examples to master coding skills and learn the fundamental concepts in the dynamic programming language Python.

C++ : How to Sort a List of Objects with Custom Comparator or Lambda Function

In the previous article, we have discussed about Different ways to Initialize a list in C++. Let us learn how to Sort a List of Objects with Custom Comparator or Lambda Function in C++ Program.

Sorting a List of Objects with Custom Comparator or Lambda Function

In this article, we will learn different ways of sorting a std::list of user defined data types with custom comparators and lambda function.

Let we have a Student type that contains roll and name.

struct Student

{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

This student type has < operator which compares two student using < on roll field. Now, let’s create list of Student Objects,

std::list<Student> list_Students = { Student(15, "Aditya"),

                                    Student(6, "Sujeet"),

                                    Student(41, "Arhan"),

                                    Student(28, "Dipti"),

                                    Student(3, "Tamanna"),};

Now, let’s sort list of Students using std::list::sort.

std::list::sort

 It has two different overloaded versions i.e.

void std::list::sort(); 
// Will use default sorting criteria and will compare using < operator
template <class Compare>
void sort (Compare comparator);
//Accepts compare function or function object and using comparator it will sort

Sorting a List with Default Criteria :

We can sort a list with default criteria i.e. < operator of type which doesn’t accept any arguments. i.e. list_Students.sort();.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    // List being sorted by default criteria
    list_Students.sort();
    std::cout<<"After sorting students based on roll : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on roll :

3 :: Tamanna

6 :: Sujeet

15 :: Aditya

28 :: Dipti

41 :: Arhan

Sorting a List of Objects with Custom Comparator & Function Object :

There is another overloaded version of std::list::sort which accepts function pointer as an argument and compare while implementing sorting i.e.

template <class Compare>

void sort (Compare studcomp);

Then we will define a function object or comparator which will compare student list based on their names.

struct StudentComp

{

// Compares 2 Students objects according to their names

bool operator ()(const Student & stud1, const Student & stud2)

{

if(stud1.name == stud2.name)

return stud1 < stud2;

return stud1.name < stud2.name;

}

};


Now the above function will try to sort the list using the names by using list_Students.sort(StudentComp());

Complete program :

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

struct StudentComp
{
// Compares 2 student objects based on their names
    bool operator ()(const Student & stud1, const Student & stud2)
    {
        if(stud1.name == stud2.name)
            return stud1 < stud2;
        return stud1.name < stud2.name;
    }
};


int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    list_Students.sort(StudentComp());
    std::cout<<"After sorting students based on name : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on name :

15 :: Aditya

41 :: Arhan

28 :: Dipti

6 :: Sujeet

3 :: Tamanna

Sorting a List of Objects with Custom Comparator & Lambda Function :

Instead of defining a separate Function object we can sort the list of students by using Lambda function by passing lambda function in sort() as argument.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

struct StudentComp
{
// Compares 2 student objects based on their names
    bool operator ()(const Student & stud1, const Student & stud2)
    {
        if(stud1.name == stud2.name)
            return stud1 < stud2;
        return stud1.name < stud2.name;
    }
};


int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    // Sort student list using Lambda function
    list_Students.sort([](const Student & stud1, const Student & stud2)
        {
            if(stud1.name == stud2.name)
                return stud1 < stud2;
            return stud1.name < stud2.name;
        });
    std::cout<<"After sorting students based on name : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on name :

15 :: Aditya

41 :: Arhan

28 :: Dipti

6 :: Sujeet

3 :: Tamanna

Computer Science Questions and Answers

Computer Science Quiz Questions and Answers PDF Download

Discrete and Engineering Mathematics

Theory of Computation

  • Finite Automata: Regular Languages Questions and Answers
  • Push Down Automata: CFL & DCFL Questions and Answers
  • Turing Machine: RE, REC and Undecidability Questions and Answers

Digital Logic

  • Logic Functions and Minimization Questions and Answers
  • Combinational Circuits Questions and Answers
  • Sequential Circuits Questions and Answers
  • Number Systems Questions and Answers

Computer Organization & Architecture

  • CPU Architecture and Addressing Modes
  • Control Unit Design
  • Instruction Pipelining
  • Memory Organization
  • IO Organization

Programming and Data Structures

  • Programming Questions and Answers
  • Arrays Questions and Answers
  • Stacks and Queues Questions and Answers
  • Linked List Questions and Answers
  • Trees Questions and Answers
  • Graphs Questions and Answers
  • Hashing Questions and Answers

Algorithms

  • Algorithm Analysis and Asymptotic Notations Questions and Answers
  • Divide and Conquer Questions and Answers
  • Greedy Method Questions and Answers
  • Dynamic Programming Questions and Answers
  • P and NP Concepts Questions and Answers
  • Algorithms Questions and Answers

Compiler Design

  • Lexical Analysis Questions and Answers
  • Parsing Techniques Questions and Answers
  • Syntax Directed Translation Questions and Answers
  • Code Generation and Optimization Questions and Answers

Operating System

  • Operating System, Process, Threads & CPU Scheduling Questions and Answers
  • IPC, Synchronization and Concurrency Questions and Answers
  • Deadlock Questions and Answers
  • Memory Management and Virtual Memory Questions and Answers
  • File System and Device Management Questions and Answers
  • Operating System Miscellaneous Questions and Answers

Databases

  • ER-Model Questions and Answers
  • Database Design: Functional Dependencies and Normalization Questions and Answers
  • Structured Query Language SQL Questions and Answers
  • Relational Model: Relational Algebra and Tuple Calculus
  • Transactions and Concurrency Control
  • File Structures

Computer Networks

  • ISO/OSI Stack and SWP Questions and Answers
  • LAN Questions and Answers
  • TCP, UDP, and IP Questions and Answers
  • Routing and Application Layer Questions and Answers

General Aptitude

  • General Aptitude Questions and Answers

C Program to Draw a Circle Using C Graphics

C Program to Draw a Circle Using C Graphics

Write a program in C to draw a circle on screen using graphics.h header file
In this program, we will draw a circle on screen having centre at mid of the screen and radius of 80 pixels. We will use outtextxy and circle functions of graphics.h header file. Below is the detailed descriptions of graphics functions used in this program.

Function Description
initgraph It initializes the graphics system by loading the passed graphics driver then changing the system into graphics mode.
getmaxx It returns the maximum X coordinate in current graphics mode and driver.
getmaxy It returns the maximum Y coordinate in current graphics mode and driver.
outtextxy It displays a string at a particular point (x,y) on screen.
circle It draws a circle with radius r and centre at (x, y).
closegraph It unloads the graphics drivers and sets the screen back to text mode.

C program to draw circle using c graphics

In this program we first initialize graphics mode, by passing graphics driver(DETECT), default graphics mode and specifies the directory path where initgraph looks for graphics drivers (*.BGI). It is the first step you need to do during graphics programming. Setting graphics driver as DETECT, means instructing the compiler to auto detect graphics driver. Here we are using getmaxx and getmaxy function to find the center coordinate of the screen.

C Program to Draw a Circle Using C Graphics

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
 
int main(){
   int gd = DETECT,gm;
   int x ,y ,radius=80;
   initgraph(&gd, &gm, "C:\\TC\\BGI");
   /* Initialize center of circle with center of screen */
   x = getmaxx()/2;
   y = getmaxy()/2;
 
   outtextxy(x-100, 50, "CIRCLE Using Graphics in C");
   /* Draw circle on screen */
   circle(x, y, radius);
 
   getch();
   closegraph();
   return 0;
}

Program Output

Circle

C Program for Bouncing Ball Animation Using C Graphics

Write a program in C for bouncing ball animation using graphics.h header file
In this program, we will draw a red color ball move it vertically up and down like a bouncing ball. We will use below mentioned functions in this program.

Function Description
initgraph It initializes the graphics system by loading the passed graphics driver then changing the system into graphics mode.
getmaxx It returns the maximum X coordinate in current graphics mode and driver.
setcolor It changes the current drawing colour. Default colour is white. Each color is assigned a number, like BLACK is 0 and RED is 4. Here we are using colour constants defined inside graphics.h header file.
setfillstyle It sets the current fill pattern and fill color.
circle It draws a circle with radius r and centre at (x, y).
floodfill It is used to fill a closed area with current fill pattern and fill color. It takes any point inside closed area and color of the boundary as input.
cleardevice It clears the screen, and sets current position to (0, 0).
kbhit It is used to determine whether a key is pressed or not. It returns a non-zero value if a key is pressed otherwise zero.
delay It is used to suspend execution of a program for a M milliseconds.
closegraph It unloads the graphics drivers and sets the screen back to text mode.

C program for bouncing ball graphics animation

In this program, we first draw a red color ball on screen having center at (x, y) and then erases it using cleardevice function. We again draw this ball at center (x, y + 5), or (x, y – 5) depending upon whether ball is moving down or up. This will look like a bouncing ball. We will repeat above steps until user press any key on keyboard.

C Program for Bouncing Ball Animation Using C Graphics

#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <dos.h>
 
int main() {
 int gd = DETECT, gm;
 int i, x, y, flag=0;
 initgraph(&gd, &gm, "C:\\TC\\BGI");
 
 /* get mid positions in x and y-axis */
 x = getmaxx()/2;
 y = 30;
 
 
 while (!kbhit()) {
  if(y >= getmaxy()-30 || y <= 30)
     flag = !flag;
     /* draws the gray board */
     setcolor(RED);
     setfillstyle(SOLID_FILL, RED);
     circle(x, y, 30);
     floodfill(x, y, RED);
 
 /* delay for 50 milli seconds */
 delay(50);
 
 /* clears screen */
 cleardevice();
 if(flag){
     y = y + 5;
 } else {
     y = y - 5;
 }
    }
 
    getch();
    closegraph();
    return 0;
}

Program Output
Here is the screenshot of bouncing ball.

BOUNCING_BALL

Prototype Design Pattern

Prototype Design Pattern

The Prototype Design Pattern is used for cloning an existing object, if the cost of creating a new object of a class is complicated and resource expensive.

Here, we do not have to repeat the complex object building process to get new object of a class. This design pattern comes under creational design pattern as it provides one of the best ways to create clone of complex objects.

Advantages of Prototype Pattern

  • It hides the complexities of making new instance of a class from client.
  • Client specifies the kind of object it requires using a prototypical instance. Client is unaware of the type of object it will get.
  • It improves the performance of the system. If the cost of creating a new instance is more because of resource intensive operations(like running a database query), it is better to clone an existing prototype object.
  • One instance of a class is used to produce all future instances.

When we should use Prototype pattern

  • When the logic of creating a new object is complex and it requires resource extensive operations to be performed.
  • When we want to hide the logic of object creation and its representation from client.
  • When the classes to instantiate are specified at run-time.
  • When objects of a class can have only few different state(lets say N). It is more convenient to first create N prototype object of different states and clone them later when we need objects of different states.

Implementation of Prototype Design Pattern

We will create an abstract class Bird and it’s concrete implementation Parrot.java, Sparrow.java and Eagle.java. Each concrete implementation of Bird class will override cloneObject method.

Prototype_Pattern

Prototype Design Pattern

Bird.java
public abstract class Bird implements Cloneable  {
    protected String name;
  
    public String getName() {
        return name;
    }
     
    public void setName(String name) {
        this.name = name;
    }
  
    public abstract Bird cloneObject() throws CloneNotSupportedException;
}

Prototype Design Pattern 1

Parrot.java
public class Parrot extends Bird {
  
    public Parrot() {
        name = PrototypeFactory.PARROT;
    }
  
    @Override
    public Bird cloneObject() throws CloneNotSupportedException {
        System.out.println("Cloning a Parrot object");
        return (Bird) super.clone();
    }
}
Eagle.java
public class Eagle extends Bird {
  
    public Eagle() {
        name = PrototypeFactory.EAGLE;
    }
  
    @Override
    public Bird cloneObject() throws CloneNotSupportedException {
        System.out.println("Cloning an Eagle object");
        return (Bird) super.clone();
    }
}
Sparrow.java
public class Sparrow extends Bird {
  
    public Sparrow() {
        name = PrototypeFactory.SPARROW;
    }
  
    @Override
    public Bird cloneObject() throws CloneNotSupportedException {
        System.out.println("Cloning a Sparrow object");
        return (Bird) super.clone();
    }
}

PrototypeFactory class will create prototype instances of Parrot, Sparrow and Eagle stores then in a HashMap. The getBirdInstance method first get the prototype instance of requested bird object from HashMap and the returns a copy of it.

Prototype Design Pattern 2

import java.util.Map;
import java.util.HashMap;
 
public class PrototypeFactory {
    public static final String PARROT = "Parrot";
    public static final String SPARROW = "Sparrow";
    public static final String EAGLE = "Eagle";
 
    private Map<String, Bird> prototypeList = new HashMap<String, Bird>();
     
    public void initialize() {   
     prototypeList.put(PrototypeFactory.PARROT, new Parrot());
     prototypeList.put(PrototypeFactory.SPARROW, new Sparrow());
     prototypeList.put(PrototypeFactory.EAGLE, new Eagle());
    }
  
    public Bird getBirdInstance(String name) throws CloneNotSupportedException {
        return (Bird)prototypeList.get(name).cloneObject();
    }
}

PrototypePatternExample class uses PrototypeFactory object to create object of Parrot, Sparrow and Eagle classes.

public class PrototypePatternExample {
    public static void main(String[] args) {
        PrototypeFactory factory = new PrototypeFactory();
        factory.initialize();
        try {
            factory.getBirdInstance(PrototypeFactory.PARROT);
            factory.getBirdInstance(PrototypeFactory.SPARROW);
            factory.getBirdInstance(PrototypeFactory.EAGLE);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

Output

Cloning a Parrot object
Cloning a Sparrow object
Cloning an Eagle object

Adapter Design Pattern

The Adapter Pattern Convert the interface of a class into another interface clients expect. It enables a client with incompatible interface to interact with existing class using an intermediate Adapter class. An Adapter class acts like a middle man through which two classes having incompatible interfaces can interact with each other. It comes under structural design pattern as it facilitates communication between two interfaces.

Advantages of Adapter Pattern

  • Two classes having incompatible interfaces can interact with each other using an Adapter class.
  • It promotes reusability of existing system. A class can be accessed by multiple systems using different interfaces and Adapters.

When we should use Adapter pattern

  • When client wants to interact with existing system using incompatible interface.
  • When a new system wants to interact with legacy(old) system using new interface which is not compatible with interface of legacy system.
  • When you want to use a 3rd party framework or library whose interface is incompatible with your system.

Components of Adapter Pattern

  • Target Interface : This is the interface expected by the client.
  • Adapter : This is a wrapper over Adaptee class which implements the Target Interface. It receives calls from the client and translates that request to one/multiple adaptee calls using Adaptee interface.
  • Adaptee Interface : This is the existing interface which is wrapped by Adapter. Client wants to interact with Adaptee but cannot interact directly because Adaptee Interface is incompatible with Target Interface.
  • Client : Client will interact with Adapter using Target Interface.
    1. Client calls Adapter using using Target Interface.
    2. Adapter class translates this request and delegates it to adaptee using one/multiple method calls using Adaptee Interface.
    3. Adaptee returns response to Adapter class as defined in Adaptee Interface and then Adapter transforms this response before returning it to Client as defined in Target Interface.

Adapter_Pattern
We will declare two incompatible interfaces Square and Rectangle.
Adapter Design Pattern

Square.java
public interface Square {
    public void setSide(int sideLength);
    public void printAreaOfSquare();
}
Rectangle.java
public interface Rectangle {
    public void setLength(int length);
    public void setWidth(int width);
    public void printAreaOfRectangle();
}

Create Chessboard.java and Tenniscourt.java implementing Square and Rectangle interfaces respectively.
Adapter Design Pattern 1

Chessboard.java
public class Chessboard implements Square {
    int sideLength;
  
    @Override
    public void setSide(int sideLength){
        this.sideLength = sideLength;
    }
  
    @Override
    public void printAreaOfSquare(){
        System.out.println("Area of Chessbpard is " + sideLength*sideLength);
    }
}

Adapter Design Pattern 2

Tenniscourt.java
public class Tenniscourt implements Rectangle {
    int length, width;
  
    @Override
    public void setLength(int length){
        this.length = length;
    }
  
    @Override
    public void setWidth(int width){
        this.width = width;
    }
  
    @Override
    public void printAreaOfRectangle(){
        System.out.println("Area of Tennis Court is " + length*width);
    }
}

Now, we will define RectangleAdapter.java which is a wrapper over Rectangle interface. It implements Square interface over Rectangle Interface.
Adapter Design Pattern 3

RectangleAdapter.java
public class RectangleAdapter implements Square {
    Rectangle rect;
  
    public RectangleAdapter(Rectangle rect) {
        this.rect = rect;
    }
  
    // Setting length and width to same value to make it a square
    @Override
    public void setSide(int sideLength){
        rect.setLength(sideLength);
        rect.setWidth(sideLength);
    }
  
    @Override
    public void printAreaOfSquare(){
        rect.printAreaOfRectangle();
    }
}

Create AdapterPatternExample.java class to show the use of RectangleAdapter to call an Rectangle object using Square interface.
Adapter Design Pattern 4

AdapterPatternExample.java
public class AdapterPatternExample {
    public static void main(String args[]){
        Square square = new Chessboard();
        Rectangle rectangle = new Tenniscourt();
        Square adapter = new RectangleAdapter(rectangle);
  
        // Calculate Area of Square using Square Interface 
        square.setSide(5);
        square.printAreaOfSquare();
   
        // Calculate Area of Rectangle using Rectangle Interface
        rectangle.setLength(5);
        rectangle.setWidth(4);
        rectangle.printAreaOfRectangle();
   
        // Now we will call Rectangle object using Square interface 
        adapter.setSide(5);
        adapter.printAreaOfSquare(); 
    }
}

Output

Area of Chessbpard is 25
Area of Tennis Court is 20
Area of Tennis Court is 20

Important Points About Adapter Pattern

  • Adapter class changes the interface of an existing object.
  • Adapter class is a good example of object composition. Adapter class “has a” instance of the adaptee class.
  • We can use an Adapter with any class Implementing Adaptee Interface.
  • Adapter wraps an object to change it’s interface whereas a decorator wraps an object to add extra functionalities.

C program to efficiently multiply a number with 7 using bitwise operator

C program to efficiently multiply a number with 7 using bitwise operator
  • Write a program in C to multiply a number with 7 using bitwise operator.
  • How to multiply a number by 7 in one line.

Required knowledge Bitwise operator in C

    • Let’s derive an expression to multiply a number with 7 using bitwise operator. Let N be the number that we want to multiply with 7.
    • N x 7 = N + N + N + N + N + N + N
    • N x 7 = N + N + N + N + N + N + N + (N – N)
    • N x 7 = (N + N + N + N + N + N + N + N) – N
    • N x 7 = 8xN – N
    • As we know that, left shifting any number by one bit multiply it by 2. Hence, multiplying any number with 8 is equivalent to right shifting it by 3 bits(For Example : NX3 = N << 3). Replacing 8xN in above statement by 8 << 3.

N x 7 = (N << 3) – N

WARNING !!!!
This approach can only be used to multiply integers or char by 7 because bitwise Operators can only be applied on char and integer operands. We cannot use bitwise operators with float, double, long double, void and other user define complex data types.

C program to multiply a number with 7 using bitwise operator.

C program to efficiently multiply a number with 7 using bitwise operator

#include<stdio.h>
 
int main() {
    int num;
     
    printf("Enter an integer\n");
    scanf("%d", &num);
     
    printf("7 X %d = %d", num, (num << 3) - num);
 
    return 0;
}

Output

Enter an integer
3
3 X 7 = 21
Enter an integer
0
0 X 7 = 0