├── README.md ├── JavaPracticeQuestionsWithSolutions.rar ├── WindowAdapterEx.java ├── EnumEx.java ├── ActionListenerEx.java ├── SingletonEx.java ├── Mouse_WindowAdapterEx.java ├── AccountExceptionEx.java ├── ThreadClassEx.java ├── RunnableEx.java ├── TreeSetEx.java ├── KeyListenerEx.java ├── CloneEx.java ├── MultiThreadEx.java ├── EvntHandExtClass.java ├── AccountComparatorEx.java ├── ThreadPriorityEx.java ├── ArrayOfButtonsEx.java ├── HashSet.java ├── MouseListenerEx.java ├── SynchronizationBankEx.java ├── ThreadMethodsEx.java ├── CompositePatternEx.java ├── DecoratorEx.java ├── CommandPattern.java ├── MyThreadSuspendResume.java ├── SerializationEx.java ├── StatePattern.java ├── ResolveDeadLockTest.java ├── TestBuilderPattern.java ├── GridBagLayoutEx.java ├── ObserverPattern.java ├── ProduceConsumerEx.java ├── LayoutManagerEx.java ├── CardLayoutEx.java ├── TestAccount.java ├── StrategyPattern.java ├── AdapterPatternDemo.java ├── LibraryApplication.java ├── BankApplicationAWT.java ├── AbstractFactoryEx.java ├── IteratorPattern.java └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # Object-Oriented-Programming-with-Java 2 | Contains the codes used for demonstrating the concepts 3 | -------------------------------------------------------------------------------- /JavaPracticeQuestionsWithSolutions.rar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenniferRanjani/Object-Oriented-Programming-with-Java/HEAD/JavaPracticeQuestionsWithSolutions.rar -------------------------------------------------------------------------------- /WindowAdapterEx.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | public class WindowAdapterEx extends WindowAdapter { 4 | 5 | WindowAdapterEx() 6 | { 7 | Frame f = new Frame("Adapter Example"); 8 | 9 | f.setSize(300,300); 10 | f.setVisible(true); 11 | f.addWindowListener(this); 12 | } 13 | 14 | public void windowClosing(WindowEvent e) { 15 | System.exit(0); 16 | } 17 | 18 | public static void main(String[] args) 19 | { 20 | new WindowAdapterEx(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /EnumEx.java: -------------------------------------------------------------------------------- 1 | class EnumEx{ 2 | enum Color{ 3 | RED(100), GREEN(101), BLUE(102); 4 | 5 | int value; 6 | private Color(int val) 7 | { 8 | value = val; 9 | } 10 | int getValue() { 11 | return value; 12 | } 13 | 14 | } 15 | public static void main(String[] args) { 16 | Color c1 = Color.BLUE; 17 | Color v[] = Color.values(); 18 | 19 | System.out.println(c1); 20 | System.out.println(c1.name()); 21 | 22 | System.out.println(c1.getValue()); 23 | System.out.println(c1.ordinal()); 24 | 25 | for(Color c: v) 26 | System.out.println(c); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ActionListenerEx.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | 4 | class ActionListenerEx extends Frame implements ActionListener{ 5 | TextField tf; 6 | test(){ 7 | setTitle("Core Banking"); 8 | tf = new TextField(); 9 | tf.setBounds(100,50,170,30); 10 | Button b=new Button("Submit"); 11 | b.setBounds(100,100,100,30); 12 | add(b); 13 | add(tf); 14 | 15 | b.addActionListener(this); 16 | setSize(1000,1000); 17 | setBackground(Color.cyan); 18 | setLayout(null); 19 | setVisible(true); 20 | } 21 | public static void main(String[] args) 22 | { 23 | ActionListenerEx t= new ActionListenerEx(); 24 | } 25 | 26 | public void actionPerformed(ActionEvent E) 27 | { 28 | tf.setText("Welcome to Core Banking"); 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /SingletonEx.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class SingleRandom 3 | { 4 | private Random generator; 5 | private static SingleRandom instance = null; 6 | private SingleRandom() { generator = new Random(); } 7 | public void setSeed(int seed) { generator.setSeed(seed); } 8 | public int nextInt() { return generator.nextInt(); } 9 | public static synchronized SingleRandom getInstance() 10 | { 11 | if (instance ==null) 12 | { 13 | instance = new SingleRandom(); 14 | } 15 | return instance; 16 | } 17 | 18 | protected Object clone() throws CloneNotSupportedException { 19 | throw new CloneNotSupportedException("Clone is not allowed."); 20 | } 21 | } 22 | public class SingletonEx{ 23 | public static void main(String args[]){ 24 | int r1 = SingleRandom.getInstance().nextInt(); 25 | System.out.println(r1); 26 | r1 = SingleRandom.getInstance().nextInt(); 27 | System.out.println(r1); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Mouse_WindowAdapterEx.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | 4 | public class Mouse_WindowAdapterEx extends Frame 5 | { 6 | Mouse_WindowAdapterEx() 7 | { 8 | setSize(400,400); 9 | setVisible(true); 10 | Label l=new Label(); 11 | l.setBounds(20,50,200,20); 12 | l.setBackground(Color.cyan); 13 | 14 | TextArea area=new TextArea(); 15 | area.setBounds(20,80,300, 150); 16 | area.addMouseListener(new MouseAdapter() 17 | { 18 | public void mouseReleased(MouseEvent e) 19 | { 20 | l.setText(area.getSelectedText()); 21 | } 22 | }); 23 | 24 | addWindowListener(new WindowAdapter() 25 | { 26 | public void windowClosing(WindowEvent e) 27 | { 28 | System.exit(0); 29 | } 30 | }); 31 | 32 | 33 | add(l);add(area); 34 | } 35 | public static void main(String[] args) 36 | { 37 | new Mouse_WindowAdapterEx(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /AccountExceptionEx.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Account{ 4 | int acc; 5 | String name; 6 | float amt; 7 | Account(int acc,String name,float amt){ 8 | this.acc = acc; 9 | this.name = name; 10 | this.amt = amt; } 11 | 12 | void withdraw(float amt) throws MaxLimitException 13 | { 14 | if (amt > 20000) 15 | throw new MaxLimitException(amt-20000); 16 | } 17 | } 18 | 19 | class MaxLimitException extends Exception 20 | { 21 | private float amt; 22 | 23 | MaxLimitException(float amt) 24 | { 25 | this.amt = amt; 26 | } 27 | 28 | public String toString() 29 | { 30 | return "You are trying to withdraw an extra amount of Rs. "+amt; 31 | } 32 | } 33 | 34 | class AccountExceptionEx { 35 | public static void main(String[] args) { 36 | 37 | Account a[] = new Account[3]; 38 | 39 | 40 | a[0]= new Account(123,"Ankit",50000); 41 | a[1]= new Account(112,"Ashok",40000); 42 | a[2]= new Account(111,"Ryan",25000); 43 | 44 | try { 45 | a[2].withdraw(21999); 46 | } 47 | catch(MaxLimitException e) 48 | { 49 | System.out.println(e); 50 | } 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /ThreadClassEx.java: -------------------------------------------------------------------------------- 1 | class NewThread extends Thread{ 2 | Thread t; 3 | 4 | NewThread(){ 5 | super("Demo"); 6 | System.out.println("Child"+this); 7 | // start(); //starting the thread during its creation 8 | } 9 | 10 | public void run() 11 | { 12 | try { 13 | for(int n = 5; n>0; n--) { 14 | System.out.println("Child Thread"+n); 15 | Thread.sleep(500); // time specified in milli seconds u can also use Thread.sleep(milli,nano) 16 | } 17 | }catch(InterruptedException e) { 18 | System.out.println("Child Interrupted"); 19 | } 20 | System.out.println("Exiting Child"); 21 | } 22 | } 23 | 24 | 25 | class ThreadClassEx 26 | { 27 | public static void main(String args[]) { 28 | 29 | NewThread nt = new NewThread(); 30 | 31 | nt.start(); 32 | try { 33 | for(int n = 5; n>0; n--) { 34 | System.out.println("Main thread"+n); 35 | Thread.sleep(1000); // time specified in milli seconds u can also use Thread.sleep(milli,nano) 36 | } 37 | } 38 | catch(InterruptedException e) { 39 | System.out.println("Main Interrupted"); 40 | } 41 | System.out.println("Exiting Main"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /RunnableEx.java: -------------------------------------------------------------------------------- 1 | class NewThread implements Runnable{ 2 | Thread t; 3 | 4 | NewThread(){ 5 | t = new Thread(this,"Demo"); 6 | System.out.println("Child"+t); 7 | // t.start(); // Thread can also be started while it is created 8 | } 9 | 10 | public void run() 11 | { 12 | try { 13 | for(int n = 5; n>0; n--) { 14 | System.out.println("Child Thread"+n); 15 | Thread.sleep(500); // time specified in milli seconds u can also use Thread.sleep(milli,nano) 16 | } 17 | }catch(InterruptedException e) { 18 | System.out.println("Child Interrupted"); 19 | } 20 | System.out.println("Exiting Child"); 21 | } 22 | } 23 | 24 | 25 | class RunnableEx 26 | { 27 | public static void main(String args[]) { 28 | 29 | NewThread nt = new NewThread(); 30 | 31 | nt.t.start(); 32 | try { 33 | for(int n = 5; n>0; n--) { 34 | System.out.println("Main thread"+n); 35 | Thread.sleep(1000); // time specified in milli seconds u can also use Thread.sleep(milli,nano) 36 | } 37 | } 38 | catch(InterruptedException e) { 39 | System.out.println("Main Interrupted"); 40 | } 41 | System.out.println("Exiting Main"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /TreeSetEx.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class TreeSetEx { 4 | 5 | static TreeSet set(TreeSet A, TreeSet B, char op) { 6 | 7 | if (op == '+') 8 | A.addAll(B); // Union. 9 | else if (op == '*') 10 | A.retainAll(B); // Intersection. 11 | else 12 | A.removeAll(B); // Set difference. 13 | 14 | return A; 15 | } 16 | public static void main(String args[]) { 17 | TreeSet I1 = new TreeSet(); 18 | I1.add(10); 19 | I1.add(20); 20 | I1.add(30); 21 | I1.add(40); 22 | 23 | TreeSet I2 = new TreeSet(); 24 | I2.add(10); 25 | I2.add(20); 26 | I2.add(50); 27 | I2.add(60); 28 | 29 | TreeSet S1 = new TreeSet(); 30 | S1.add("java"); 31 | S1.add("C++"); 32 | S1.add("DIP"); 33 | S1.add("C"); 34 | 35 | TreeSet S2 = new TreeSet(); 36 | S2.add("C"); 37 | S2.add("C++"); 38 | S2.add("Python"); 39 | S2.add("Graphics"); 40 | 41 | 42 | I1 = set(I1,I2,'*'); 43 | System.out.println(I1); 44 | 45 | S1 = set(S1,S2,'-'); 46 | System.out.println(S1); 47 | 48 | 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /KeyListenerEx.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | public class KeyListenerEx extends Frame implements KeyListener 4 | { 5 | String msg = ""; 6 | 7 | test() 8 | { 9 | addKeyListener(this); 10 | setSize(400,400); 11 | setLayout(null); 12 | setVisible(true); 13 | setBackground(Color.cyan); 14 | } 15 | 16 | public void keyPressed(KeyEvent e) 17 | { 18 | int key = e.getKeyCode(); 19 | switch(key) 20 | { 21 | case KeyEvent.VK_F1: msg += "";break; 22 | case KeyEvent.VK_PAGE_UP: msg += "";break; 23 | case KeyEvent.VK_LEFT: msg += "";break; 24 | } 25 | repaint(); 26 | } 27 | 28 | public void keyReleased(KeyEvent e) 29 | { 30 | repaint(); 31 | } 32 | 33 | public void keyTyped(KeyEvent e) 34 | { 35 | msg +=e.getKeyChar(); 36 | repaint(); 37 | } 38 | 39 | public void paint(Graphics g) 40 | { 41 | g.drawString(msg, 50, 50); 42 | } 43 | 44 | public static void main(String[] args) 45 | { 46 | new KeyListenerEx(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /CloneEx.java: -------------------------------------------------------------------------------- 1 | class Test1 2 | { 3 | int x, y; 4 | 5 | Test1() 6 | { 7 | 8 | } 9 | Test1(Test1 t){ 10 | this.x = t.x; 11 | this.y = t.y; 12 | } 13 | } 14 | 15 | class Test2 implements Cloneable 16 | { 17 | int a, b; 18 | 19 | Test1 c = new Test1(); 20 | 21 | public Object clone() throws 22 | CloneNotSupportedException 23 | { 24 | Test2 t = (Test2)super.clone(); 25 | t.c = new Test1(this.c); //Comment this line for Shallow copy 26 | return t; 27 | } 28 | } 29 | 30 | class test 31 | { 32 | public static void main(String args[]) throws 33 | CloneNotSupportedException 34 | { 35 | Test2 t1 = new Test2(); 36 | t1.a = 10; 37 | t1.b = 20; 38 | t1.c.x = 30; 39 | t1.c.y = 40; 40 | 41 | Test2 t3 = (Test2)t1.clone(); 42 | // t3.a = 100; 43 | // t3.b = 200; 44 | // t3.c.x = 300; 45 | 46 | System.out.println(t1.a + " " + t1.b + " " + 47 | t1.c.x + " " + t1.c.y); 48 | System.out.println(t3.a + " " + t3.b + " " + 49 | t3.c.x + " " + t3.c.y); 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /MultiThreadEx.java: -------------------------------------------------------------------------------- 1 | class NewThread extends Thread{ 2 | Thread t; 3 | String name; 4 | NewThread(String tName){ 5 | super(tName); 6 | name= tName; 7 | System.out.println("Child"+this); 8 | } 9 | 10 | public void run() 11 | { 12 | try { 13 | for(int n = 5; n>0; n--) { 14 | System.out.println("Child Thread: "+name+": "+n); 15 | Thread.sleep(500); // time specified in milli seconds u can also use Thread.sleep(milli,nano) 16 | } 17 | }catch(InterruptedException e) { 18 | System.out.println("Child Interrupted"); 19 | } 20 | System.out.println("Exiting Child"); 21 | } 22 | } 23 | 24 | 25 | class MultiThreadEx 26 | { 27 | public static void main(String args[]) { 28 | 29 | NewThread nt1 = new NewThread("One"); 30 | NewThread nt2 = new NewThread("Two"); 31 | NewThread nt3 = new NewThread("Three"); 32 | 33 | nt1.start(); 34 | nt2.start(); 35 | nt3.start(); 36 | 37 | try { 38 | for(int n = 5; n>0; n--) { 39 | System.out.println("Main thread"+n); 40 | Thread.sleep(1000); // time specified in milli seconds u can also use Thread.sleep(milli,nano) 41 | } 42 | } 43 | catch(InterruptedException e) { 44 | System.out.println("Main Interrupted"); 45 | } 46 | System.out.println("Exiting Main"); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /EvntHandExtClass.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | class EvntHandExtClass extends Frame{ 4 | TextField tf; 5 | Label l; 6 | test() { 7 | setTitle("Core Banking"); 8 | tf = new TextField(); 9 | tf.setBounds(100,100,170,30); 10 | 11 | Button b=new Button("Submit"); 12 | b.setBounds(100,150,100,30); 13 | 14 | l = new Label(); 15 | l.setBounds(100,50,170,30); 16 | l.setBackground(Color.green); 17 | 18 | add(b); 19 | add(tf); 20 | add(l); 21 | 22 | AHandler a = new AHandler(this); 23 | b.addActionListener(a); 24 | tf.addTextListener(a); 25 | 26 | setSize(1000,1000); 27 | setBackground(Color.cyan); 28 | setLayout(null); 29 | setVisible(true); 30 | } 31 | public static void main(String[] args) { 32 | EvntHandExtClass t= new EvntHandExtClass(); } 33 | } 34 | 35 | class AHandler implements ActionListener,TextListener{ 36 | EvntHandExtClass obj; 37 | AHandler(EvntHandExtClass t){ 38 | this.obj = t; 39 | } 40 | public void textValueChanged(TextEvent e) { 41 | obj.l.setText("Entered text: " + obj.tf.getText()); 42 | } 43 | 44 | public void actionPerformed(ActionEvent E) { 45 | obj.l.setText("Welcome to Core Banking");} 46 | } 47 | -------------------------------------------------------------------------------- /AccountComparatorEx.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Account{ 4 | int acc; 5 | String name; 6 | float amt; 7 | Account(int acc,String name,float amt){ 8 | this.acc = acc; 9 | this.name = name; 10 | this.amt = amt; } 11 | public String toString() { 12 | return "Acc. No.: "+acc+" Name: "+name+" Amount: "+amt;} 13 | } 14 | 15 | class AmtCmp implements Comparator{ 16 | public int compare(Account a1,Account a2){ 17 | if(a1.amt==a2.amt) 18 | return 0; 19 | else if(a1.amt>a2.amt) 20 | return 1; 21 | else 22 | return -1; } 23 | } 24 | 25 | class AccCmp implements Comparator{ 26 | public int compare(Account a1,Account a2){ 27 | if(a1.acc==a2.acc) 28 | return 0; 29 | else if(a1.acc>a2.acc) 30 | return 1; 31 | else 32 | return -1; } 33 | } 34 | 35 | class AccountComparatorEx { 36 | public static void main(String[] args) { 37 | List al = new ArrayList(); 38 | 39 | al.add(new Account(123,"Ankit",5000)); 40 | al.add(new Account(112,"Ashok",4000)); 41 | al.add(new Account(111,"Ryan",5000)); 42 | 43 | System.out.println("Comparison on Amount"); 44 | Collections.sort(al,new AmtCmp()); 45 | for(Account a:al) 46 | System.out.println(a); 47 | 48 | System.out.println("Comparison on Acc. No."); 49 | Collections.sort(al,new AccCmp()); 50 | for(Account a:al) 51 | System.out.println(a); } 52 | } 53 | -------------------------------------------------------------------------------- /ThreadPriorityEx.java: -------------------------------------------------------------------------------- 1 | class NewThread extends Thread{ 2 | String name; 3 | NewThread(String tName, int priority){ 4 | super(tName); 5 | name= tName; 6 | setPriority(priority); 7 | System.out.println("Child"+this); 8 | } 9 | 10 | public void run() 11 | { 12 | try { 13 | for(int n = 5; n>0; n--) { 14 | System.out.println("Child Thread: "+name+": "+n); 15 | Thread.sleep(500); 16 | } 17 | }catch(InterruptedException e) { 18 | System.out.println("Child Interrupted"); 19 | } 20 | System.out.println("Exiting Child"); 21 | } 22 | } 23 | 24 | 25 | public class ThreadPriorityEx 26 | { 27 | public static void main(String args[]) { 28 | Thread t = Thread.currentThread(); 29 | t.setPriority(1); 30 | 31 | NewThread nt1 = new NewThread("One",2); 32 | NewThread nt2 = new NewThread("Two",Thread.MAX_PRIORITY); 33 | NewThread nt3 = new NewThread("Three",Thread.NORM_PRIORITY); 34 | 35 | nt1.start(); 36 | nt2.start(); 37 | nt3.start(); 38 | 39 | try { 40 | 41 | 42 | nt1.join(); 43 | nt2.join(); 44 | nt3.join(); 45 | 46 | 47 | for(int n = 5; n>0; n--) { 48 | System.out.println("Main thread"+n); 49 | Thread.sleep(1000); 50 | } 51 | } 52 | catch(Exception e) { 53 | System.out.println("Main Interrupted"); 54 | } 55 | System.out.println("Exiting Main"); 56 | } 57 | } 58 | 59 | 60 | -------------------------------------------------------------------------------- /ArrayOfButtonsEx.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | public class ArrayOfButtonsEx implements ActionListener { 4 | Frame f; 5 | TextField tf = new TextField(); 6 | Button b[] = new Button[3]; 7 | ArrayOfButtonsEx(){ 8 | f = new Frame("ButtonExample"); 9 | b[0] = new Button("Yes"); 10 | b[1] = new Button("No"); 11 | b[2] = new Button("May Be"); 12 | 13 | f.add(b[0]); 14 | f.add(b[1]); 15 | f.add(b[2]); 16 | 17 | for(int i = 0;i<3;i++) 18 | { 19 | b[i].setBounds(100,100+i*50,100,30); 20 | } 21 | 22 | for(int i =0;i<3;i++) 23 | { 24 | b[i].addActionListener(this); 25 | } 26 | tf.setBackground(Color.cyan); 27 | tf.setBounds(100,250,200,30); 28 | f.add(tf); 29 | f.setSize(300,300); 30 | f.setLayout(null); 31 | f.setVisible(true); } 32 | 33 | public void actionPerformed(ActionEvent e) 34 | { 35 | for (int j=0;j<3;j++) 36 | { 37 | if(e.getSource() == b[j]) 38 | tf.setText("Button Pressed: "+b[j].getLabel()); 39 | } 40 | } 41 | 42 | public static void main(String[] args) 43 | { 44 | new ArrayOfButtonsEx(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /HashSet.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Objects; 3 | import java.util.Set; 4 | 5 | class Account 6 | { 7 | private String name; 8 | private int age; 9 | 10 | // Constructor 11 | Account(String name, int age) 12 | { 13 | this.name = name; 14 | this.age = age; 15 | } 16 | 17 | @Override 18 | public boolean equals(Object ob) { 19 | 20 | if (ob == this) 21 | return true; 22 | 23 | if (ob == null || ob.getClass() != getClass()) { 24 | return false; 25 | } 26 | 27 | Account p = (Account) ob; 28 | return Objects.equals(name, p.name) && p.age == age; 29 | } 30 | 31 | @Override 32 | public int hashCode() { 33 | return Objects.hash(name,age); 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return "{" + name + ", " + age + "}"; 39 | } 40 | } 41 | 42 | class Main{ 43 | 44 | public static void main (String[] args) 45 | { 46 | Account p1 = new Account("John", 19); 47 | Account p2 = new Account("John", 20); 48 | Account p3 = new Account("Carol", 16); 49 | Account p4 = new Account("Zen", 14); 50 | 51 | 52 | Set set = new HashSet<>(); 53 | set.add(p1); 54 | set.add(p2); 55 | set.add(p3); 56 | set.add(p4); 57 | 58 | System.out.println(set); 59 | 60 | System.out.println(p1.hashCode()); 61 | System.out.println(p2.hashCode()); 62 | 63 | 64 | System.out.println(p1.equals(p2)); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /MouseListenerEx.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | public class MouseListenerEx extends Frame implements MouseListener{ 4 | String msg ="Welcome"; 5 | Color c = Color.red; 6 | 7 | MouseListenerEx() 8 | { 9 | addMouseListener(this); 10 | setSize(300,300); 11 | setLayout(null); 12 | setVisible(true); 13 | } 14 | 15 | public void mouseEntered(MouseEvent e) 16 | { 17 | msg = "Mouse Entered"; 18 | repaint(); 19 | } 20 | 21 | public void mouseExited(MouseEvent e) 22 | { 23 | msg = "Mouse Exited"; 24 | repaint(); 25 | } 26 | 27 | public void mouseClicked(MouseEvent e) 28 | { 29 | Graphics g=getGraphics(); 30 | g.setColor(Color.BLUE); 31 | g.fillOval(e.getX(),e.getY(),30,30); 32 | } 33 | 34 | public void mousePressed(MouseEvent e) 35 | { 36 | } 37 | public void mouseReleased(MouseEvent e) 38 | { 39 | } 40 | 41 | public void paint(Graphics g) 42 | { 43 | g.setColor(c); 44 | Font font = new Font("TimesNewRoman", Font.PLAIN, 24); 45 | g.setFont(font); 46 | g.drawString(msg, 50, 150); 47 | } 48 | 49 | public static void main(String[] args) 50 | { 51 | new MouseListenerEx(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /SynchronizationBankEx.java: -------------------------------------------------------------------------------- 1 | class Account 2 | { 3 | float amount; 4 | 5 | synchronized void withdraw(float amt) { 6 | try 7 | { 8 | System.out.println("Details for Thread"+Thread.currentThread()); 9 | Thread.sleep(1000); 10 | 11 | if(amount - amt < 0) 12 | System.out.println("Insufficient Funds. Current Balance is"+amount); 13 | else { 14 | amount -=amt; 15 | System.out.println("Balance is "+amount); 16 | } 17 | } 18 | catch (Exception e) 19 | { 20 | System.out.println("Thread interrupted."); 21 | } 22 | } 23 | } 24 | 25 | class AccountThread extends Thread 26 | { 27 | private float amt; 28 | Account A; 29 | 30 | AccountThread(float amt, Account A1){ 31 | this.amt = amt; 32 | this.A = A1; 33 | } 34 | 35 | public void run() { 36 | // Uncomment the following lines if we dont have access to the Account class and withdraw method can not be synchronized. 37 | // synchronized(A) 38 | // { 39 | A.withdraw(amt); 40 | try { 41 | Thread.sleep(1000); 42 | } catch (InterruptedException e) { 43 | 44 | } 45 | // } 46 | } 47 | } 48 | 49 | 50 | class SynchronizationBankEx 51 | { 52 | public static void main(String args[]) { 53 | Account A = new Account(); 54 | A.amount = 7000; 55 | AccountThread T1 = new AccountThread(5000, A); 56 | AccountThread T2 = new AccountThread(7000, A); 57 | 58 | T1.start(); 59 | T2.start(); 60 | 61 | try { 62 | T1.join(); 63 | T2.join(); 64 | } 65 | catch(Exception e) { 66 | System.out.println("Interrupted"); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /ThreadMethodsEx.java: -------------------------------------------------------------------------------- 1 | 2 | class NewThread extends Thread{ 3 | String name; 4 | NewThread(String tName){ 5 | super(tName); 6 | name= tName; 7 | System.out.println("Child"+this); 8 | } 9 | 10 | public void run() 11 | { 12 | try { 13 | for(int n = 5; n>0; n--) { 14 | System.out.println("Child Thread: "+name+": "+n); 15 | Thread.sleep(500); // time specified in milli seconds u can also use Thread.sleep(milli,nano) 16 | } 17 | }catch(InterruptedException e) { 18 | System.out.println("Child Interrupted"); 19 | } 20 | System.out.println("Exiting Child"); 21 | } 22 | } 23 | 24 | 25 | class ThreadMethodsEx 26 | { 27 | public static void main(String args[]) { 28 | 29 | NewThread nt1 = new NewThread("One"); 30 | NewThread nt2 = new NewThread("Two"); 31 | NewThread nt3 = new NewThread("Three"); 32 | 33 | nt1.start(); 34 | nt2.start(); 35 | nt3.start(); 36 | 37 | try { 38 | // Uncomment the following lines to learn the impact of isAlive() 39 | // while(nt1.isAlive() | nt2.isAlive() | nt3.isAlive()) 40 | // { Thread.sleep(5000); 41 | // } 42 | 43 | // Uncomment the following lines to learn the impact of join() 44 | // nt1.join(); 45 | // nt2.join(); 46 | // nt3.join(); 47 | 48 | 49 | for(int n = 5; n>0; n--) { 50 | System.out.println("Main thread"+n); 51 | Thread.sleep(1000); // time specified in milli seconds u can also use Thread.sleep(milli,nano) 52 | // Try using yield() instead of sleep() 53 | // Thread.yield(); 54 | } 55 | } 56 | catch(Exception e) { 57 | System.out.println("Main Interrupted"); 58 | } 59 | System.out.println("Exiting Main"); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /CompositePatternEx.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | //Declare all interfaces and classes as public; public modifier is ignored for simplicity 4 | 5 | interface Shape { 6 | 7 | public void draw(String fillColor); 8 | } 9 | 10 | class Triangle implements Shape { 11 | 12 | @Override 13 | public void draw(String fillColor) { 14 | System.out.println("Drawing Triangle with color "+fillColor); 15 | } 16 | 17 | } 18 | 19 | 20 | class Circle implements Shape { 21 | 22 | @Override 23 | public void draw(String fillColor) { 24 | System.out.println("Drawing Circle with color "+fillColor); 25 | } 26 | 27 | } 28 | 29 | //Composite Class 30 | class Drawing implements Shape{ 31 | 32 | //collection of Shapes 33 | private List shapes = new ArrayList(); 34 | 35 | @Override 36 | public void draw(String fillColor) { 37 | for(Shape sh : shapes) 38 | { 39 | sh.draw(fillColor); 40 | } 41 | } 42 | 43 | //adding shape to drawing 44 | public void add(Shape s){ 45 | this.shapes.add(s); 46 | } 47 | 48 | //removing shape from drawing 49 | public void remove(Shape s){ 50 | this.shapes.remove(s); 51 | } 52 | 53 | //removing all the shapes 54 | public void clear(){ 55 | System.out.println("Clearing all the shapes from drawing"); 56 | this.shapes.clear(); 57 | } 58 | } 59 | 60 | 61 | 62 | public class CompositePatternEx { 63 | 64 | public static void main(String[] args) { 65 | Shape tri = new Triangle(); 66 | Shape tri1 = new Triangle(); 67 | Shape cir = new Circle(); 68 | 69 | Drawing drawing = new Drawing(); 70 | drawing.add(tri1); 71 | drawing.add(tri1); 72 | drawing.add(cir); 73 | 74 | drawing.draw("Red"); 75 | 76 | drawing.clear(); 77 | 78 | drawing.add(tri); 79 | drawing.add(cir); 80 | drawing.draw("Green"); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /DecoratorEx.java: -------------------------------------------------------------------------------- 1 | //Source: https://www.journaldev.com/1540/decorator-design-pattern-in-java-example 2 | 3 | //For simplicity public modifier is removed from all the interfaces and classes. 4 | 5 | interface Car { 6 | public void assemble(); 7 | } 8 | 9 | class BasicCar implements Car { 10 | 11 | @Override 12 | public void assemble() { 13 | System.out.println("Basic Car."); 14 | } 15 | } 16 | 17 | class CarDecorator implements Car { 18 | 19 | protected Car car; 20 | String color= null; 21 | String steering =null; 22 | 23 | public CarDecorator(Car c){ 24 | car=c; 25 | } 26 | 27 | @Override 28 | public void assemble() { 29 | car.assemble(); 30 | } 31 | } 32 | 33 | class SportsCar extends CarDecorator { 34 | 35 | public SportsCar(Car c) { 36 | super(c); 37 | } 38 | 39 | @Override 40 | public void assemble(){ 41 | super.assemble(); 42 | System.out.print("Adding features of Sports Car."); 43 | steering(); 44 | } 45 | 46 | public void steering() { 47 | steering = "Four-wheel Steering"; 48 | System.out.println(" The sports Car has "+steering+"."); 49 | } 50 | } 51 | 52 | class LuxuryCar extends CarDecorator { 53 | 54 | public LuxuryCar(Car c) { 55 | super(c); 56 | } 57 | 58 | @Override 59 | public void assemble(){ 60 | super.assemble(); 61 | System.out.print("Adding features of Luxury Car."); 62 | color(); 63 | } 64 | 65 | public void color() { 66 | color = "Red"; 67 | System.out.println(" Color of the Luxury Car is "+color+"."); 68 | } 69 | } 70 | 71 | public class DecoratorEx { 72 | 73 | public static void main(String[] args) { 74 | Car sportsCar = new SportsCar(new BasicCar()); 75 | sportsCar.assemble(); 76 | System.out.println("\n*****"); 77 | 78 | Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar())); 79 | sportsLuxuryCar.assemble(); 80 | } 81 | } 82 | 83 | -------------------------------------------------------------------------------- /CommandPattern.java: -------------------------------------------------------------------------------- 1 | //Source: https://www.tutorialspoint.com/design_pattern/command_pattern.htm 2 | 3 | import java.util.*; 4 | 5 | interface Order { 6 | //Command 7 | void execute(); 8 | } 9 | 10 | 11 | class Stock { 12 | 13 | private String name = "ABC"; 14 | private int quantity = 10; 15 | 16 | public void buy(){ 17 | System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] bought"); 18 | } 19 | public void sell(){ 20 | System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] sold"); 21 | } 22 | } 23 | 24 | 25 | class BuyStock implements Order { 26 | private Stock abcStock; 27 | 28 | public BuyStock(Stock abcStock){ 29 | this.abcStock = abcStock; 30 | } 31 | 32 | public void execute() { 33 | abcStock.buy(); 34 | } 35 | } 36 | 37 | class SellStock implements Order { 38 | private Stock abcStock; 39 | 40 | public SellStock(Stock abcStock){ 41 | this.abcStock = abcStock; 42 | } 43 | 44 | public void execute() { 45 | abcStock.sell(); 46 | } 47 | } 48 | 49 | 50 | 51 | class Broker { 52 | //Invoker 53 | private List orderList = new ArrayList(); 54 | 55 | public void takeOrder(Order order){ 56 | orderList.add(order); 57 | } 58 | 59 | public void placeOrders(){ 60 | 61 | for (Order order : orderList) { 62 | order.execute(); 63 | } 64 | orderList.clear(); 65 | } 66 | } 67 | 68 | 69 | public class CommandPattern { 70 | public static void main(String[] args) { 71 | 72 | //Client 73 | Stock abcStock = new Stock(); 74 | 75 | BuyStock buyStockOrder = new BuyStock(abcStock); 76 | SellStock sellStockOrder = new SellStock(abcStock); 77 | 78 | Broker broker = new Broker(); 79 | broker.takeOrder(buyStockOrder); 80 | broker.takeOrder(sellStockOrder); 81 | 82 | broker.placeOrders(); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /MyThreadSuspendResume.java: -------------------------------------------------------------------------------- 1 | class NewThread extends Thread{ 2 | String name; 3 | boolean flag; 4 | 5 | NewThread(String tName){ 6 | super(tName); 7 | name= tName; 8 | flag = false; 9 | System.out.println("Child"+this); 10 | } 11 | 12 | public void run() 13 | { 14 | try { 15 | for(int n = 5; n>0; n--) { 16 | System.out.println("Child Thread: "+name+": "+n); 17 | Thread.sleep(2000); 18 | 19 | synchronized(this) 20 | { 21 | while(flag) { 22 | wait(); 23 | } 24 | } 25 | 26 | } 27 | }catch(InterruptedException e) { 28 | System.out.println("Child Interrupted"); 29 | } 30 | System.out.println("Exiting Child"); 31 | } 32 | 33 | synchronized void mySuspend() 34 | { 35 | flag = true; 36 | } 37 | 38 | synchronized void myResume() 39 | { 40 | flag = false; 41 | notify(); 42 | } 43 | } 44 | 45 | 46 | class MyThreadSuspendResume 47 | { 48 | public static void main(String args[]) { 49 | Thread t = Thread.currentThread(); 50 | t.setPriority(1); 51 | 52 | NewThread nt1 = new NewThread("One"); 53 | NewThread nt2 = new NewThread("Two"); 54 | 55 | 56 | nt1.start(); 57 | nt2.start(); 58 | 59 | 60 | try { 61 | Thread.sleep(2000); 62 | 63 | nt1.mySuspend(); 64 | System.out.println("Suspending first Thread"); 65 | 66 | nt2.mySuspend(); 67 | System.out.println("Suspending second Thread"); 68 | Thread.sleep(2000); 69 | 70 | System.out.println("Resuming first Thread"); 71 | nt1.myResume(); 72 | Thread.sleep(3000); 73 | System.out.println("Resuming second Thread"); 74 | nt2.myResume(); 75 | 76 | 77 | } 78 | catch(Exception e) { 79 | System.out.println("Main Interrupted"); 80 | } 81 | 82 | try { 83 | nt1.join(); 84 | nt2.join(); 85 | } catch (InterruptedException e) { 86 | e.printStackTrace(); 87 | } 88 | 89 | System.out.println("Exiting Main"); 90 | } 91 | } 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /SerializationEx.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class SerializationEx implements Serializable { 4 | // Normal variables 5 | int i = 20; 6 | transient float j = 30; 7 | 8 | public static void main(String[] args) throws Exception 9 | { 10 | SerializationEx input = new SerializationEx(); 11 | 12 | // serialization 13 | FileOutputStream fos = new FileOutputStream("abc.txt"); 14 | ObjectOutputStream oos = new ObjectOutputStream(fos); 15 | oos.writeInt(input.i); 16 | oos.writeFloat(input.j); 17 | oos.close(); 18 | 19 | // de-serialization 20 | FileInputStream fis = new FileInputStream("abc.txt"); 21 | ObjectInputStream ois = new ObjectInputStream(fis); 22 | 23 | System.out.println("i = " + ois.readInt()); 24 | System.out.println("j = " + ois.readFloat()); 25 | 26 | ois.close(); 27 | } 28 | 29 | } 30 | 31 | //Uncomment the following lines to see the impact of transient on writeObject and readObject 32 | // public class SerializationEx implements Serializable { 33 | // // Normal variables 34 | // int i = 20; 35 | // transient float j = 30; 36 | 37 | // public static void main(String[] args) throws Exception 38 | // { 39 | // SerializationEx input = new SerializationEx(); 40 | 41 | // // serialization 42 | // FileOutputStream fos = new FileOutputStream("abc.txt"); 43 | // ObjectOutputStream oos = new ObjectOutputStream(fos); 44 | // oos.writeObject(input); 45 | // oos.close(); 46 | 47 | // // de-serialization 48 | // FileInputStream fis = new FileInputStream("abc.txt"); 49 | // ObjectInputStream ois = new ObjectInputStream(fis); 50 | 51 | // SerializationEx output = (SerializationEx)ois.readObject(); 52 | // System.out.println("i ="+ output.i + "j ="+output.j); 53 | // ois.close(); 54 | // } 55 | // } 56 | -------------------------------------------------------------------------------- /StatePattern.java: -------------------------------------------------------------------------------- 1 | //Source: https://www.journaldev.com/1751/state-design-pattern-java 2 | 3 | // //Uncomment the following code the study the need for the state design pattern 4 | // //TV Remote Example without state design pattern 5 | // public class TVRemoteBasic { 6 | 7 | // private String state=""; 8 | 9 | // public void setState(String state){ 10 | // this.state=state; 11 | // } 12 | 13 | // public void doAction(){ 14 | // if(state.equalsIgnoreCase("ON")){ 15 | // System.out.println("TV is turned ON"); 16 | // }else if(state.equalsIgnoreCase("OFF")){ 17 | // System.out.println("TV is turned OFF"); 18 | // } 19 | // } 20 | 21 | // public static void main(String args[]){ 22 | // TVRemoteBasic remote = new TVRemoteBasic(); 23 | 24 | // remote.setState("ON"); 25 | // remote.doAction(); 26 | 27 | // remote.setState("OFF"); 28 | // remote.doAction(); 29 | // } 30 | 31 | // } 32 | 33 | 34 | //State Design Pattern 35 | interface State { 36 | 37 | public void goNext(); 38 | } 39 | 40 | class TVStartState implements State { 41 | 42 | @Override 43 | public void goNext() { 44 | System.out.println("TV is turned ON"); 45 | } 46 | 47 | } 48 | 49 | class TVStopState implements State { 50 | 51 | @Override 52 | public void goNext() { 53 | System.out.println("TV is turned OFF"); 54 | } 55 | 56 | } 57 | 58 | class TVContext implements State { 59 | 60 | private State tvState; 61 | 62 | public void setState(State state) { 63 | tvState=state; 64 | } 65 | 66 | public State getState() { 67 | return tvState; 68 | } 69 | 70 | @Override 71 | public void goNext() { 72 | tvState.goNext(); 73 | } 74 | } 75 | 76 | 77 | class StatePattern { 78 | 79 | public static void main(String[] args) { 80 | TVContext context = new TVContext(); 81 | State tvStartState = new TVStartState(); 82 | State tvStopState = new TVStopState(); 83 | 84 | context.setState(tvStartState); 85 | context.goNext(); 86 | 87 | 88 | context.setState(tvStopState); 89 | context.goNext(); 90 | 91 | } 92 | 93 | } 94 | 95 | -------------------------------------------------------------------------------- /ResolveDeadLockTest.java: -------------------------------------------------------------------------------- 1 | public class ResolveDeadLockTest { 2 | 3 | public static void main(String[] args) { 4 | ResolveDeadLockTest test = new ResolveDeadLockTest(); 5 | 6 | final A a = test.new A(); 7 | final B b = test.new B(); 8 | 9 | // Thread-1 10 | Runnable block1 = new Runnable() { 11 | public void run() { 12 | 13 | //Deadlock in the following code can be resolved by rearranging the synchronized blocks on "object b" first followed by a synchronized block on "object a" 14 | synchronized (a) { 15 | try { 16 | // Adding delay so that both threads can start trying to lock resources 17 | Thread.sleep(100); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | // Thread-1 have A but need B also 22 | synchronized (b) { 23 | System.out.println("In block 1"); 24 | } 25 | } 26 | } 27 | }; 28 | 29 | // Thread-2 30 | Runnable block2 = new Runnable() { 31 | public void run() { 32 | synchronized (b) { 33 | // Thread-2 have B but need A also 34 | synchronized (a) { 35 | System.out.println("In block 2"); 36 | } 37 | } 38 | } 39 | }; 40 | 41 | new Thread(block1).start(); 42 | new Thread(block2).start(); 43 | } 44 | 45 | // Resource A 46 | private class A { 47 | private int i = 10; 48 | 49 | public int getI() { 50 | return i; 51 | } 52 | 53 | public void setI(int i) { 54 | this.i = i; 55 | } 56 | } 57 | 58 | // Resource B 59 | private class B { 60 | private int i = 20; 61 | 62 | public int getI() { 63 | return i; 64 | } 65 | 66 | public void setI(int i) { 67 | this.i = i; 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /TestBuilderPattern.java: -------------------------------------------------------------------------------- 1 | import javax.swing.JOptionPane; 2 | 3 | class Computer { 4 | 5 | //required parameters 6 | private String HDD; 7 | private String RAM; 8 | 9 | //optional parameters 10 | private boolean isGraphicsCardEnabled; 11 | private boolean isBluetoothEnabled; 12 | 13 | 14 | public String getHDD() { 15 | return HDD; 16 | } 17 | 18 | public String getRAM() { 19 | return RAM; 20 | } 21 | 22 | public boolean isGraphicsCardEnabled() { 23 | return isGraphicsCardEnabled; 24 | } 25 | 26 | public boolean isBluetoothEnabled() { 27 | return isBluetoothEnabled; 28 | } 29 | 30 | private Computer(ComputerBuilder builder) { 31 | this.HDD=builder.HDD; 32 | this.RAM=builder.RAM; 33 | this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled; 34 | this.isBluetoothEnabled=builder.isBluetoothEnabled; 35 | } 36 | 37 | //Builder Class 38 | public static class ComputerBuilder{ 39 | 40 | // required parameters 41 | private String HDD; 42 | private String RAM; 43 | 44 | // optional parameters 45 | private boolean isGraphicsCardEnabled; 46 | private boolean isBluetoothEnabled; 47 | 48 | public ComputerBuilder(String hdd, String ram){ 49 | this.HDD=hdd; 50 | this.RAM=ram; 51 | } 52 | 53 | public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) { 54 | this.isGraphicsCardEnabled = isGraphicsCardEnabled; 55 | return this; 56 | } 57 | 58 | public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) { 59 | this.isBluetoothEnabled = isBluetoothEnabled; 60 | return this; 61 | } 62 | 63 | public Computer build(){ 64 | return new Computer(this); 65 | } 66 | 67 | } 68 | } 69 | 70 | public class TestBuilderPattern { 71 | 72 | public static void main(String[] args) { 73 | String hdd, ram; 74 | Boolean bt; 75 | hdd = JOptionPane.showInputDialog("Enter HDD size in GB"); 76 | ram = JOptionPane.showInputDialog("Enter RAM size in GB"); 77 | bt = Boolean.parseBoolean(JOptionPane.showInputDialog("Should Bluetooth be Enable (T/F)?")); 78 | 79 | Computer comp = new Computer.ComputerBuilder(hdd, ram).setBluetoothEnabled(bt).build(); 80 | JOptionPane.showConfirmDialog(null, "HDD = "+comp.getHDD()+" isGraphicsCardEnabled "+ comp.isGraphicsCardEnabled()); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /GridBagLayoutEx.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | public class GridBagLayoutEx implements ActionListener { 4 | Frame f,p; 5 | 6 | TextField tf; 7 | Button b[] = new Button[3]; 8 | GridBagLayoutEx(){ 9 | f = new Frame("ButtonExample"); 10 | 11 | b[0] = new Button("Yes"); 12 | b[1] = new Button("No"); 13 | b[2] = new Button("May Be"); 14 | 15 | 16 | 17 | tf = new TextField(); 18 | tf.setBackground(Color.cyan); 19 | 20 | // *********************Grid Bag Constraints********************** 21 | GridBagConstraints gbc = new GridBagConstraints(); 22 | f.setLayout(new GridBagLayout()); 23 | 24 | gbc.fill = GridBagConstraints.HORIZONTAL; 25 | gbc.gridx = 0; 26 | gbc.gridy = 0; 27 | gbc.weightx = 0.5; 28 | f.add(b[0],gbc); 29 | 30 | gbc.ipady = 40; 31 | gbc.gridx = 1; 32 | gbc.gridy = 0; 33 | f.add(b[1],gbc); 34 | 35 | 36 | gbc.gridwidth = 2; 37 | gbc.insets = new Insets(10,10,10,10); 38 | gbc.gridx = 0; 39 | gbc.gridy = 1; 40 | f.add(b[2],gbc); 41 | 42 | gbc.ipady = 0; 43 | gbc.weighty = 1; 44 | gbc.anchor = GridBagConstraints.PAGE_END; 45 | gbc.gridx = 0; 46 | gbc.gridy = 2; 47 | gbc.gridwidth = 1; 48 | f.add(tf,gbc); 49 | //*********************End of Constraints************************* 50 | 51 | for(int i =0;i<3;i++) 52 | { 53 | b[i].addActionListener(this); 54 | } 55 | 56 | f.setSize(300,300); 57 | f.setVisible(true); 58 | 59 | 60 | } 61 | 62 | public void actionPerformed(ActionEvent e) 63 | { 64 | for (int j=0;j<3;j++) 65 | { 66 | if(e.getSource() == b[j]) 67 | tf.setText("Button Pressed: "+b[j].getLabel()); 68 | } 69 | } 70 | 71 | public static void main(String[] args) 72 | { 73 | new GridBagLayoutEx(); 74 | } 75 | } 76 | 77 | 78 | -------------------------------------------------------------------------------- /ObserverPattern.java: -------------------------------------------------------------------------------- 1 | //Source: https://www.tutorialspoint.com/design_pattern/observer_pattern.htm 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | class Subject { 7 | 8 | private List observers = new ArrayList(); 9 | private int state; 10 | 11 | public int getState() { 12 | return state; 13 | } 14 | 15 | public void setState(int state) { 16 | this.state = state; 17 | notifyAllObservers(); 18 | } 19 | 20 | public void attach(Observer observer){ 21 | observers.add(observer); 22 | } 23 | 24 | public void notifyAllObservers(){ 25 | for (Observer observer : observers) { 26 | observer.update(); 27 | } 28 | } 29 | } 30 | 31 | 32 | abstract class Observer { 33 | protected Subject subject; 34 | public abstract void update(); 35 | } 36 | 37 | class BinaryObserver extends Observer{ 38 | 39 | public BinaryObserver(Subject subject){ 40 | this.subject = subject; 41 | } 42 | 43 | @Override 44 | public void update() { 45 | System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) ); 46 | } 47 | } 48 | 49 | class OctalObserver extends Observer{ 50 | 51 | public OctalObserver(Subject subject){ 52 | this.subject = subject; 53 | } 54 | 55 | @Override 56 | public void update() { 57 | System.out.println( "Octal String: " + Integer.toOctalString( subject.getState() ) ); 58 | } 59 | } 60 | 61 | class HexaObserver extends Observer{ 62 | 63 | public HexaObserver(Subject subject){ 64 | this.subject = subject; 65 | } 66 | 67 | @Override 68 | public void update() { 69 | System.out.println( "Hex String: " + Integer.toHexString( subject.getState() ).toUpperCase() ); 70 | } 71 | } 72 | 73 | class ObserverPattern { 74 | public static void main(String[] args) { 75 | Subject subject = new Subject(); 76 | 77 | HexaObserver h = new HexaObserver(subject); 78 | OctalObserver o = new OctalObserver(subject); 79 | BinaryObserver b = new BinaryObserver(subject); 80 | 81 | subject.attach(h); 82 | subject.attach(o); 83 | subject.attach(b); 84 | 85 | 86 | System.out.println("First state change: 15"); 87 | subject.setState(15); 88 | System.out.println("Second state change: 10"); 89 | subject.setState(10); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /ProduceConsumerEx.java: -------------------------------------------------------------------------------- 1 | public class ProduceConsumerEx { 2 | public static void main(String[] args) { 3 | CubbyHole c = new CubbyHole(); 4 | Producer p1 = new Producer(c, 1); 5 | Consumer c1 = new Consumer(c, 1); 6 | Consumer c2 = new Consumer(c, 2); 7 | p1.start(); 8 | c1.start(); 9 | c2.start(); 10 | } 11 | } 12 | 13 | //Uncomment these lines to understand what will happen when inter thread communication is not available. 14 | //class CubbyHole 15 | //{ 16 | // private int contents; 17 | // 18 | // synchronized int get() 19 | // { 20 | // return contents; 21 | // } 22 | // 23 | // synchronized void put(int value) { 24 | // contents = value; 25 | // } 26 | //} 27 | class CubbyHole { 28 | private int contents; 29 | private boolean available = false; 30 | 31 | public synchronized int get() { 32 | while (available == false) { 33 | try { 34 | wait(); 35 | } catch (InterruptedException e) {} 36 | } 37 | available = false; 38 | notifyAll(); 39 | return contents; 40 | } 41 | public synchronized void put(int value) { 42 | while (available == true) { 43 | try { 44 | wait(); 45 | } catch (InterruptedException e) { } 46 | } 47 | contents = value; 48 | available = true; 49 | notifyAll(); 50 | } 51 | } 52 | class Consumer extends Thread { 53 | private CubbyHole cubbyhole; 54 | private int number; 55 | 56 | public Consumer(CubbyHole c, int number) { 57 | cubbyhole = c; 58 | this.number = number; 59 | } 60 | public void run() { 61 | int value = 0; 62 | for (int i = 0; i < 10; i++) { 63 | value = cubbyhole.get(); 64 | System.out.println("Consumer #" + this.number + " got: " + value); 65 | } 66 | } 67 | } 68 | class Producer extends Thread { 69 | private CubbyHole cubbyhole; 70 | private int number; 71 | public Producer(CubbyHole c, int number) { 72 | cubbyhole = c; 73 | this.number = number; 74 | } 75 | public void run() { 76 | for (int i = 0; i < 20; i++) { 77 | int val = (int)(Math.random() * 100); 78 | cubbyhole.put(val); 79 | System.out.println("Producer #" + this.number + " put: " + val); 80 | try { 81 | sleep(1000); 82 | } catch (InterruptedException e) { } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /LayoutManagerEx.java: -------------------------------------------------------------------------------- 1 | //Uncomment the appropriate layout choice and comment the remaining segments to understand how each layout manager works. 2 | import java.awt.*; 3 | import java.awt.event.*; 4 | public class LayoutManagerEx implements ActionListener { 5 | Frame f; 6 | TextField tf; 7 | Button b[] = new Button[3]; 8 | LayoutManagerEx(){ 9 | f = new Frame("ButtonExample"); 10 | 11 | b[0] = new Button("Yes"); 12 | b[1] = new Button("No"); 13 | b[2] = new Button("May Be"); 14 | 15 | f.add(b[0]); 16 | f.add(b[1]); 17 | f.add(b[2]); 18 | 19 | tf = new TextField(); 20 | tf.setBackground(Color.cyan); 21 | f.add(tf); 22 | 23 | 24 | // **************Manual Positioning********** 25 | for(int i = 0;i<3;i++) 26 | { 27 | b[i].setBounds(100,100+i*50,100,30); 28 | } 29 | 30 | tf.setBounds(100,250,200,30); 31 | f.setLayout(null); 32 | 33 | // **************Flow Layout*************** 34 | // f.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); 35 | // f.setLayout(new FlowLayout(FlowLayout.LEADING)); 36 | 37 | // ****************Grid Layout************* 38 | 39 | // f.setLayout(new GridLayout(2,2)); 40 | 41 | // ***************Border Layout************ 42 | 43 | // 44 | // f.setLayout(new BorderLayout()); 45 | // 46 | // f.add(b[0],BorderLayout.WEST); 47 | // f.add(b[1],BorderLayout.EAST); 48 | // f.add(b[2],BorderLayout.NORTH); 49 | // f.add(tf, BorderLayout.SOUTH); 50 | 51 | 52 | 53 | for(int i =0;i<3;i++) 54 | { 55 | b[i].addActionListener(this); 56 | } 57 | 58 | f.setSize(300,300); 59 | f.setVisible(true); 60 | 61 | 62 | } 63 | 64 | public void actionPerformed(ActionEvent e) 65 | { 66 | for (int j=0;j<3;j++) 67 | { 68 | if(e.getSource() == b[j]) 69 | tf.setText("Button Pressed: "+b[j].getLabel()); 70 | } 71 | } 72 | 73 | public static void main(String[] args) 74 | { 75 | new LayoutManagerEx(); 76 | } 77 | } 78 | 79 | -------------------------------------------------------------------------------- /CardLayoutEx.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | 4 | public class CardLayoutEx { 5 | String msg=""; 6 | TextField tf; 7 | CheckboxGroup type; 8 | CardLayoutEx() 9 | { 10 | Frame f = new Frame("Adapter Example"); 11 | f.setTitle("Banking Application"); 12 | f.setSize(500,500); 13 | f.setVisible(true); 14 | f.setLayout(new FlowLayout(FlowLayout.LEFT,100,15)); 15 | 16 | 17 | Label l1 = new Label("Name"); 18 | f.add(l1); 19 | 20 | tf = new TextField("Enter your name"); 21 | f.add(tf); 22 | 23 | Label l2 = new Label("Mode"); 24 | f.add(l2); 25 | 26 | type = new CheckboxGroup(); 27 | Checkbox net,debit; 28 | net = new Checkbox("Net Banking",type,true); 29 | debit = new Checkbox("Debit Card",type,false); 30 | f.add(net); 31 | f.add(debit); 32 | 33 | CardLayout cLo = new CardLayout(); 34 | Panel deck = new Panel(); 35 | deck.setLayout(cLo); 36 | Panel card1 = new Panel(); 37 | Panel card2 = new Panel(); 38 | 39 | Label l3 = new Label("User Name: "); 40 | TextField tf2 = new TextField(); 41 | Label l4 = new Label("Password "); 42 | TextField tf3 = new TextField(); 43 | tf3.setEchoChar('*'); 44 | card1.add(l3); 45 | card1.add(tf2); 46 | card1.add(l4); 47 | card1.add(tf3); 48 | 49 | Label l5 = new Label("Card No. "); 50 | TextField tf4 = new TextField(); 51 | Label l6 = new Label("cvv"); 52 | TextField tf5 = new TextField(""); 53 | 54 | card2.add(l5); 55 | card2.add(tf4); 56 | card2.add(l6); 57 | card2.add(tf5); 58 | 59 | deck.add(card1,"Net Banking"); 60 | deck.add(card2,"Debit Card"); 61 | 62 | f.add(deck); 63 | 64 | net.addItemListener(new ItemListener() { 65 | public void itemStateChanged(ItemEvent e) { 66 | cLo.show(deck,"Net Banking"); 67 | } 68 | }); 69 | 70 | debit.addItemListener(new ItemListener() { 71 | public void itemStateChanged(ItemEvent e) { 72 | cLo.show(deck,"Debit Card"); 73 | } 74 | }); 75 | 76 | 77 | 78 | } 79 | 80 | public static void main(String[] args) 81 | { 82 | new CardLayoutEx(); 83 | } 84 | 85 | } 86 | 87 | 88 | -------------------------------------------------------------------------------- /TestAccount.java: -------------------------------------------------------------------------------- 1 | /* Banking Application that demonstrates the use of Inheritance, Interfaces, Method Overriding and Dynamic Method Dispatch*/ 2 | 3 | import java.util.*; 4 | 5 | interface Bank{ 6 | void deposit(float amount); 7 | void withdraw(float amount); 8 | void deductFee(); 9 | } 10 | class BankAccount implements Bank{ 11 | private int acc; 12 | private String name; 13 | private float amount; 14 | 15 | BankAccount(int acc,String name,float amt){ 16 | this.acc = acc; 17 | this.name = name; 18 | this.amount = amt; 19 | } 20 | 21 | void setAcc(int acc) 22 | { 23 | this.acc = acc; 24 | } 25 | void setName(String name) 26 | { 27 | this.name = name; 28 | } 29 | float getBalance(){ 30 | return amount;} 31 | 32 | public void deposit(float amount) 33 | { 34 | this.amount = this.amount+amount; 35 | } 36 | 37 | public void withdraw(float amount) 38 | { 39 | if (this.amount < amount) 40 | System.out.println("Insufficient Funds. Withdrawal Failed"); 41 | else 42 | this.amount=this.amount-amount; 43 | } 44 | 45 | public void deductFee() 46 | { 47 | } 48 | } 49 | 50 | class CheckingAccount extends BankAccount implements Bank 51 | { 52 | private static final float TRANS_FEE = 25; 53 | private static final int FREE_TRANS = 2; 54 | private float TransCount =0; 55 | 56 | 57 | CheckingAccount(int acc,String name,float amt) 58 | { 59 | super(acc,name,amt); } 60 | 61 | public void deductFee() 62 | { 63 | if(TransCount > FREE_TRANS) 64 | {float fee = (TransCount-FREE_TRANS)*TRANS_FEE; 65 | super.withdraw(fee); 66 | TransCount=0;} 67 | } 68 | 69 | public void deposit(float amount) 70 | { 71 | TransCount++; 72 | super.deposit(amount); 73 | } 74 | public void withdraw(float amount) 75 | { 76 | TransCount++; 77 | super.withdraw(amount); 78 | } 79 | 80 | } 81 | class TestAccount{ 82 | public static void main(String[] args) { 83 | 84 | Scanner sr = new Scanner(System.in); 85 | 86 | System.out.println("Enter 1 for new customers (< 1 year) and 0 for others"); 87 | int yr = sr.nextInt(); 88 | 89 | 90 | BankAccount ba; 91 | if (yr==1) 92 | ba = new BankAccount(111,"Ankit",5000); 93 | else 94 | ba = new CheckingAccount(111,"Ankit",5000); 95 | 96 | 97 | System.out.println("Initial: "+ba.getBalance()); 98 | 99 | ba.deposit(1000); 100 | ba.withdraw(2000); 101 | ba.deposit(6000); 102 | System.out.println("After three Transactions: " + ba.getBalance()); 103 | 104 | ba.deductFee(); 105 | 106 | System.out.println("After fee Deduction: " + ba.getBalance()); 107 | sr.close(); 108 | 109 | }} 110 | 111 | -------------------------------------------------------------------------------- /StrategyPattern.java: -------------------------------------------------------------------------------- 1 | //Source: https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | interface PaymentStrategy { 7 | public void pay(int amount); 8 | } 9 | 10 | class CreditCardStrategy implements PaymentStrategy { 11 | private String name; 12 | private String cardNumber; 13 | private String cvv; 14 | private String dateOfExpiry; 15 | 16 | public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){ 17 | this.name=nm; 18 | this.cardNumber=ccNum; 19 | this.cvv=cvv; 20 | this.dateOfExpiry=expiryDate; 21 | } 22 | @Override 23 | public void pay(int amount) { 24 | System.out.println(amount +" paid with credit/debit card"); 25 | } 26 | 27 | } 28 | 29 | class PaypalStrategy implements PaymentStrategy { 30 | 31 | private String emailId; 32 | private String password; 33 | 34 | public PaypalStrategy(String email, String pwd){ 35 | this.emailId=email; 36 | this.password=pwd; 37 | } 38 | 39 | @Override 40 | public void pay(int amount) { 41 | System.out.println(amount + " paid using Paypal."); 42 | } 43 | 44 | } 45 | 46 | class Item { 47 | 48 | private String upcCode; 49 | private int price; 50 | 51 | public Item(String upc, int cost){ 52 | this.upcCode=upc; 53 | this.price=cost; 54 | } 55 | 56 | public String getUpcCode() { 57 | return upcCode; 58 | } 59 | 60 | public int getPrice() { 61 | return price; 62 | } 63 | 64 | } 65 | 66 | class ShoppingCart { 67 | 68 | //List of items 69 | List items; 70 | 71 | public ShoppingCart(){ 72 | this.items=new ArrayList(); 73 | } 74 | 75 | public void addItem(Item item){ 76 | this.items.add(item); 77 | } 78 | 79 | public void removeItem(Item item){ 80 | this.items.remove(item); 81 | } 82 | 83 | public int calculateTotal(){ 84 | int sum = 0; 85 | for(Item item : items){ 86 | sum += item.getPrice(); 87 | } 88 | return sum; 89 | } 90 | 91 | public void pay(PaymentStrategy paymentMethod){ 92 | int amount = calculateTotal(); 93 | paymentMethod.pay(amount); 94 | } 95 | } 96 | 97 | class StrategyPattern { 98 | 99 | public static void main(String[] args) { 100 | ShoppingCart cart = new ShoppingCart(); 101 | 102 | Item item1 = new Item("1234",10); 103 | Item item2 = new Item("5678",40); 104 | 105 | cart.addItem(item1); 106 | cart.addItem(item2); 107 | 108 | //pay by paypal 109 | cart.pay(new PaypalStrategy("myemail@example.com", "mypwd")); 110 | 111 | //pay by credit card 112 | cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15")); 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /AdapterPatternDemo.java: -------------------------------------------------------------------------------- 1 | //All interfaces and classes should be declared as public and should be created in a separate file. 2 | interface MediaPlayer { 3 | public void play(String audioType, String fileName); 4 | } 5 | 6 | 7 | interface AdvancedMediaPlayer { 8 | public void playVlc(String fileName); 9 | public void playMp4(String fileName); 10 | } 11 | 12 | class VlcPlayer implements AdvancedMediaPlayer{ 13 | public void playVlc(String fileName) { 14 | System.out.println("Playing vlc file. Name: "+ fileName); 15 | } 16 | 17 | public void playMp4(String fileName) { 18 | //do nothing 19 | } 20 | } 21 | 22 | 23 | class Mp4Player implements AdvancedMediaPlayer{ 24 | 25 | @Override 26 | public void playVlc(String fileName) { 27 | //do nothing 28 | } 29 | 30 | @Override 31 | public void playMp4(String fileName) { 32 | System.out.println("Playing mp4 file. Name: "+ fileName); 33 | } 34 | } 35 | 36 | class MediaAdapter implements MediaPlayer { 37 | 38 | AdvancedMediaPlayer advancedMusicPlayer; 39 | 40 | public MediaAdapter(String audioType){ 41 | 42 | if(audioType.equalsIgnoreCase("vlc") ){ 43 | advancedMusicPlayer = new VlcPlayer(); 44 | 45 | }else if (audioType.equalsIgnoreCase("mp4")){ 46 | advancedMusicPlayer = new Mp4Player(); 47 | } 48 | } 49 | 50 | @Override 51 | public void play(String audioType, String fileName) { 52 | 53 | if(audioType.equalsIgnoreCase("vlc")){ 54 | advancedMusicPlayer.playVlc(fileName); 55 | } 56 | else if(audioType.equalsIgnoreCase("mp4")){ 57 | advancedMusicPlayer.playMp4(fileName); 58 | } 59 | } 60 | } 61 | 62 | class AudioPlayer implements MediaPlayer { 63 | MediaAdapter mediaAdapter; 64 | 65 | @Override 66 | public void play(String audioType, String fileName) { 67 | 68 | //inbuilt support to play mp3 music files 69 | if(audioType.equalsIgnoreCase("mp3")){ 70 | System.out.println("Playing mp3 file. Name: " + fileName); 71 | } 72 | 73 | //mediaAdapter is providing support to play other file formats 74 | else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){ 75 | mediaAdapter = new MediaAdapter(audioType); 76 | mediaAdapter.play(audioType, fileName); 77 | } 78 | 79 | else{ 80 | System.out.println("Invalid media. " + audioType + " format not supported"); 81 | } 82 | } 83 | } 84 | 85 | public class AdapterPatternDemo { 86 | public static void main(String[] args) { 87 | AudioPlayer audioPlayer = new AudioPlayer(); 88 | 89 | audioPlayer.play("mp3", "beyond the horizon.mp3"); 90 | audioPlayer.play("mp4", "alone.mp4"); 91 | audioPlayer.play("vlc", "far far away.vlc"); 92 | audioPlayer.play("avi", "mind me.avi"); 93 | } 94 | } 95 | 96 | -------------------------------------------------------------------------------- /LibraryApplication.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | interface Search{ 4 | public static > int binarySearch(List list, T key,int low, int high) 5 | { 6 | int mid; 7 | 8 | 9 | if (key==null) { 10 | System.out.println("No such book found"); 11 | return -1; 12 | } 13 | if (low>high){ 14 | System.out.println("No such book found"); 15 | return -1; 16 | } 17 | mid = low+(high-low)/2; 18 | if( list.get(mid).compareTo(key) > 0 ) 19 | return binarySearch(list, key, mid+1, high); 20 | else if(list.get(mid).compareTo(key) < 0 ) 21 | return binarySearch( list, key, low, mid-1 ); 22 | else 23 | return mid; 24 | } 25 | 26 | @SuppressWarnings("rawtypes") 27 | static ArrayList split (List list,int code) 28 | { 29 | if (code==0) 30 | { 31 | ArrayList al1 = new ArrayList(); 32 | for (Library i: list) 33 | al1.add(i.bookID); 34 | return al1; 35 | } 36 | if (code==1) 37 | { 38 | ArrayList al2 = new ArrayList(); 39 | for (Library i: list) 40 | al2.add(i.bookName); 41 | return al2; 42 | } 43 | return null; 44 | } 45 | } 46 | 47 | class Library implements Search{ 48 | 49 | String bookName; 50 | int bookID; 51 | String rackNo; 52 | 53 | Library(String name, int id,String num){ 54 | bookName = name; 55 | bookID = id; 56 | rackNo = num; 57 | } 58 | public String toString() { 59 | return "Name: "+bookName+" ID: "+bookID+" Rack No.: "+rackNo; 60 | } 61 | } 62 | 63 | class LibraryApplication{ 64 | 65 | @SuppressWarnings("unchecked") 66 | public static void main(String args[]){ 67 | 68 | int index; 69 | ArrayList al = new ArrayList(); 70 | al.add(new Library("Java",19532,"A2")); 71 | al.add(new Library("C++",17888,"F1")); 72 | al.add(new Library("IoT",242537,"B6")); 73 | al.add(new Library("DIP",347888,"E8")); 74 | 75 | 76 | Collections.sort(al,new Comparator(){ 77 | public int compare(Library l1, Library l2) { 78 | if (l1.bookID==l2.bookID) 79 | return 0; 80 | else if(l1.bookID I = new ArrayList(); 89 | I = Search.split(al,0); 90 | System.out.println(I); 91 | index = Search.binarySearch(I,19532,0,al.size()-1); 92 | 93 | if (index!=-1) 94 | System.out.println(al.get(index)); 95 | 96 | Collections.sort(al,new Comparator(){ 97 | public int compare(Library l1, Library l2) { 98 | return l2.bookName.compareTo(l1.bookName); 99 | } 100 | }); 101 | 102 | 103 | ArrayList S = new ArrayList(); 104 | S = Search.split(al,1); 105 | index = Search.binarySearch(S,"C++",0,al.size()-1); 106 | if (index!=-1) 107 | System.out.println(al.get(index)); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /BankApplicationAWT.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | import java.text.*; 4 | public class BankApplicationAWT implements ItemListener,ActionListener{ 5 | String msg=""; 6 | TextField tf; 7 | CheckboxGroup gender; 8 | Choice state; 9 | double pchange,interest; 10 | Label l5,l6; 11 | Frame f; 12 | BankApplicationAWT() 13 | { 14 | f = new Frame("Adapter Example"); 15 | f.setTitle("Banking Application"); 16 | f.setSize(500,500); 17 | f.setVisible(true); 18 | f.setLayout(new FlowLayout(FlowLayout.LEFT,100,25)); 19 | 20 | Label l1 = new Label("Name"); 21 | f.add(l1); 22 | 23 | tf = new TextField("Enter your name"); 24 | f.add(tf); 25 | 26 | Label l2 = new Label("Gender"); 27 | f.add(l2); 28 | 29 | gender = new CheckboxGroup(); 30 | Checkbox male,female; 31 | male = new Checkbox("Male",gender,false); 32 | female = new Checkbox("Female",gender,false); 33 | f.add(male); 34 | f.add(female); 35 | 36 | Label l3 = new Label("State"); 37 | f.add(l3); 38 | 39 | state = new Choice(); 40 | state.add("None"); 41 | state.add("Rajasthan"); 42 | state.add("Haryana"); 43 | state.add("Andhra"); 44 | state.add("TamilNadu"); 45 | f.add(state); 46 | 47 | Label l4 = new Label("Interest Rate"); 48 | f.add(l4); 49 | 50 | l5 = new Label("0.0"); 51 | f.add(l5); 52 | l6 = new Label(msg); 53 | f.add(l6); 54 | Button b1 = new Button("Find Interest"); 55 | f.add(b1); 56 | 57 | male.addItemListener(this); 58 | female.addItemListener(this); 59 | state.addItemListener(this); 60 | b1.addActionListener(this); 61 | } 62 | 63 | public static void main(String[] args) 64 | { 65 | new BankApplicationAWT(); 66 | } 67 | 68 | public void itemStateChanged(ItemEvent e) { 69 | 70 | if (gender.getSelectedCheckbox().getLabel().equals("Female")) 71 | pchange = 0.8; 72 | else 73 | pchange = 1; 74 | } 75 | 76 | public void actionPerformed(ActionEvent e) { 77 | 78 | switch(state.getSelectedIndex()) 79 | { 80 | case 1: interest = 10.25; break; 81 | case 2: interest = 9.25; break; 82 | case 3: interest = 9; break; 83 | case 4: interest = 9.75; break; 84 | } 85 | 86 | DecimalFormat dec = new DecimalFormat("#0.00"); 87 | l5.setText(dec.format(interest*pchange)); 88 | // l5.setText(String.format("%.2f", interest*pchange)); 89 | // l5.setText(Double.toString(interest*pchange)); 90 | 91 | msg+="The interest rate for "; 92 | msg+=tf.getText() +"(" + gender.getSelectedCheckbox().getLabel()+") from" + state.getSelectedItem() +" is: "+l5.getText(); 93 | l6.setText(msg); 94 | msg=""; 95 | 96 | } 97 | 98 | public void paint(Graphics g) { 99 | g.drawString(msg, 450,50); 100 | msg=""; 101 | } 102 | } 103 | 104 | -------------------------------------------------------------------------------- /AbstractFactoryEx.java: -------------------------------------------------------------------------------- 1 | import javax.swing.JOptionPane; 2 | 3 | 4 | class BankAccount { 5 | protected final double timePeriod = 0.5; 6 | protected double rateOfInterest=0; 7 | public double calculateInterest(double principle) { 8 | double interest = (principle * rateOfInterest * timePeriod)/100; 9 | return interest; 10 | } 11 | } 12 | 13 | class SavingAccount extends BankAccount{ 14 | SavingAccount(){ 15 | rateOfInterest = 4.0; 16 | } 17 | } 18 | 19 | class CurrentAccount extends BankAccount{ 20 | CurrentAccount(){ 21 | rateOfInterest = 3.5; 22 | } 23 | } 24 | 25 | class SweepInAccount extends BankAccount{ 26 | SweepInAccount(){ 27 | rateOfInterest = 8.25; 28 | } 29 | 30 | } 31 | 32 | abstract class AbstractFactory { 33 | abstract BankAccount getAccountInstance(String accType); 34 | abstract BankName getBankInstance(String bankType) ; 35 | } 36 | class AccountFactory extends AbstractFactory { 37 | 38 | BankAccount getAccountInstance(String accType){ 39 | 40 | if(accType.equals("current")) 41 | return new CurrentAccount(); 42 | else if(accType.equals("savings")) 43 | return new SavingAccount(); 44 | else if(accType.equals("sweep")) 45 | return new SweepInAccount(); 46 | else 47 | return null; 48 | 49 | } 50 | 51 | @Override 52 | BankName getBankInstance(String bankType) { 53 | return null; 54 | } 55 | } 56 | 57 | class BankName{ 58 | protected String Name = null; 59 | 60 | public String getName() { 61 | return Name;} 62 | } 63 | 64 | class YesBank extends BankName 65 | { 66 | YesBank(){ 67 | Name = "YES BANK"; 68 | } 69 | } 70 | 71 | class SBI extends BankName 72 | { 73 | SBI(){ 74 | Name = "SBI"; 75 | } 76 | } 77 | 78 | class BankFactory extends AbstractFactory{ 79 | BankName getBankInstance(String bankType) { 80 | if(bankType.equals("sbi")) 81 | return new SBI(); 82 | else if (bankType.equals("yes bank")) 83 | return new YesBank(); 84 | else 85 | return null; 86 | } 87 | 88 | @Override 89 | BankAccount getAccountInstance(String accType) { 90 | return null; 91 | } 92 | } 93 | 94 | class FactoryProducer { 95 | public static AbstractFactory getFactory(String choice){ 96 | 97 | if(choice.equalsIgnoreCase("account")){ 98 | return new AccountFactory(); 99 | 100 | }else if(choice.equalsIgnoreCase("bank")){ 101 | return new BankFactory(); 102 | } 103 | 104 | return null; 105 | } 106 | } 107 | 108 | public class AbstractFactoryEx { 109 | 110 | public static void main(String[] args){ 111 | 112 | String accType, bankType; 113 | double amount; 114 | double interest; 115 | BankAccount baAbstract = null; 116 | BankName bnAbstract = null; 117 | 118 | bankType = JOptionPane.showInputDialog("Enter the Bank Name"); 119 | accType = JOptionPane.showInputDialog("Enter the account type"); 120 | amount = Double.parseDouble((JOptionPane.showInputDialog("Enter the amount"))); 121 | 122 | AbstractFactory bankFactory = FactoryProducer.getFactory("bank"); 123 | bnAbstract = bankFactory.getBankInstance(bankType); 124 | bankFactory = FactoryProducer.getFactory("account"); 125 | baAbstract = bankFactory.getAccountInstance(accType); 126 | interest = baAbstract.calculateInterest(amount); 127 | 128 | System.out.println(interest); 129 | System.out.println(bnAbstract.Name); 130 | 131 | JOptionPane.showConfirmDialog(null, "For "+bnAbstract.getName()+" Interest is: "+ interest); 132 | System.exit(0); 133 | 134 | } 135 | } 136 | 137 | -------------------------------------------------------------------------------- /IteratorPattern.java: -------------------------------------------------------------------------------- 1 | //Source: https://www.journaldev.com/1716/iterator-design-pattern-java 2 | import java.util.*; 3 | 4 | enum ChannelTypeEnum { 5 | 6 | ENGLISH, HINDI, FRENCH, ALL; 7 | } 8 | 9 | class Channel { 10 | 11 | private double frequency; 12 | private ChannelTypeEnum TYPE; 13 | 14 | public Channel(double freq, ChannelTypeEnum type){ 15 | frequency=freq; 16 | TYPE=type; 17 | } 18 | 19 | public double getFrequency() { 20 | return frequency; 21 | } 22 | 23 | public ChannelTypeEnum getTYPE() { 24 | return TYPE; 25 | } 26 | 27 | @Override 28 | public String toString(){ 29 | return "Frequency="+frequency+", Type="+TYPE; 30 | } 31 | 32 | } 33 | 34 | 35 | interface ChannelCollection { 36 | 37 | public void addChannel(Channel c); 38 | 39 | public void removeChannel(Channel c); 40 | 41 | public ChannelIterator iterator(ChannelTypeEnum type); 42 | 43 | } 44 | 45 | 46 | 47 | 48 | class ChannelCollectionImpl implements ChannelCollection { 49 | 50 | private List channelsList; 51 | 52 | public ChannelCollectionImpl() { 53 | channelsList = new ArrayList<>(); 54 | } 55 | 56 | public void addChannel(Channel c) { 57 | channelsList.add(c); 58 | } 59 | 60 | public void removeChannel(Channel c) { 61 | channelsList.remove(c); 62 | } 63 | 64 | @Override 65 | public ChannelIterator iterator(ChannelTypeEnum type) { 66 | return new ChannelIteratorImpl(type, channelsList); 67 | } 68 | 69 | private class ChannelIteratorImpl implements ChannelIterator { 70 | 71 | private ChannelTypeEnum type; 72 | private List channels; 73 | private int position; 74 | 75 | public ChannelIteratorImpl(ChannelTypeEnum ty, List channelsList) { 76 | type = ty; 77 | channels = channelsList; 78 | } 79 | 80 | @Override 81 | public boolean hasNext() { 82 | while (position < channels.size()) { 83 | Channel c = channels.get(position); 84 | if (c.getTYPE().equals(type) || type.equals(ChannelTypeEnum.ALL)) { 85 | return true; 86 | } else 87 | position++; 88 | } 89 | return false; 90 | } 91 | 92 | @Override 93 | public Channel next() { 94 | Channel c = channels.get(position); 95 | position++; 96 | return c; 97 | } 98 | 99 | } 100 | } 101 | 102 | class IteratorPattern { 103 | 104 | public static void main(String[] args) { 105 | ChannelCollection channels = populateChannels(); 106 | ChannelIterator baseIterator = channels.iterator(ChannelTypeEnum.ALL); 107 | while (baseIterator.hasNext()) { 108 | Channel c = baseIterator.next(); 109 | System.out.println(c.toString()); 110 | } 111 | System.out.println("******"); 112 | // Channel Type Iterator 113 | ChannelIterator englishIterator = channels.iterator(ChannelTypeEnum.FRENCH); 114 | while (englishIterator.hasNext()) { 115 | Channel c = englishIterator.next(); 116 | System.out.println(c.toString()); 117 | } 118 | } 119 | 120 | private static ChannelCollection populateChannels() { 121 | ChannelCollection channels = new ChannelCollectionImpl(); 122 | channels.addChannel(new Channel(98.5, ChannelTypeEnum.ENGLISH)); 123 | channels.addChannel(new Channel(99.5, ChannelTypeEnum.HINDI)); 124 | channels.addChannel(new Channel(100.5, ChannelTypeEnum.FRENCH)); 125 | channels.addChannel(new Channel(101.5, ChannelTypeEnum.ENGLISH)); 126 | channels.addChannel(new Channel(102.5, ChannelTypeEnum.HINDI)); 127 | channels.addChannel(new Channel(103.5, ChannelTypeEnum.FRENCH)); 128 | channels.addChannel(new Channel(104.5, ChannelTypeEnum.ENGLISH)); 129 | channels.addChannel(new Channel(105.5, ChannelTypeEnum.HINDI)); 130 | channels.addChannel(new Channel(106.5, ChannelTypeEnum.FRENCH)); 131 | return channels; 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------