Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Creating a table of data in Java using Swing

// Creating a table of records using java (Swing)
import java.awt.*;
import javax.swing.*;
/*
 * applet code="jtable" width=400 height=200>
 * </applet>
 */
public class jtable extends JApplet
{
    public void init()
    {
        Container contentPane=getContentPane();
        contentPane.setLayout(new BorderLayout());
        final String[] colHeads={"NAME","CONTACT","HOUSE_NO"};
        final Object[][] data={

                                         {"JOHN","2368","8718"},
                                         {"KEVIN","9898","71U2"},
                                         {"MATT","9893","6769"},
                                         {"ANDREW","9812","5687"},
                                         {"MICHAEL","4542","1234"},
                                         {"JONATHAN","9933","3513"}

                                        };
       

        JTable table=new JTable(data,colHeads);
        int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
        int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
        JScrollPane jp=new JScrollPane(table,v,h);
        contentPane.add(jp,BorderLayout.CENTER);
    }
} 
 
                     

Binary Search Tree in Java

    /* Program to implement search function, count nodes function and three traversal functions of a binary tree using recursion */

      import java.io.*;
    class TreeNode
    {
        TreeNode left,right;
        int data;
        public TreeNode()
        {
            data=0;
            left=right=null;
        }
        public TreeNode(int n)
        {
            data=n;
            left=right=null;
        }
        public void disp()
        {
            System.out.println(data + " ");
        }
        public TreeNode getleft()
        {
            return left;
        }
        public TreeNode getright()
        {
            return right;
        }
        public void setdata(int d)
        {
            data=d;
        }
        public int getdata()
        {
            return data;
        }
    }
   
    class BinaryTree
    {
        TreeNode root;
        public BinaryTree()
        {
            root=null;
        }
        public int countnodes()
        {
            return countnodes(root);
        }
        private int countnodes(TreeNode r)
        {
            if(r==null)
                return 0;
            else
            {
                int l=1;
                l=l+countnodes(r.getleft());
                l=l+countnodes(r.getright());
                return l;
            }
        }
        public boolean search(int value)
        {
            return search(root,value);
        }
        private boolean search(TreeNode r,int val)
        {
            boolean found=false;
            while((r!=null) && !found)
            {
                int rval=r.getdata();
                if(val < rval)
                    r=r.getleft();
                else if(val > rval)
                    r=r.getright();
                else
                {
                    found=true;
                    break;
                }
                found=search(r,val);
            }
            return found;
        }
        public void inoder()
        {
            inorder(root);
        }
        private void inorder(TreeNode r)
        {
            if(r!=null)
            {
                inorder(r.getleft());
                System.out.print(r.getdata() + "  ");
                inorder(r.getright());
            }
        }
        public void preoder()
        {
            preorder(root);
        }
        private void preorder(TreeNode r)
        {
            if(r!=null)
            {
                System.out.print(r.getdata() + "  ");
                preorder(r.getleft());               
                preorder(r.getright());
            }
        }
        public void postoder()
        {
            postorder(root);
        }
        private void postorder(TreeNode r)
        {
            if(r!=null)
            {
                postorder(r.getleft());               
                postorder(r.getright());
                System.out.print(r.getdata() + "  ");
            }
        }
    }

    class bttest
    {
        protected static BinaryTree bt;       
        public static void main(String args[])
        {
            int val;
            bt=new BinaryTree();
            System.out.println("\nPost order traversal of the tree is :  ");
            bt.postorder(); 
            System.out.println("\nPre order traversal of the tree is :  ");
            bt.preorder(); 
            System.out.println("\nInorder order traversal of the tree is :  ");
            bt.inorder();
            int l=bt.countnodes();
            System.out.println("\nNo. of nodes : " +l);
            try
            {
                System.out.println("\nEnter search item : ");
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                val=Integer.parseInt(br.readLine());
                if(bt.search(val))
                    System.out.println("Item exists in the tree");
                else
                    System.out.println("Item does not exist in the tree");
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
            System.out.println("\n");
        }
    } 

Drawing Ellipses and Ovals in Java Applet

import java.awt.*;
import java.applet.*;
/*
 * 
 * 
 */
public class ellipses extends Applet
{
    public void paint(Graphics g)
    {
        g.drawOval(10,10,50,50);
        g.fillOval(100,10,75,50);
        g.drawOval(190,10,90,30);
        g.fillOval(70,90,140,100);
    }
}



Notepad Application in Java

/* This is a classic notepad application program created in Java which can be used like any other text editor  */ 

import java.io.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.*;
public class Notepad extends Frame
{
    Clipboard cBoard=getToolkit().getSystemClipboard(); // graphical interface of the notepad
    TextArea tArea=new TextArea();   // textarea of the notepad
    String fName; // text file name
    Notepad()    // default constructor
    {
        gaListener gListen=new gaListener();
        addWindowListener(gListen);
        add(tArea);
        MenuBar mBar=new MenuBar();     // creating the menu bar
        Menu fileMenu=new Menu("File"); // creating "File" option for menu bar
       
        MenuItem nOption=new MenuItem("New"); // initializing elements under "File" option
        MenuItem oOption=new MenuItem("Open");
        MenuItem sOption=new MenuItem("Save");
        MenuItem cOption=new MenuItem("Close");
       
        nOption.addActionListener(new Ne_option());   // adding the elements under "File" option
        fileMenu.add(nOption);
        oOption.addActionListener(new Ope_option());
        fileMenu.add(oOption);
        sOption.addActionListener(new Sav_option());
        fileMenu.add(sOption);
        cOption.addActionListener(new Clos_option());
        fileMenu.add(cOption);
        mBar.add(fileMenu);         // adding the "File" menu into the menu bar
       
        Menu editMenu=new Menu("Edit");         // creating the "Edit" option for menu bar
        MenuItem cutOption=new MenuItem("Cut"); // initializing elements under "Edit" option
        MenuItem copyOption=new MenuItem("Copy");
        MenuItem pasteOption=new MenuItem("Paste");
       
        cutOption.addActionListener(new Cu_option());// adding the elements under "Edit" option
        editMenu.add(cutOption);
        copyOption.addActionListener(new Cop_option());
        editMenu.add(copyOption);
        pasteOption.addActionListener(new Past_option());
        editMenu.add(pasteOption);
        mBar.add(editMenu);         // adding the "Edit" menu into menu bar
        setMenuBar(mBar);           // finalizing the menu bar
       
        setTitle("NOTEPAD IN JAVA");      // title displayed on top of the notepad
    }
   
    class gaListener extends WindowAdapter
    {
        public void windowClosing(WindowEvent closeNotepad)
        {
            System.exit(0);  // function for closing the notepad
        }
    }
   
    class Ne_option implements ActionListener  // class for "New"
    {
        public void actionPerformed(ActionEvent ne)
        {
            tArea.setText(" ");   // the notepad becomes empty when user click on "New"
        }
    }
   
    class Ope_option implements ActionListener  // class for "Open"
    {
        public void actionPerformed (ActionEvent ope)
        {
            FileDialog fDialog=new FileDialog(Notepad.this,"Select a text file",FileDialog.LOAD);
            fDialog.show(); // a message "Select a text file" is displayed when user clicks on "Open"
            if(fDialog.getFile()!=null)  // if text files exist in the directory
            {
                fName=fDialog.getDirectory()+fDialog.getFile(); // retrieving the text file from the directory
                setTitle(fName);  // title changes to name of the opened text file(if found)
                ReadFile();
            }
            tArea.requestFocus();
        }
    }
   
    class Clos_option implements ActionListener     //class for "Close"
    {
        public void actionPerformed(ActionEvent close_o)
        {
            System.exit(0);
        }
    }
   
    class Sav_option implements ActionListener
    {
        public void actionPerformed(ActionEvent sav_o)
        {
            FileDialog fDialog=new FileDialog(Notepad.this,"Save the text file with .txt extension",FileDialog.SAVE);
            fDialog.show();     // a message "Save the text file with .txt extension" is displayed when user clicks on "Save"
            if(fDialog.getFile()!=null)
            {
                fName=fDialog.getDirectory()+fDialog.getFile();
                setTitle(fName); // title changes to saved filename's
                try
                {
                    DataOutputStream dOutStream=new DataOutputStream(new FileOutputStream(fName));
                    String oLine=tArea.getText();
                    BufferedReader bReader=new BufferedReader(new StringReader(oLine));
                    while((oLine=bReader.readLine())!=null);
                    {
                        dOutStream.writeBytes(oLine+"\r\n");
                        dOutStream.close();
                    }
                }
                catch(Exception e)
                {
                        System.out.println("Required file not found");
                }
                tArea.requestFocus();
            }
        }
    }
   
    void ReadFile()  // function for reading the file
    {
        BufferedReader br;
        StringBuffer sBuffer=new StringBuffer();
        try
        {
            br=new BufferedReader(new FileReader(fName));
            String oLine;
            while((oLine=br.readLine())!=null)
                sBuffer.append(oLine+"\n");
                tArea.setText(sBuffer.toString());
                br.close();
        }
        catch(FileNotFoundException fe)
        {
            System.out.println("Required file not found");
        }
        catch(IOException e){}
    }
   
    class Cu_option implements ActionListener   // class for "Cut" option
    {
        public void actionPerformed(ActionEvent cut_o)
        {
            String sText=tArea.getSelectedText();
            StringSelection sSelection=new StringSelection(sText);
            cBoard.setContents(sSelection,sSelection);
            tArea.replaceRange(" ",tArea.getSelectionStart(),tArea.getSelectionEnd());  // highlighted text relaced by blank space
        }
    }
   
    class Cop_option implements ActionListener  // class for "Copy" option
    {
        public void actionPerformed(ActionEvent copy_o)
        {
            String sText=tArea.getSelectedText();
            StringSelection cString=new StringSelection(sText);
            cBoard.setContents(cString,cString);
        }
    }
   
    class Past_option implements ActionListener  // class for "Paste" option
    {
        public void actionPerformed(ActionEvent paste_o)
        {
            Transferable ctransfer=cBoard.getContents(Notepad.this);
            try
            {
                String sText=(String)ctransfer.getTransferData(DataFlavor.stringFlavor);
                tArea.replaceRange(sText,tArea.getSelectionStart(),tArea.getSelectionEnd());
            }
            catch(Exception e)
            {
                System.out.println("Not a string flavor");
            }
        }
    }
   
    public static void main(String args[])
    {
        Frame nFrame=new Notepad(); // creating object of the notepad
        nFrame.setSize(600,600);  // height=600 , width = 600
        nFrame.setVisible(true);
    }
}

Concatenation of two Linked Lists in java

import java.io.*;
class node
{
    protected int data;
    protected node link;
    public node()             // default constructor
    {
        data=0;
        link=null;
    }
    public node(int d,node n)         // parametrized constructor
    {
        data=d;
        link=n;
    }
    public void setlink(node n)  // stores passed reference in link part
    {
        link=n;
    }
    public void setdata(int d)   // stores passed value in data part
    {
        data=d;
    }
    public node getlink()       // returns the link part
    {
        return link;
    }
    public int getdata()     // returns the data part
    {
        return data;
    }
}
class linkedlist
{
    protected node start;
    public linkedlist()
    {
        start=null;
    }
    public boolean isempty()
    {
         return start==null;
    }
    public void insert(int val)  // insert a node in list pointed by start
    {
        node nptr,ptr,save=null;
        nptr=new node(val,null);
        boolean ins=false;
        if(start==null)
            start=nptr;
        else if(val<=start.getdata()) // insert in the beginning
        {
            nptr.setlink(start);    // set nptr i.e new node's link to start
            start=nptr;
        }
        else
        {
            save=start;          // insert in the middle or end of list
            ptr=start.getlink();
            while(ptr!=null)
            {
                if(val>=save.getdata() && val<=ptr.getdata())
                {
                    save.setlink(nptr);
                    nptr.setlink(ptr);
                    ins=true;
                    break;
                }
                else
                {
                    save=ptr;
                    ptr=ptr.getlink();
                }
            }
            if(ins==false)     // case of insertion in the end
                save.setlink(nptr);
        }
    }
    public void traverse()
    {
        node ptr=start;

        System.out.println();
        System.out.print(start.getdata()+ " --> ");
        ptr=start.getlink();
        while(ptr.getlink()!=null)
        {
            System.out.print(ptr.getdata()+ " --> ");
            ptr=ptr.getlink();
        }
        System.out.print(ptr.getdata()+"!!!");   // last node's info
        System.out.println();
    }
    public void concat(node l2)  // concatenation function
    {
        node ptr,save=null;
        save=ptr=start;
        while(ptr!=null)
        {
            save=ptr;
            ptr=ptr.getlink();
        }
        save.setlink(l2);
    }
}
class linkjava1
{
    protected static linkedlist l1,l2;
    public static void main(String args[])
    {
        int num;
        l1=new linkedlist();
        l2=new linkedlist();
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("....Starting Linked list for concatenation...");
        System.out.println("....Enter 7 integers for list 1....");
        for(int a=0;a<7;a++)
        {
            try
            {
                num=Integer.parseInt(br.readLine());
                l1.insert(num);
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }
        System.out.println("\nList one : ");
        l1.traverse();
        System.out.println("....Enter 5 integers for list 2....");
        for(int a=0;a<5;a++)
        {
            try
            {
                num=Integer.parseInt(br.readLine());
                l2.insert(num);
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }
        System.out.println("\nList two : ");
        l2.traverse();   
        l1.concat(l2.start);
        System.out.println("\nConcatenated list : ");
        l1.traverse();
    }
}   

Array Stack using interface in Java

/*  Stack using interface  */

    import java.io.*;
    interface stack
    {
        void push(int val);
        void pop();
        void display();
        void check();
    }
    class stacktest implements stack
    {
        int top,a[],n;
        stacktest(int cap)
        {
            n=cap;
            top=-1;
            a=new int[n];
        }
        public void push(int val)
        {
            if(top==n-1)
                System.out.println("\nStack overflow .... \n");
            else
                a[++top]=val;
        }
        public void pop()
        {
            int r;
            if(top==-1)
                System.out.println("\nStack underflow...\n");
            else
            {           
                r=a[top--];
                System.out.println("\nDeleted Element : " + r + "\n");
            }
        }
        public void display()
        {
            if(top==-1)
                System.out.println("\nStack Underflow .... \n");
            else
            {
                System.out.print("Stack : ");
                for(int i=top;i>=0;i--)
                    System.out.print(a[i] + "   ");
                System.out.println();
            }
        }
        public void check()
        {
            if(top==-1)
                System.out.println("\nStack empty... no element in stack....");
            else if(top==n-1)
                System.out.println("\nStack full.... no empty space...");
            else
            {
                int s=top+1;
                System.out.println("\nStack contains " + s + " elements");
            }
        }
    }
    class interstack
    {
        public static void main(String args[])throws IOException
        {
            System.out.println("\nProgram to implement stack using interface ");
            int ch,n,val;
            System.out.println("Enter array capacity : ");
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            n=Integer.parseInt(br.readLine());
            stacktest obj=new stacktest(n);
            do
            {
            System.out.println("[1] Push [2] Pop [3] Display [4] Check stack status [5] Exit \n");
            System.out.println("Enter choice : ");
            ch=Integer.parseInt(br.readLine());
            switch(ch)
            {
                case 1:
                    System.out.println("Enter value to push : ");
                    val=Integer.parseInt(br.readLine());
                    obj.push(val);
                    obj.display();
                    break;
           
                case 2:
                    obj.pop();
                    obj.display();
                    break;
                       
                case 3:
                    obj.display();
                    break;
   
                case 4:
                    obj.check();
                    break;

                case 5:    break;

                default :
                        System.out.println("Enter correct choice..");
                        break;
            }
            }while(ch!=5);
        }
    }

Use of Threads in Java - An Illustration

class newthread extends Thread
    {
        newthread()
        {
            super("Demo Thread");
        }
        public void run()
        {
            try
            {
                for(int i=5;i>0;i--)
                {
                    System.out.println("Child Thread : " +i);
                    Thread.sleep(500);
                }
            }
            catch(InterruptedException e)
            {
                System.out.println("Child Interrupted ");
                System.out.println("Child Exiting");
            }
        }
    }
    public class testthread
    {
        public static void main(String args[])
        {
            newthread nt1=new newthread();
            newthread nt2=new newthread();
            newthread nt3=new newthread();
            nt1.setPriority(3);
            nt1.start();
            nt2.setPriority(5);
            nt2.start();
            nt3.setPriority(7);
            nt3.start();
            try
            {
                for(int i=5;i>0;i--)
                {
                    System.out.println("Main Thread :" + i);
                    Thread.sleep(1000);
                }
            }
            catch(InterruptedException e)
            {
                System.out.println("Main Interrupted");
                System.out.println("Main Exiting");
            }
            System.out.println("Priority of Thread 1 : "+nt1.getPriority());
            System.out.println("Priority of Thread 2 : "+nt2.getPriority());
            System.out.println("Priority of Thread 3 : "+nt3.getPriority());
        }
    }



Output :

Child Thread : 5
Child Thread : 5
Main Thread :5
Child Thread : 5
Child Thread : 4
Child Thread : 4
Child Thread : 4
Child Thread : 3
Child Thread : 3
Main Thread :4
Child Thread : 3
Child Thread : 2
Child Thread : 2
Child Thread : 2
Main Thread :3
Child Thread : 1
Child Thread : 1
Child Thread : 1
Main Thread :2
Main Thread :1
Priority of Thread 1 : 3
Priority of Thread 2 : 5
Priority of Thread 3 : 7 

Creating packages and derived classes in Java : An illustration

This program is a simple illustration of creating packages in Java and derived classes within the same package.

A package in Java can be defined as a directory which contains a group of Java class files. The main advantage of this method is that any no. of derived classes can be created within the same package.

Below is a program which uses packages to show the details of an employee.

Package 1: Office

In the office directory there are two Java files - emp.java & dept.java

emp.java


    package office;
    public class emp
    {
        public String name,address,acc_no;
        public emp(String nm,String add,String acc_no2)
        {
            name=nm;
            address=add;
            acc_no=acc_no2;
        }
    }


dept.java

    package office;     /* no need to use import within the same package  */
    public class dept extends emp
    {
        public String dept,desig;
        public dept(String nm,String add,String acc,String deptm,String desg)
        {
            super(nm,add,acc);
            dept=deptm;
            desig=desg;
        }
    }

It is advisable to keep the code within the directory as when you compile it the class files will also be in the same directory.

To create the class use the following the commands :

javac emp.java
javac dept.java

If you face any problem while implementing the above command, you can also use the commands below :
javac office/emp.java
javac office/dept.java

Now, you have successfully created your first package.

Package 2 : Finance


In the finance package, there is a single java file - salary2.java

salary2.java


    package finance;
    import office.emp;     /*use import to create derived class of outside 
                                  package */
    import office.dept;
    public class salary2 extends dept
    {
        private float basic,hr,da,saly;
        public salary2(String nm,String add,String acc,String deptm,String   
                                  desg,float bas,float h_r,float d_a)
        {
            super(nm,add,acc,deptm,desg);
            basic=bas;
            hr=h_r;
            da=d_a;
            saly=basic + (float)0.01*hr + (float)0.01*da;
        }
        public void display()
        {
            System.out.println("Name    : " + name);
            System.out.println("Address : " + address);
            System.out.println("Acc No. : " + acc_no);
            System.out.println("Department : " + dept);
            System.out.println("Designation : " + desig);
            System.out.println("Basic Pay : " + basic);
            System.out.println("DA : " + hr + "%");
            System.out.println("HR : " + da + "%");
            System.out.println("Total Salary : "+ saly);
        }
    }

Now to create the class files use the following commands :

javac salary2.java   or   javac finance/salary2.java

Now create a normal java outside of both the office and finance directory from where you can call the methods to show the details of the employees.

abc.java

    import finance.salary2;
    public class abc
    {
        public static void main(String args[])
        {
            salary2 sal=new salary2("Rohit","265,G.C.Road,Kolkata- 
            02","97832","SALES","CEO",8000,8,10);
            sal.display();
        }
    }

Now the run the following commands to get the final output.

javac abc.java
java abc

The following output will be shown :

Name    : Rohit
Address : 265,G.C.Road,Kolkata-02
Acc No. : 97832
Department : SALES
Designation : CEO
Basic Pay : 8000.0
DA : 8.0%
HR : 10.0%
Total Salary : 8000.18



Note :  To create a derived class in the same package you don't need to use the import statement. You will need the import statement only when creating a derived class of an outside package.

Circular Queue in Java using abstract class

import java.io.*;
abstract class que
{
    abstract void insert(int val);
    abstract void del();
    abstract void display();
}
public class cq extends que
{
    int a[],front,rear,n;
    cq(int cap)
    {
        n=cap;
        front=-1;
        rear=-1;
        a=new int[n];
    }
    void insert(int val)
    {
        if(front==0 && rear==n-1 || rear==front-1)
            System.out.println("Queue overflow... \n");
        else if(front==-1 && rear==-1)
        {
            front=0;
            a[++rear]=val;
        }
        else if(rear==n-1)
        {
            rear=0;
            a[rear]=val;
        }
        else
            a[++rear]=val;
    }
    void del()
    {
        if(front==-1)
            System.out.println("Queue underflow... \n");
        else if(front==rear)
        {
            front=-1;
            rear=-1;
        }
        else if(front==n-1)
            front=0;
        else front++;
    }
    void display()
    {
        int i;
        if(front < 0)
            System.out.println("Queue underflow...\n");
        else if(rear>=front)
        {
            System.out.println("Queue : ");
            for(i=front;i<=rear;i++)
                System.out.print(a[i] + "   ");
            System.out.println();
        }
        else
        {
            System.out.println("Queue : ");
            for(i=front;i<n;i++)
                System.out.print(a[i] + "   ");
            for(i=0;i<=rear;i++)
                System.out.print(a[i] + "   ");
        }
    }
    public static void main(String args[])throws IOException
    {
        int ch,val,cap;
        System.out.println("\nProgram to implement circular queue in java : \n");
        System.out.println("Enter queue capacity : ");
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        cap=Integer.parseInt(br.readLine());
        cq obj=new cq(cap);
        do
        {
            System.out.print("\n[1] Insert [2] Delete [3] Display [4] Exit \n");
            System.out.print("\nEnter your choice : ");
            ch=Integer.parseInt(br.readLine());
            switch(ch)
            {
                case 1: 
                    System.out.println("Enter value to insert : ");
                    val=Integer.parseInt(br.readLine());
                    obj.insert(val);
                    obj.display();
                    break;

                case 2:
                    obj.del();
                    obj.display();
                    break;
                
                case 3:
                    obj.display();
                    break;
            
                case 4: break;
                
                default : System.out.println("Enter correct choice .... \n");
                    break;
            }
        }while(ch!=4);
    }
}

How to implement Bubble Sort using method call and inheritance in Java ?

import java.io.*;
class run
{
        void sort(int a[],int n)
        {
            int i,j;
            for(i=0;i<n-1;i++)
                for(j=0;j<n-1-i;j++)
                    if(a[j] > a[j+1])
                    {
                        int temp = a[j];
                        a[j]=a[j+1];
                        a[j+1]=temp;
                    }
        }
        public void display(int a[],int n)
        {
            for(int i=0;i<n;i++)
                System.out.print(a[i] + "   ");
   
        }
}
public class bubble extends run
{
    public static void main(String args[])throws IOException
    {
        System.out.print("\nProgram to sort array using bubble sort : \n");
        int n,i;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("\nEnter array capacity : ");
        n=Integer.parseInt(br.readLine());
        int a[]=new int[n];
        for(i=0;i<n;i++)
            a[i]=(int)(Math.random()*100);
        run obj=new run();
        System.out.print("\nArray before sorting : ");
        obj.display(a,n);
        obj.sort(a,n);
        System.out.print("\nArray after sorting : ");
        obj.display(a,n);
    } 
}

How to implement Bubble Sort using only method call in Java ?

import java.io.*;
public class bubble
{
        void sort(int a[],int n)
        {
            int i,j;
            for(i=0;i<n-1;i++)
                for(j=0;j<n-1-i;j++)
                    if(a[j] > a[j+1])
                    {
                        int temp = a[j];
                        a[j]=a[j+1];
                        a[j+1]=temp;
                    }
        }
        public void display(int a[],int n)
        {
            for(int i=0;i<n;i++)
                System.out.print(a[i] + "   ");
   
        }
    
    public static void main(String args[])throws IOException
    {
        System.out.print("\nProgram to sort array using bubble sort : \n");
        int n,i;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("\nEnter array capacity : ");
        n=Integer.parseInt(br.readLine());
        int a[]=new int[n];
        for(i=0;i<n;i++)
            a[i]=(int)(Math.random()*100);
        bubble obj=new bubble();
        System.out.print("\nArray before sorting : ");
        obj.display(a,n);
        obj.sort(a,n);
        System.out.print("\nArray after sorting : ");
        obj.display(a,n);
    } 
}

How to use different types of constructors in Java ?

public class consdemo
{
    int a;
    consdemo()  // default constructor
    {
        a=10;
    }
    consdemo(int x)    // parametrized constructor
    {        
        a=x;
    }
    consdemo(consdemo obj)   //  copy constructor
    {
        a=obj.a;
    }
    void disp()
    {
        System.out.print("   "  + a);
    }
    public static void main(String args[])
    {
        consdemo obj1=new consdemo();
        obj1.disp();
        consdemo obj2=new consdemo(9);
        obj2.disp();
        consdemo obj3=new consdemo(obj1);
        obj3.disp();
    }
}

Output :  10   9   10

Traversing a linked list in Java

/**
 * This is a program of entering data in sorted order 
 * in a linked list & then traversing the list 
 * Programming Language : Java
*/

import java.io.*;
class node
{
    protected int data;
    protected node link;
    public node()
    {
        data=0;
        link=null;
    }
    public node(int d,node n)
    {
        data=d;
        link=n;
    }
    public void setlink(node n)
    {
        link=n;
    }
    public void setdata(int d)
    {
        data=d;
    }
    public node getlink()
    {
        return link;
    }
    public int getdata()
    {
        return data;
    }
}
class linkedlist
{
    protected node start;
    public linkedlist()
    {
        start=null;
    }
    public boolean isempty()
    {
        return start==null;
    }
    public void insert(int val)
    {
        node nptr=null,ptr=null,save=null;
        boolean ins=false;
        if(start==null)
            start=nptr;
        else if(val<=start.getdata())
        {
            nptr.setlink(start);
            start=nptr;
        }
        else
        {
            save=start.getlink();
            while(ptr!=null)
            {
                if(val>=save.getdata() && val<=ptr.getdata())
                {
                    save.setlink(nptr);
                    nptr.setlink(ptr);
                    ins=true;
                    break;
                }
                else
                {
                    save=ptr;
                    ptr=ptr.getlink();
                }
            }
            if(ins==false)
            {
                save.setlink(nptr);
            }
        }
    }
    public void traverse1()
    {
        node ptr=start;
        System.out.print(start.getdata() + "-->");
        ptr=start.getlink();
        while(ptr.getlink()!=null)
        {
            System.out.print(ptr.getdata() + "-->");
            ptr=ptr.getlink();
        }
        System.out.print(ptr.getdata() + " |||| ");
        System.out.println();
    }
}
class traverse
{
    protected static linkedlist T;
    public static void main(String args[])
    {
        int n;
        T=new linkedlist();
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        for(int i=0;i<7;i++)
        {
            System.out.print("Enter data : ");
            try
            {
                n=Integer.parseInt(br.readLine());
                T.insert(n);
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }
        System.out.println("\nThe list is : ");
        T.traverse1();
        System.out.println();
    }
}


Textfield in Java using Applet

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
 * 
 * 
*/
public class text extends Applet implements ActionListener
{
    TextField lang,ver;
    public void init()
    {
        Label langx=new Label("Programming Language : ",Label.RIGHT);
        Label verx=new Label("Version : ",Label.RIGHT);
        lang=new TextField(15);
        ver=new TextField(10);
        add(langx);
        add(lang);
        add(verx);
        add(ver);
        lang.addActionListener(this);
        ver.addActionListener(this);
    }
    public void actionPerformed(ActionEvent ae)
    {
        repaint();
    }
    public void paint(Graphics g)
    {
        g.drawString("Programming Language :"+lang.getText(),10,100);
        g.drawString("Version : "+ver.getText(),10,125);
    }
}
      
Output :

Handling Choice in Java using Applet


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
   <applet code="choice" width=200 height=100>
   </applet>
 */
public class choice extends Applet implements ItemListener
{
    Choice lang,ver;
    String msg=" ";
    public void init()
    {
        lang=new Choice();
        ver=new Choice();
    
        lang.add("Java");
        lang.add("C++");
        lang.add("PHP");
        lang.add("HTML");
    
        ver.add("Sun JDK");
        ver.add("Borland");
        ver.add("5.3.1");
        ver.add("5");
    
        add(lang);
        add(ver);
        lang.addItemListener(this);
        ver.addItemListener(this);
    }
    public void itemStateChanged(ItemEvent ie)
    {
        repaint();
    }
    public void paint(Graphics g)
    {
        msg="Language :";
        msg+=lang.getSelectedItem();
        g.drawString(msg,6,120);
        msg="Version :";
        msg+=ver.getSelectedItem();
        g.drawString(msg,6,150);
    }
}


Loading an Image with Java Applet

import java.awt.*;
import java.applet.*;
/*
 * <applet code="image" width=300 height=150
 * <param name="img" value="cover.jpeg">
 * </applet>
 */
public class image extends Applet
{
    Image img;
    public void init()
    {
        img=getImage(getDocumentBase(),getParameter("img"));
    }
    public void paint(Graphics g)
    {
        g.drawImage(img,10,20,this);
    }
}

Java JCheckBoxGroup using applet

import java.applet.*;   
import java.awt.*;
public class program extends Applet
{
    public void init()
    {
        this.add(new Label("What is your favourite programming language ?"));
        CheckboxGroup cbg = new CheckboxGroup();
        this.add(new Checkbox("C", cbg, false));
        this.add(new Checkbox("C++", cbg, false));
        this.add(new Checkbox("JAVA", cbg, true));
        this.add(new Checkbox("PHP", cbg, false));
        this.add(new Checkbox("HTML", cbg, false));
    }
}


Radix Sort in Java

import java.io.*;
public class radix
{
    public void radix(int a[],int n)throws IOException
    {
            int i,j,k=1,l,temp,cnt;
            int b[][]=new int[10][n];
            int max=a[0],c=0;
            for(i=0;i<n;i++)
                if(a[i]>max)
                    max=a[i];
            while(max%10!=0)
                {
                    c++;
                    max/=10;
                }   
            for(i=0;i<10;i++)
                for(j=0;j<n;j++)
                    b[i][j]=-999;   
            for(l=0;l<c;l++)
            {
                for(j=0;j<n;j++)
                    {
                        temp=(a[j]/k)%10;
                        b[temp][j]=a[j];
                    }
                   
                k=k*10;    cnt=0;
                for(i=0;i<10;i++)
                    for(j=0;j<n;j++)
                        if(b[i][j]!=-999)
                            a[cnt++]=b[i][j];
                for(i=0;i<10;i++)
                    for(j=0;j<n;j++)
                        b[i][j]=-999;
            }
    }
    public void main(String args[])throws IOException
    {
        System.out.print("\nProgram to sort array using radix sort sort : \n");
        int n,i;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("\nEnter array capacity : ");
        n=Integer.parseInt(br.readLine());
        int a[]=new int[n];
        for(i=0;i<n;i++)
            a[i]=(int)(Math.random()*100);          
        System.out.print("\nArray before sorting : ");
        for(i=0;i<n;i++)
            System.out.print(a[i] + "   ");
        radix(a,n);
        System.out.print("\nArray after sorting : ");
        for(i=0;i<n;i++)
            System.out.print(a[i] + "   ");

    }
}

Create an image alongwith string with Java Applet

import java.awt.*;
import javax.swing.*;
/*
    <applet code="label" width=300 height =100>
    </appelet>
*/
public class label extends JApplet
{
    public void init()
    {
        Container contentPane=getContentPane();
        ImageIcon i=new ImageIcon("Spain.gif");
        JLabel j1=new JLabel("Spain",i,JLabel.CENTER);
        contentPane.add(j1);
    }
}



 


Top