Java Questions Part11 - Programs on Algo, DS, DB

1.Write a Java program to demonstrate Leaner Search?

Answer: Linear search is used to search a key element from multiple elements. Linear search is less used today because it is slower than binary search and hashing.
Algorithm given below:
Step 1: Traverse the array
Step 2: Match the key element with array element
Step 3: If key element is found, return the index position of the array element
Step 4: If key element is not found, return -1.

public class LinearSearchExample{   

public static int linearSearch(int[] arr, int key){   

        for(int i=0;i<arr.length;i++){   

            if(arr[i] == key){   

                return i;   

            }   

        }   

        return -1;   

    }   

    public static void main(String a[]){   

        int[] a1= {10,20,30,50,70,90};   

        int key = 50;   

        System.out.println(key+" is found at index: "+linearSearch(a1, key));   

    }   

}   

Output:
50 is found at index: 3

2. Write a Java program to demonstrate Binary Search?

Answer: Binary search is used to search a key element from multiple elements. Binary search is faster than linear search. In case of binary search, array elements must be in ascending order. If you have unsorted array, you can sort the array using Arrays.sort(arr) method.
class BinarySearchExample{ 

 public static void binarySearch(int arr[], int first, int last, int key){ 

   int mid = (first + last)/2; 

   while( first <= last ){ 

      if ( arr[mid] < key ){ 

        first = mid + 1;    

      }else if ( arr[mid] == key ){ 

        System.out.println("Element is found at index: " + mid); 

        break; 

      }else{ 

         last = mid - 1; 

      } 

      mid = (first + last)/2; 

   } 

   if ( first > last ){ 

      System.out.println("Element is not found!"); 

   } 

 } 

 public static void main(String args[]){ 

        int arr[] = {10,20,30,40,50}; 

        int key = 30; 

        int last=arr.length-1; 

        binarySearch(arr,0,last,key);     

 } 

} 

Output:
Element is found at index: 2

3. Write a Java program to demonstrate Bubble sort?

Answer: We can create a java program to sort array elements using bubble sort. Bubble sort algorithm is known as the simplest sorting algorithm.
In bubble sort algorithm, array is traversed from first element to last element. Here, current element is compared with the next element. If current element is greater than the next element, it is swapped.
public class BubbleSortExample { 

    static void bubbleSort(int[] arr) { 

        int n = arr.length; 

        int temp = 0; 

         for(int i=0; i < n; i++){ 

                 for(int j=1; j < (n-i); j++){ 

                          if(arr[j-1] > arr[j]){ 

                                 //swap elements 

                                 temp = arr[j-1]; 

                                 arr[j-1] = arr[j]; 

                                 arr[j] = temp; 

                         }                 

                 } 

         }
 

    } 

    public static void main(String[] args) { 

                int arr[] ={3,60,35,2,45,320,5}; 
         
                System.out.println("Array Before Bubble Sort"); 

                for(int i=0; i < arr.length; i++){ 

                        System.out.print(arr[i] + " "); 

                } 

                System.out.println(); 
               
                bubbleSort(arr);//sorting array elements using bubble sort 
               
                System.out.println("Array After Bubble Sort"); 

                for(int i=0; i < arr.length; i++){ 

                        System.out.print(arr[i] + " "); 
                }   

        } 

} 

Output:
Array Before Bubble Sort

3 60 35 2 45 320 5

Array After Bubble Sort

2 3 5 35 45 60 320

4. Write a Java program to demonstrate connecting to a Database?

Answer: There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
Register the Driver class
Create connection
Create statement
Execute queries
Close connection
import java.sql.*; 

class MysqlCon{ 

public static void main(String args[]){ 

try{ 

Class.forName("com.mysql.jdbc.Driver"); 

Connection con=DriverManager.getConnection( 

"jdbc:mysql://localhost:1234/ABCD","username","pswd"); 

//here sonoo is database name, root is username and password 

Statement stmt=con.createStatement(); 

ResultSet rs=stmt.executeQuery("select * from emp"); 

while(rs.next()) 

System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3)); 

con.close(); 

}catch(Exception e){ System.out.println(e);} 

} 

} 

5. Write a Java program to demonstrate inserting data into a table using JDBC?

Answer:
public class JDBCExample {

   // JDBC driver name and database URL

   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 

   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   //  Database credentials

   static final String USER = "username";

   static final String PASS = "password";

   public static void main(String[] args) {

   Connection conn = null;

   Statement stmt = null;

   try{

      //STEP 2: Register JDBC driver

      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection

      System.out.println("Connecting to a selected database...");

      conn = DriverManager.getConnection(DB_URL, USER, PASS);

      System.out.println("Connected database successfully...");

    
      //STEP 4: Execute a query

      System.out.println("Inserting records into the table...");

      stmt = conn.createStatement();

    
      String sql = "INSERT INTO Registration " +

                   "VALUES (100, 'Zara', 'Ali', 18)";

      stmt.executeUpdate(sql);

      sql = "INSERT INTO Registration " +

                   "VALUES (101, 'Mahnaz', 'Fatma', 25)";

      stmt.executeUpdate(sql);

      sql = "INSERT INTO Registration " +

                   "VALUES (102, 'Zaid', 'Khan', 30)";

      stmt.executeUpdate(sql);

      sql = "INSERT INTO Registration " +

                   "VALUES(103, 'Sumit', 'Mittal', 28)";

      stmt.executeUpdate(sql);

      System.out.println("Inserted records into the table...");


   }catch(SQLException se){

      //Handle errors for JDBC

      se.printStackTrace();

   }catch(Exception e){

      //Handle errors for Class.forName

      e.printStackTrace();

   }finally{

      //finally block used to close resources

      try{

         if(stmt!=null)

            conn.close();

      }catch(SQLException se){

      }// do nothing

      try{

         if(conn!=null)

            conn.close();

      }catch(SQLException se){

         se.printStackTrace();

      }//end finally try

   }//end try

   System.out.println("byebye!");

}//end main

}//end JDBCExample

Output:
Connecting to a selected database...

Connected database successfully...

Inserting records into the table...

Inserted records into the table...

byebye!

6. Write a Java program to demonstrate inserting an image using JDBC?

Answer:
import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class InsertingImageToDatabase {

   public static void main(String args[]) throws Exception {

      //Registering the Driver

      DriverManager.registerDriver(new com.mysql.jdbc.Driver());

      //Getting the connection

      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";

      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");

      System.out.println("Connection established......");

      //Creating the Statement

      Statement stmt = con.createStatement();

      //Executing the statement

      String createTable = "CREATE TABLE Tutorial( "

         + "Name VARCHAR(255), "

         + "Type VARCHAR(50), "

         + "Logo BLOB)";

      stmt.execute(createTable);

      //Inserting values

      String query = "INSERT INTO Tutorial(Name, Type, Logo) VALUES (?, ?, ?)";

      PreparedStatement pstmt = con.prepareStatement(query);

      pstmt.setString(1, "JavaFX");

      pstmt.setString(2, "Java_library");

      FileInputStream fin = new FileInputStream("E:\\images\\javafx_logo.jpg");

      pstmt.setBinaryStream(3, fin);

      pstmt.execute();


      pstmt.setString(1, "CoffeeScript");

      pstmt.setString(2, "scripting Language");

      fin = new FileInputStream("E:\\images\\coffeescript_logo.jpg");

      pstmt.setBinaryStream(3, fin);

      pstmt.execute();

      pstmt.setString(1, "Cassandra");

      pstmt.setString(2, "NoSQL database");

      fin = new FileInputStream("E:\\images\\cassandra_logo.jpg");

      pstmt.setBinaryStream(3, fin);

      pstmt.execute();

      System.out.println("Data inserted");

      ResultSet rs = stmt.executeQuery("Select *from Tutorial");

      while(rs.next()) {

         System.out.print("Name: "+rs.getString("Name")+", ");

         System.out.print("Tutorial Type: "+rs.getString("Type")+", ");

         System.out.print("Logo: "+rs.getBlob("Logo"));

         System.out.println();

      }

   }

}

Output:
Connection established......

Data inserted

Name: JavaFX, Tutorial Type: Java_library, Logo: com.mysql.jdbc.Blob@7dc5e7b76

Name: CoffeeScript, Tutorial Type: scripting Language, Logo:

com.mysql.jdbc.Blob@1ee0005

Name: Cassandra, Tutorial Type: NoSQL database, Logo: com.mysql.jdbc.Blob@75a1cd677

7. WAP of depth first search algo

Answer:
import java.util.Iterator;

import java.util.LinkedList;

public class DFS {

                //no of vertices.

    int V;   

    //we are building graph using adjacency list.

                //so we should have linked list for every node and store adjacent nodes of that node in that list

    LinkedList<Integer> adjList[];

    // constructor

    DFS(int v)

    {

        V = v;

        adjList = new LinkedList[v];

        for (int i=0; i<v; ++i)

                                {

            adjList[i] = new LinkedList();  //it will create empty list for every node

                                }

    }

    //adding edges to graph

    void addEdgesToGraph(int v, int u)

    {

        adjList[v].add(u);     //here it will add vertex to adjacency list of another vertex so that edge can be added to graph.

    }

    // depth first traversal is used by depth first search. it will traverse one strong component completely

    void DFTraversal(int v,int visited[])

    {

        visited[v] = 1;

       System.out.print(v + " ");

        Iterator<Integer> i = adjList[v].listIterator();

        while (i.hasNext())

        {

            int n = i.next();

            if (visited[n]==0)

                DFTraversal(n, visited);

        }

    }

    //depth first search will call depth fist traversal on disconnected components. it will keep track of visited[] array.

    void DFSearch(int v)

    {
   
        int visited[] = new int[V];
                             
        DFTraversal(v, visited);

                                for (int i=1;i<V;i++)

                                {

                                                if(visited[i]==0)

                                                {

                                     DFTraversal(i, visited);

                                                }

                                }
    }

    public static void main(String args[])

    {

        DFS obj = new DFS(10);

        obj.addEdgesToGraph(1,2);

        obj.addEdgesToGraph(1,4);

        obj.addEdgesToGraph(2,5);

        obj.addEdgesToGraph(2,6);

        obj.addEdgesToGraph(4,7);

        obj.addEdgesToGraph(4,8);

        obj.addEdgesToGraph(3,9);

        obj.addEdgesToGraph(3,4);

        obj.addEdgesToGraph(4,3);       

        obj.DFSearch(1);

    }

}

Output:

1 2 5 6 4 7 8 3 9

No comments:

Post a Comment