Sunday, 30 September 2012

Computer Program Technology: Retriving data from the database




CREATE A DATABASE  "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.

TYPE THE FOLLOWING CODE IN THE NOTEPAD AND RUN THE PROGRAM




//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class retrieveDBUsingJList extends JFrame {
  
    //Initializing program components
    private DefaultListModel model;
    private JButton buttons[];
    private JList dbList;
    private JPanel p1,p2;
    private String bLabel[] = {"ID","First Name","Middle Name","Last Name","Age"};
  
    Connection con;
    Statement st;
    ResultSet rs;
    String db;

    //Setting up GUI
    public retrieveDBUsingJList() {
      
        //Setting up the Title of the Window
        super("Retrieve DB and Display Using JList");

        //Set Size of the Window (WIDTH, HEIGHT)
        setSize(300,200);

        //Exit Property of the Window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              
        //Constructing JButtons, JList, and DefaultListModel
        model = new DefaultListModel();
        buttons = new JButton[5];
        dbList = new JList(model);
      
        //Setting up JList property
        dbList.setVisibleRowCount(5);
        dbList.setFixedCellHeight(27);
        dbList.setFixedCellWidth(130);
        dbList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      
        //Constructing JPanel 1 and its property
        p1 = new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("Database: "));
        p1.add(new JScrollPane(dbList)); //Adding JList in JPanel 1
      
        //Constructing JPanel 2 and its property
        p2 = new JPanel();
        p2.setLayout(new GridLayout(5,1));
        p2.setBorder(BorderFactory.createTitledBorder("Display: "));
      
        //Constructing all 5 JButtons using "for loop" and add it in JPanel 2
        for(int count=0; count<buttons.length; count++) {
            buttons[count] = new JButton(bLabel[count]);
            p2.add(buttons[count]);
        }
      
        //Setting up the container ready for the components to be added.
        Container pane = getContentPane();
        setContentPane(pane);

        //Setting up the container layout
        GridLayout grid = new GridLayout(1,2);
        pane.setLayout(grid);
      
        //Creating a connection to MS Access and fetch errors using "try-catch" to check if it is successfully connected or not.
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
                con = DriverManager.getConnection(db,"","");
                st = con.createStatement();      
              
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
                System.exit(0);
            }
          
        //Implemeting Even-Listener on JButton buttons[0] which is ID
        buttons[0].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("id"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[1] which is First Name
        buttons[1].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("firstName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
        buttons[2].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("middleName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[3] which is Last Name
        buttons[3].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("familyName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[4] which is Age
        buttons[4].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("age"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
               
        //Adding components to the container
        pane.add(p1);
        pane.add(p2);
      
        /**Set all the Components Visible.
         * If it is set to "false", the components in the container will not be visible.
         */
        setVisible(true);
        setResizable(false);
    }
  
    //Main Method
    public static void main (String[] args) {
        retrieveDBUsingJList rdjl = new retrieveDBUsingJList();
    }
}

Friday, 28 September 2012

Computer Program Technology: Java program to add information to ms-access



 CREATE A DATABASE  "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.


TYPE THE FOLLOWING CODE IN THE NOTEPAD AND RUN THE PROGRAM

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class addItemToDatabase extends JFrame {
   
    //Initializing Components
    private JTextField inputs[];
    private JButton add, reset;
    private JLabel labels[];
    private String fldLabel[] = {"First Name: ","Middle Name: ","Family Name: ","Age: "};
    private JPanel p1;
   
    Connection con;
    Statement st;
    ResultSet rs;
    String db;

    //Setting up GUI
    public addItemToDatabase() {
       
        //Setting up the Title of the Window
        super("Adding Data to the Database");

        //Set Size of the Window (WIDTH, HEIGHT)
        setSize(300,180);

        //Exit Property of the Window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        //Constructing Components
        inputs = new JTextField[4];
        labels = new JLabel[4];
        add = new JButton("Add");
        reset = new JButton("Reset");
        p1 = new JPanel();
       
        //Setting Layout on JPanel 1 with 5 rows and 2 column
        p1.setLayout(new GridLayout(5,2));

        //Setting up the container ready for the components to be added.
        Container pane = getContentPane();
        setContentPane(pane);

        //Setting up the container layout
        GridLayout grid = new GridLayout(1,1,0,0);
        pane.setLayout(grid);
       
        //Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
                con = DriverManager.getConnection(db,"","");
                st = con.createStatement();       
               
                JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
               
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
                System.exit(0);
            }
       
        //Constructing JLabel and JTextField using "for loop" in their desired order
        for(int count=0; count<inputs.length && count<labels.length; count++) {
            labels[count] = new JLabel(fldLabel[count]);
            inputs[count] = new JTextField(20);
           
            //Adding the JLabel and the JTextFied in JPanel 1
            p1.add(labels[count]);
            p1.add(inputs[count]);
        }
       
        //Implemeting Even-Listener on JButton add
        add.addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
               
                if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
                    JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
                   
                else
                   
                try {
                   
                    String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
                    st.execute(add); //Execute the add sql
                   
                    Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
                   
                    JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
                   
                }catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
                }catch (Exception ei) {
                    JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        );
       
        //Implemeting Even-Listener on JButton reset
        reset.addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                inputs[0].setText(null);
                inputs[1].setText(null);
                inputs[2].setText(null);
                inputs[3].setText(null);
            }
        }
        );
       
        //Adding JButton "add" and "reset" to JPanel 1 after the JLabel and JTextField
        p1.add(add);
        p1.add(reset);
       
        //Adding JPanel 1 to the container
        pane.add(p1);
       
        /**Set all the Components Visible.
         * If it is set to "false", the components in the container will not be visible.
         */
        setVisible(true);
    }
   
    //Main Method
    public static void main (String[] args) {
        addItemToDatabase aid = new addItemToDatabase();
    }
}

Thursday, 27 September 2012

Java Database connection using MS-Access

This is a small java program which is used to test connection between Java and MS-Access.
1) Create a MS-Access database "Confirm".
    Field Names:- confirm, confirm_to as Text data type

2) Type the following code in the notepad
3) Run the program.

    //Java Core Package 
    import javax.swing.*; 
    //Java Extension Package 
    import java.awt.*; 
    import java.awt.event.*; 
    import java.sql.*; 
     
    public class databaseCon extends JFrame implements ActionListener { 
      
     //Initializing components 
     private JButton connect; 
     private JTextField confirmation; 
     Connection con; 
     Statement st; 
     ResultSet rs; 
     String db; 
     
     //Setting up GUI 
        public databaseCon() { 
          
         //Setting up the Title of the Window 
         super("MS Access Connection"); 
     
         //Set Size of the Window (WIDTH, HEIGHT) 
         setSize(250,95); 
     
         //Exit Property of the Window 
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       
      //Constructing Components 
         connect = new JButton("Test Connection"); 
         confirmation = new JTextField(20); 
     
         //Setting up the container ready for the components to be added. 
         Container pane = getContentPane(); 
         setContentPane(pane); 
     
         //Setting up the container layout 
         FlowLayout flow = new FlowLayout(FlowLayout.CENTER); 
         pane.setLayout(flow); 
          
         //Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not. 
         try { 
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
        db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=database.mdb;"; 
        con = DriverManager.getConnection(db,"",""); 
        st = con.createStatement();   
         
        confirmation.setText("Successfully Connected to Database"); 
         
       } catch (Exception e) { 
        JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE); 
        System.exit(0); 
       } 
        
       //Adding Event Listener to the button "Connect" 
         connect.addActionListener(this); 
          
         //Adding components to the container 
      pane.add(confirmation); 
      pane.add(connect); 
       
         /**Set all the Components Visible.
          * If it is set to "false", the components in the container will not be visible.
          */ 
         setVisible(true); 
        } 
         
        //Creating an event to the JButton "Connect" 
        public void actionPerformed(ActionEvent event) { 
          
         try { 
          if(event.getSource() == connect ) { 
            
           //Adding values on the database field "confirm" and "confirm_to" 
           String insert = "insert into Confirm (confirm, confirm_to) values ('"+confirmation.getText()+"','"+confirmation.getText()+"')"; 
        st.execute(insert); //Execute the sql 
         
        //This will display if the connection and the insertion of data to the database is successful. 
        confirmation.setText("Test Successful"); 
         
        //Display what is in the database 
        rs=st.executeQuery("select * from Confirm"); 
        while(rs.next()) { 
         System.out.println(rs.getString("confirm")); 
        } 
          } 
         }catch(Exception e) { 
          JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE); 
       System.exit(0); 
         } 
        } 
         
     //Main Method 
        public static void main (String[] args) { 
         databaseCon pjtf = new databaseCon(); 
     } 
    } 


Monday, 24 September 2012

sateesh.bagadhi: Simple Programs

The following Java programs are fundamental & simple programs used for academic record purpose.
 
                                                           1. Welcome to java
class Hello
{
public static void main(String args[])
{
System.out.println("Welcome to java ");
}
}
output
 javac Hello.java
java Hello
Welcome to java


  2. To find the big number
class Big
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
if(a>b)
System.out.println("given number a is big" +a);
else
System.out.println("given number b is big" +b);
}
}
Output:
javac Big.java
java Big 12 32
given number b is big 32


  3. Operators
class Sum
{
public static void main(String args[])
{
int a=65;
int b=47;
int c=a+b;
int d=a-b;
int e=a*b;
System.out.println("sum given numbers a & b " +c);
System.out.println("difference of given numbers a & b" +d);
System.out.println("multiplication of given numbers a & b" +e);
}
}
Output:
javac Sum.java
java Sum
Sum of given numbers a & b 112
Difference of given numbers a & b 18
Multiplication of given numbers a & b 3055


4. Even or odd
class Evenodd
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
if(a%2==0)
System.out.println("given number a is even" +a);
else
System.out.println("given number a is odd" +a);
}
}
 Output:
javac Evenodd.java
java Evenodd 2
Given number a is even2


5. factorial and its average
class Factorial
{
public  static void main(String args[])
{
int fact=1;
int n=Integer.parseInt(args[0]);
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial of given number is "+sum);
double avg=sum/n;
System.out.println("Average of factorial is "+avg);
}
}
Output
javac Factorial.java
java Factorial 5
factorial of given number is 120
average of factorial is 24.0


6. Fibonacci Series
class Fibonacci
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
int next,f=0,s=1;
System.out.println(+f);
System.out.println(+s);
for (int i=1;i<=(n-2);i++)
{
next=f+s;
System.out.println(+next);
f=s;
s=next;
}
}
}
output:
javac Fibonacci.java
java Fibonacci 7
0
1
1
2
3
5
7.    print triangle with ‘*’

class Triangle
{
public static void main(String args[])
{
loop1:for(int i=0;i<=100;i++)
{
System.out.println();
if(i>10) break;
for(int j=0;j<=100;j++)
{
System.out.print("*");
if(i==j) continue loop1;
}
}
}
}
Out put:
javac Triangle.java
java Triangle
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
*  * * * * * * * *

8.  Palindrome or not
import java.io.*;
class Palindrome
{
public static void main(String args[])
{
try
{
BufferedReader object=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number");
int num=Integer.parseInt(object.readLine());
int n=num;
int rev=0;
System.out.println("Number:");
System.out.println(""+num);
for(int i=0;i<=num;i++)
{
int r=num%10;
num=num/10;
rev=rev*10+r;
i=0;
}
System.out.println("After reversing the number:"+"");
System.out.println(""+rev);
if(n==rev)
{
System.out.println("Number is palindrome");
}
else
{
System.out.println("number is not palindrome");
}
}
catch(Exception e)
{
System.out.println("out of range");
}
}
}
Output:
javac Palindrome.java
java Palindrome
Enter the number    1221
After reversing number
1221
Given number is Palindrome
9. find area using multiple class
class Room
{
float length;
float breath;
void getdata(float l, float b)
{
length=l;
breath=b;
}
}
class Roomarea
{
public static void main(String args[])
{
float area;
Room room1=new Room();
room1.getdata(14,10);
area=room1.length*room1.breath;
System.out.println("Area :" +area);
}
}
Output:
javac Roomarea.java
java Roomarea
Area =140.0


10.        print transpose of given matrix
import java.io.*;
class Trans
{
public static void main(String args[]) throws IOException
{
int a[][]=new int[5][5];
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter how many row and columns for matrix A");
int m=Integer.parseInt(br.readLine());
int n=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("Given matrix is .....");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print("\t" +a[i][j]);
}
System.out.println();
}
System.out.println("Transpose of given matrix is .....");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print("\t" +a[j][i]);
}
System.out.println();
}
}
}


Output:
Javac Trans.java
Java Trans
Enter how many rows and columns in matrix A:
2
2
Enter the elements into matrix A:
1
2
3
4
Given matrix is ….
1      2
3      4
Transpose of given matrix is….
1        3
2      4


11.    Matrix Addition
import java.io.*;
class Addition
{
public static void main(String args[]) throws IOException
{
int a[][]=new int[5][5];
int b[][]=new int[5][5];
int c[][]=new int[5][5];
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter how many row and columns for matrix A");
int m=Integer.parseInt(br.readLine());
int n=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("Enter how many row and columns for matrix B");
int p=Integer.parseInt(br.readLine());
int q=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix B");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(br.readLine());
}
}
if(m!=p&&n!=q)
{
System.out.println("Addition not  possible");
System.exit(0);
}
else
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("result matrix is .....");
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
System.out.print("\t" +c[i][j]);
}
}
}
}    


Output:
javac Addition.java
java Addition
Enter how many rows and columns for matrix A:
2
2
Enter the elements into matrix A:
1
2
3
4
Enter how many rows and columns for matrix B:
2
2
Enter elements into matrix B:
1
2
3
4
Result matrix is….
2               4
6               8              


                                                                  
12.      Matrix multiplication.
import java.io.*;
class Multiplication
{
public static void main(String args[]) throws IOException
{
int a[][]=new int[5][5];
int b[][]=new int[5][5];
int c[][]=new int[5][5];
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter how many row and columns for matrix A");
int m=Integer.parseInt(br.readLine());
int n=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("Enter how many row and columns for matrix B");
int p=Integer.parseInt(br.readLine());
int q=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix B");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(br.readLine());
}
}
if(m!=p&&n!=q)
{
System.out.println("Addition not  possible");
System.exit(0);
}
else
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("result matrix is .....");
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
System.out.print("\t" +c[i][j]);
}
}
}
}


Output:
javac Matrix.java
java Matrix
Enter how many rows and columns for matrix A:
2
2
Enter the elements into matrix A:
1
2
3
4
Enter how many rows and columns for matrix B:
2
2
Enter elements into matrix B:
5
6
7
8
Result matrix is….
6               8
10             12              


13. find complex number using constructors
class complex
{
int real,img;
complex() {}
complex(int a)
{
real=img=a;
}
complex(int x, int y)
{
real=x;
img=y;
}
complex sum(complex c1, complex c2)
{
complex c3=new complex();
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
return c3;
}
void display()
{
System.out.println(real+"+i"+img);
}
}
class Complexnum
{
public static void main(String args[])
{
complex c1=new complex(1,2);
complex c2=new complex(2);
complex c3=new complex();
c3=c3.sum(c1,c2);
c3.display();
}
}
Output:
Javac Complexnum.java
Java Complexnum
3+i4


14. find concatenation of two strings
class Concat
{
public static void main(String args[])
{
String str1="Table";
String str2="Tennis";
String Game=str1+" "+str2;
System.out.println(Game);
}
}
Output:
Javac Concat.java
Java Concat
Tabie tennis
                 
               


15.  bubble sort
import java.io.*;
class Bubblesort
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0,i,j,t;
int a[]=new int[10];
System.out.println("Enter size of the array:");
try
{
n=Integer.parseInt(br.readLine());
}
catch(Exception e) {}
System.out.println("Enter elements into the array:");
try
{
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
}
catch(Exception e) {}
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
System.out.println("The sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
Output:
javac Bubblesort.java
java Bubblesort
Enter the size of array
5
Enter the elements into the array
45
34
76
12
69
The sorted array is
12 34 45 69 76


16. selection sort
import java.io.*;
class Selectionsort
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0,i,j,t;
int a[]=new int[10];
System.out.println("Enter size of the array:");
try
{
n=Integer.parseInt(br.readLine());
}
catch(Exception e){}
System.out.println("Enter elements into the array:");
try
{
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
}
catch(Exception e){}
i=0;
while(i<n-1)
{
int key=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[key])
{
key=j;
}
}
t=a[key];
a[key]=a[i];
a[i]=t;
i++;
}
System.out.println("The sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}


Output:
javac Selectionsort.java
java Selectionsort
Enter the size of array
5
Enter the elements into the array
45
34
76
12
69
The sorted array is
76 69 45 34 12


17.  Binary Search
import java.lang.*;
import java.util.*;
import java.io.*;
class Search
{
public int binarysearch(int[]a,int key)
{
int f=1;
int low=0;
int high=a.length-1;
int mid=(low+high)/2;
while(low<=high)
{
if(a[mid]==key)
{
f=0;
break;
}
if(a[mid]<key)
low=mid+1;
else
high=mid-1;
mid=(low+high)/2;
}
return(f);
}
}
class Binarysearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Search s=new Search();
int[]a;
int i,k,n;
int f=1;
System.out.println("Binary search");
System.out.println("enter your choice");
System.out.println("Enter the size of array");
n=sc.nextInt( );
a=new int[n];
System.out.println("Enter the elements");
for(i=0;i<n;i++)
a[i]=sc.next();
System.out.println("Enter the element to search:");
k=sc.nextInt();
int c=s.binarysearch(a,k);
if(c==0)
System.out.println("The element is found");
else
System.out.println("The elements is not found");
}
}


Output:
javac Binarysearch.java
java Binarysearch
BINARY SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
8
The element is found
Output:
javac Binarysearch.java
java Binarysearch
BINARY SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
10
The element not found

18.  Linear search
import java.lang.*;
import java.util.*;
import java.io.*;
class Search
{
public int linearsearch(int[]a,int key)
{
int flag=1;
for(int i=0;i<a.length;i++)
{
if(a[i]==key)
{
flag=0;
}
}
return(flag);
}
}
class Linearsearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
{
Search s=new Search( );
int []a;
int i,k,n,ch;
int f=1;
System.out.println("Linear Search\n");
System.out.println("Enter the size of array");
n=sc.nextInt( );
a=new int[n];
System.out.println("enter the elements");
for (i=0;i<n;i++)
a[i]=sc.nextInt( );
System.out.println("enter the element to search");
k=sc.nextInt( );
f=s.linearsearch(a,k);
if(f==0)
System.out.println("The element is found");
else
System.out.println("Element is not found");
}
}
}


Output:
javac Linearsearch.java
java Linearsearch
LINEAR SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
8
The element is found
Output:
javac Linearsearch.java
java Linearsearch
LINEAR SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
10
The element not found