JAVA Assignment
Submitted by Sunil Kumar Gunasekaran
1) Given an array of integers, sort the integer values.
package Assignment;
// import java.io.System;
publicclassBubbleSort{
publicstaticvoid main(String a[])
{
int i;
int array[] = {12,9,4,99,120,1,3,10};
// prints the value before sorting array.
System.out.println("Values Before bubble sort of Integers:n");
for(i = 0; i <array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
// sorting array
bubble_srt(array, array.length);
// printing the elements of array after the sort
System.out.print("Values after the sort:n");
for(i = 0; i <array.length ; i++)
System.out.print(array[i]+" ");
System.out.println();
} // end of main
// static bubble sort method
publicstaticvoidbubble_srt( int a[], int n )
{
int i, j,t=0;
for (i = 0; i < n; i++)
{
// since highest value is put at the last in first iteration
for (j = 1; j < n-i; j++)
{
if(a[j-1] > a[j])
{
t = a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
}// end of bubble_srt()
}// end of class
Output
Values Before bubble sort of Integers:
12 9 4 99 120 1 3 10
Values after the sort:
1 3 4 9 10 12 99 120

2) Given an array of integers, print only odd numbers.
package Assignment;
publicclassOddNumbers {
publicstaticvoid main (String args[])
{
int i;
int array[] = {12,9,4,99,120,1,3,10};
// print the elements of array
System.out.print("Elements of the array are ::n");
for(i = 0; i <array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
System.out.println();
// logic for printing the odd elements of the array
System.out.println("Printing the odd numbers of the array::");
for (i=0;i <array.length;i++ )
{
if (array[i] % 2 != 0 )
{
System.out.print(array[i]+" ");
}
elsecontinue;
}

Output:
Elements of the array are ::
12 9 4 99 120 1 3 10
Printing the odd numbers of the array::
9 99 1 3
3) Given an array of integers move all even numbers to the beginning of the array.
package Assignment;
publicclassMoveEven {
publicstaticvoid main (String args[])
{
int i;
int array[] = {12,9,4,99,120,1,3,10};
// The array elements before moving even elements
System.out.println("Values Before moving even integers front of arrayn");
for(i = 0; i <array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
// Function which moves the even elements to the frobt of the array.
move(array, array.length);
// Printing the array elements after the even integers are moved to front.
System.out.println("Values After moving even integers front of arrayn");
for(i = 0; i <array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
}
publicstaticvoid move (int a[],int n)
{
inti,j,t;
for(i = 0; i < n; i++)
{
if (a[i]%2 ==0)
{
for (j = i; j > 0; j--)
{
t = a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
}
}

Output:
Values Before moving even integers front of array
12 9 4 99 120 1 3 10
Values After moving even integers front of array
10

120

4

12

9

99

1

3
4) Print the unique numbers and also print the number of occurrences of duplicate
numbers.
package Assignment;
// This can be accomplished using hash tables. Please look at it.
publicclass Unique {
publicstaticvoid main(String[] args) {
int i;
int array[] = {12,9,4,99,120,1,3,10, 12, 4,4, 120,3,3,3};
// Printing the array elements
int limit = array.length;
System.out.println("Printing the elements of arrayn");
for(i = 0; i <array.length; i++)
System.out.print( array[i]+" ");
System.out.println();

// initializing a two dimensional array.
int holder[][]= newint [limit][2];
// filling the two dimensional array.
for (i=0;i<array.length;i++)
{
holder[i][0] = 0;
holder[i][1] = 0;
}
int flag;

// For pasting the unique elements into another array.
for (i=0;i<array.length;i++)
{
flag =1;
for (int j=0;j<i;j++ )
{
if (array[i] == array[j])
{
flag ++;
}
}
if (flag == 1)
{
holder[i][0] = array[i];
}
}
// For counting the number of occurrences.
int j; flag=1;
for (i=0;i<holder.length;i++)
{
flag=0;
for (j=i;j<array.length;j++)
{
if (holder[i][0] == array[j])
{
flag++;
}
}
// Assigning flag value to the holder.
holder[i][1]= flag;

}

// Printing the unique elements and number of their occurrences in 2D array.
System.out.println("Printing the unique elements as 2D array");
for (i=0;i<holder.length;i++)
{
System.out.println(holder[i][0]+" "+holder[i][1]);
}
}
}

Output:
Printing the elements of array
12 9 4 99 120 1 3 10 12 4 4 120
Printing the unique elements as 2D array
12 2
9 1
4 3
99 1
120 2
1 1
3 4
10 1

3

3

3

5) Given an array of integerscheck the Fibonacci series.
package Assignment;
importjava.util.Scanner;
publicclassFibonnacci {
staticintn;
staticint [] fibo;
static Scanner console=new Scanner (System.in);

publicstaticvoid main(String[] args) {
// Array for testing whether it is fibonacci or not.
int check[] = {1,1,2,3,5,8};
// Printing the given array elements.
System.out.println("Printing the given array::");
for (int j=0;j<check.length;j++)
{
System.out.print(check[j]+" ");
}
System.out.println();

n = check.length;
// Generating new array containing fibonnaci numbers.
fibo = newint [n];
fill(fibo);

boolean flag = true;
int i;
for (i=0;i<n;i++)
{
if (fibo[i] != check[i])
{
flag = false;
break;
}
}
if (flag)
{
System.out.println("The given array elements form fibonnacci
series.");
}
else {
System.out.println("The given array elements donot form
fibonnacci series.");
}
}
// Logic for generating Fibonnacci numbers.
publicstaticvoid fill(int[]fibo)
{
int i =0;
fibo[0] = 1;
fibo[1] = 1;
for (i=2;i<fibo.length;i++)
fibo[i]=fibo[i-1]+fibo[i-2];
}// end of fill function
}// end of class

Output:
Printing the given array::
1 1 2 3 5 8
The given array elements form fibonnacci series.

6) Given an array of integers check the Palindrome of the series.
package Assignment;
publicclass Palindrome {
publicstaticvoid main(String[] args) {
int i;
int array[] = {1,3,4,3,1};
// prints the value before sorting array.
System.out.println("Elements of the array:");
for(i = 0; i <array.length; i++)
System.out.print( array[i]+" ");
// System.out.println();
int flag =1;
for (i=0; i< (array.length/2);i++)
{
if (array[i] != array[array.length -i-1] )
{
flag = 0;
}
}
System.out.println();
System.out.println();
if (flag == 0)
{
System.out.println("It is not a palindrome");
}
else {
System.out.println("It is a palindrome.");
}
}
}

Output
Elements of the array:
1 3 4 3 1
Its a palindrome.

7) Given a string print the unique words of the string.
package Assignment;
importjava.util.HashSet;
importjava.util.Iterator;
importjava.util.Scanner;
importjava.util.Set;
// import java.util.TreeSet;
// Implementing

sets to find the unique words.

publicclassUniqueWord
{
publicstaticvoid main(String[] args)
{

// Hash Set implementing the Set.
Set<String> words = newHashSet<String>();
// using a sample string to print the unique words
String sample ="This is a test is a test a test test";
Scanner in = newScanner(sample);
//System.out.println("Please enter the string");
while (in.hasNext())
{
String word = in.next();
// using the add function to add the words into the hash set.
words.add(word);
}
// Used for moving through the set and printing the words.
Iterator <String>iter = words.iterator();
// Printing the unique words of the string.
System.out.println("Printing the unique words of the given string::");
for (int i = 1; i <= 20 &&iter.hasNext(); i++)
// using iterator function to read the elements of hash set.
System.out.print(" "+ iter.next()+ " ");
}
}

Output:
Printing the unique words of the given string::
is test a This

8) Given a string print the reverse of the string.
package Assignment;
// program for printing the reverse of the string.
publicclassStringReverse
{
publicstaticvoid main(String[] args)
{
Stringstr = "molecule";
String reverse ="";
int i=0;

// printing the original string
System.out.println("Original String:: "+ str);
// converting string to character array.
char rev[] = str.toCharArray();
// appending characters to reverse string.
for (i=rev.length-1;i>=0;i--)
{
reverse = reverse + rev[i];
}
System.out.println();
// Printing the reversed String
System.out.println("Reversed String is:: " + reverse);
}
}

Output:
Original String:: molecule
Reversed String is::elucelom

9) Given a string print the string in same flow, but reversing each word of it.
package Assignment;
importjava.util.Scanner;
publicclassReaverseEach {
publicstaticvoid main(String[] args) {
String sample = "This string is being checked";
Scanner in = newScanner(sample);
ReaverseEach rev = newReaverseEach();
String word="";
String Output="";
while (in.hasNext())
{
word = in.next();
Output = Output + rev.reverseString(word)+" ";
}
System.out.println("The original string is::");
System.out.println(sample);
System.out.println();
System.out.println("The String with reversed words are printed below::");
System.out.println(Output);
}
public String reverseString(String str)
{
//String str = "molecule";
String reverse ="";
int i=0;
// printing the original string
//System.out.println("Original String:: "+ str);
// converting string to character array.
char rev[] = str.toCharArray();
// appending characters to reverse string.
for (i=rev.length-1;i>=0;i--)
{
reverse = reverse + rev[i];
}
//System.out.println();
// Printing the reversed String
//System.out.println("Reversed String is:: " + reverse);
return reverse;
}
}

Output:
The original string is::
This string is being checked
The String with reversed words are printed below::
sihTgnirtssigniebdekcehc
10) Read a file content and write it to a new file in reverse order.(reverse line 1-10 to line
10-1)
package Assignment;
import java.io.*;
importjava.util.LinkedList;
publicclassReverseFile {

publicstaticvoid main(String args[])
{
try{
// using fileinputstream to read contents inputFile.txt
FileInputStreamfstream = newFileInputStream("C:UsersSunil
KumarDesktopWhite Box TrainingJava ProgramsAssignmentinputFile.txt");
DataInputStream in = newDataInputStream(fstream);
BufferedReaderbr = newBufferedReader(newInputStreamReader(fstream));
String strLine;
// using LinkedList to store the lines in the file.
LinkedList<String> list = newLinkedList<String>();

//Reading input file line by line
while ((strLine = br.readLine()) != null)

{

list.add(strLine);
}
// Opening the outPut.txt file using FileWriter.
FileWriterfilestream = newFileWriter("C:UsersSunil KumarDesktopWhite
Box TrainingJava ProgramsAssignmentoutputFile.txt");
BufferedWriter out = newBufferedWriter(filestream);
// Writing the lines in reverse fashion into outputFile.txt
int i;
intlen = list.size();
for (i=len-1;i>=0;i--)
{
out.write(list.get(i));
out.write("n");
}
out.close();
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

Output:
inputFile.txt
First line.
Second Line.
Third Line.
Fourth Line.
Fifth Line.
Sixth Line.
Seventh Line.
Eighth Line.
Ninth Line.
Tenth Line.

outputFile.txt
Tenth Line.
Ninth Line.
Eighth Line.
Seventh Line.
Sixth Line.
Fifth Line.
Fourth Line.
Third Line.
Second Line.
First line.

11) Write a java program which provides API for database "select" and "Update".
package MySQL;
import java.sql.*;

publicclassDBAccess
{
publicstatic Statement s = null;
publicstatic Connection conn = null;

publicResultSet execute(String query)
{
ResultSetrs = null;
try {
// Execute the query and return the ResultSet
s.executeQuery(query);
rs = s.getResultSet();
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
System.out.println(e);
//e.printStackTrace();
}
returnrs;
}

publicint update(String query)
{
int count = 0;
try {
count = s.executeUpdate(query);
}
catch (Exception e)
{
System.err.println("Cannot conect to database server.");
System.out.println(e);
}
return count;
}

publicstaticvoid main (String[] args)
{
//Connection conn = null;
DBAccessdb = newDBAccess();
try
{
String userName = "root";
String password = "good";
// localhost - Name of the server.
String url = "jdbc:mysql://localhost/test";
// Create one driver instance and create one or more connection instances.
// Standard syntax of creating instance of singleton class.
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
// Connection instance using the Driver.
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
s = conn.createStatement ();

int count;

// Two types of methods present in the JDBC code - executeUpdate and executeQuery

// Passing the query and updating the record.
String query2 = "Update EMP set email='hare@gmail.com' where id = 2;";
count = db.update(query2);
System.out.println("Updated record count = " + count);

// Passing query and s executing query and returning rs.
String query1 = "select * from EMP";
ResultSetrs = db.execute(query1);

while (rs.next ())
{
intidVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("email");
System.out.println (
"id = " + idVal
+ ", name = " +nameVal
+ ", email = " + catVal);
++count;
}

rs.close ();
s.close ();

s.close ();
// System.out.println (count + " rows were inserted");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
System.out.println(e);
e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}

Output:
Database connection established
Updated record count = 1
id = 1, name = Sunil, email = abcded@gmail.com
id = 2, name = Manish, email = hare@gmail.com
id = 1, name = Balaji, email = abcded@gmail.com
Database connection terminated

Java programs - bubble sort, iterator, linked list, hash set, reverse string, reverse number fibonnacci

  • 1.
    JAVA Assignment Submitted bySunil Kumar Gunasekaran 1) Given an array of integers, sort the integer values. package Assignment; // import java.io.System; publicclassBubbleSort{ publicstaticvoid main(String a[]) { int i; int array[] = {12,9,4,99,120,1,3,10}; // prints the value before sorting array. System.out.println("Values Before bubble sort of Integers:n"); for(i = 0; i <array.length; i++) System.out.print( array[i]+" "); System.out.println(); // sorting array bubble_srt(array, array.length); // printing the elements of array after the sort System.out.print("Values after the sort:n"); for(i = 0; i <array.length ; i++) System.out.print(array[i]+" "); System.out.println(); } // end of main // static bubble sort method publicstaticvoidbubble_srt( int a[], int n ) { int i, j,t=0; for (i = 0; i < n; i++) { // since highest value is put at the last in first iteration for (j = 1; j < n-i; j++) { if(a[j-1] > a[j]) { t = a[j-1]; a[j-1]=a[j]; a[j]=t; } } } }// end of bubble_srt() }// end of class
  • 2.
    Output Values Before bubblesort of Integers: 12 9 4 99 120 1 3 10 Values after the sort: 1 3 4 9 10 12 99 120 2) Given an array of integers, print only odd numbers. package Assignment; publicclassOddNumbers { publicstaticvoid main (String args[]) { int i; int array[] = {12,9,4,99,120,1,3,10}; // print the elements of array System.out.print("Elements of the array are ::n"); for(i = 0; i <array.length; i++) System.out.print( array[i]+" "); System.out.println(); System.out.println(); // logic for printing the odd elements of the array System.out.println("Printing the odd numbers of the array::"); for (i=0;i <array.length;i++ ) { if (array[i] % 2 != 0 ) { System.out.print(array[i]+" "); } elsecontinue; } Output: Elements of the array are :: 12 9 4 99 120 1 3 10 Printing the odd numbers of the array:: 9 99 1 3
  • 3.
    3) Given anarray of integers move all even numbers to the beginning of the array. package Assignment; publicclassMoveEven { publicstaticvoid main (String args[]) { int i; int array[] = {12,9,4,99,120,1,3,10}; // The array elements before moving even elements System.out.println("Values Before moving even integers front of arrayn"); for(i = 0; i <array.length; i++) System.out.print( array[i]+" "); System.out.println(); // Function which moves the even elements to the frobt of the array. move(array, array.length); // Printing the array elements after the even integers are moved to front. System.out.println("Values After moving even integers front of arrayn"); for(i = 0; i <array.length; i++) System.out.print( array[i]+" "); System.out.println(); } publicstaticvoid move (int a[],int n) { inti,j,t; for(i = 0; i < n; i++) { if (a[i]%2 ==0) { for (j = i; j > 0; j--) { t = a[j-1]; a[j-1]=a[j]; a[j]=t; } } } } } Output: Values Before moving even integers front of array 12 9 4 99 120 1 3 10 Values After moving even integers front of array 10 120 4 12 9 99 1 3
  • 4.
    4) Print theunique numbers and also print the number of occurrences of duplicate numbers. package Assignment; // This can be accomplished using hash tables. Please look at it. publicclass Unique { publicstaticvoid main(String[] args) { int i; int array[] = {12,9,4,99,120,1,3,10, 12, 4,4, 120,3,3,3}; // Printing the array elements int limit = array.length; System.out.println("Printing the elements of arrayn"); for(i = 0; i <array.length; i++) System.out.print( array[i]+" "); System.out.println(); // initializing a two dimensional array. int holder[][]= newint [limit][2]; // filling the two dimensional array. for (i=0;i<array.length;i++) { holder[i][0] = 0; holder[i][1] = 0; } int flag; // For pasting the unique elements into another array. for (i=0;i<array.length;i++) { flag =1; for (int j=0;j<i;j++ ) { if (array[i] == array[j]) { flag ++; } } if (flag == 1) { holder[i][0] = array[i]; } }
  • 5.
    // For countingthe number of occurrences. int j; flag=1; for (i=0;i<holder.length;i++) { flag=0; for (j=i;j<array.length;j++) { if (holder[i][0] == array[j]) { flag++; } } // Assigning flag value to the holder. holder[i][1]= flag; } // Printing the unique elements and number of their occurrences in 2D array. System.out.println("Printing the unique elements as 2D array"); for (i=0;i<holder.length;i++) { System.out.println(holder[i][0]+" "+holder[i][1]); } } } Output: Printing the elements of array 12 9 4 99 120 1 3 10 12 4 4 120 Printing the unique elements as 2D array 12 2 9 1 4 3 99 1 120 2 1 1 3 4 10 1 3 3 3 5) Given an array of integerscheck the Fibonacci series. package Assignment; importjava.util.Scanner; publicclassFibonnacci { staticintn; staticint [] fibo;
  • 6.
    static Scanner console=newScanner (System.in); publicstaticvoid main(String[] args) { // Array for testing whether it is fibonacci or not. int check[] = {1,1,2,3,5,8}; // Printing the given array elements. System.out.println("Printing the given array::"); for (int j=0;j<check.length;j++) { System.out.print(check[j]+" "); } System.out.println(); n = check.length; // Generating new array containing fibonnaci numbers. fibo = newint [n]; fill(fibo); boolean flag = true; int i; for (i=0;i<n;i++) { if (fibo[i] != check[i]) { flag = false; break; } } if (flag) { System.out.println("The given array elements form fibonnacci series."); } else { System.out.println("The given array elements donot form fibonnacci series."); } } // Logic for generating Fibonnacci numbers. publicstaticvoid fill(int[]fibo) { int i =0; fibo[0] = 1; fibo[1] = 1; for (i=2;i<fibo.length;i++) fibo[i]=fibo[i-1]+fibo[i-2]; }// end of fill function
  • 7.
    }// end ofclass Output: Printing the given array:: 1 1 2 3 5 8 The given array elements form fibonnacci series. 6) Given an array of integers check the Palindrome of the series. package Assignment; publicclass Palindrome { publicstaticvoid main(String[] args) { int i; int array[] = {1,3,4,3,1}; // prints the value before sorting array. System.out.println("Elements of the array:"); for(i = 0; i <array.length; i++) System.out.print( array[i]+" "); // System.out.println(); int flag =1; for (i=0; i< (array.length/2);i++) { if (array[i] != array[array.length -i-1] ) { flag = 0; } } System.out.println(); System.out.println(); if (flag == 0) { System.out.println("It is not a palindrome"); } else { System.out.println("It is a palindrome."); } } } Output
  • 8.
    Elements of thearray: 1 3 4 3 1 Its a palindrome. 7) Given a string print the unique words of the string. package Assignment; importjava.util.HashSet; importjava.util.Iterator; importjava.util.Scanner; importjava.util.Set; // import java.util.TreeSet; // Implementing sets to find the unique words. publicclassUniqueWord { publicstaticvoid main(String[] args) { // Hash Set implementing the Set. Set<String> words = newHashSet<String>(); // using a sample string to print the unique words String sample ="This is a test is a test a test test"; Scanner in = newScanner(sample); //System.out.println("Please enter the string"); while (in.hasNext()) { String word = in.next(); // using the add function to add the words into the hash set. words.add(word); } // Used for moving through the set and printing the words. Iterator <String>iter = words.iterator(); // Printing the unique words of the string. System.out.println("Printing the unique words of the given string::"); for (int i = 1; i <= 20 &&iter.hasNext(); i++) // using iterator function to read the elements of hash set. System.out.print(" "+ iter.next()+ " "); } } Output:
  • 9.
    Printing the uniquewords of the given string:: is test a This 8) Given a string print the reverse of the string. package Assignment; // program for printing the reverse of the string. publicclassStringReverse { publicstaticvoid main(String[] args) { Stringstr = "molecule"; String reverse =""; int i=0; // printing the original string System.out.println("Original String:: "+ str); // converting string to character array. char rev[] = str.toCharArray(); // appending characters to reverse string. for (i=rev.length-1;i>=0;i--) { reverse = reverse + rev[i]; } System.out.println(); // Printing the reversed String System.out.println("Reversed String is:: " + reverse); } } Output: Original String:: molecule Reversed String is::elucelom 9) Given a string print the string in same flow, but reversing each word of it. package Assignment; importjava.util.Scanner; publicclassReaverseEach { publicstaticvoid main(String[] args) { String sample = "This string is being checked"; Scanner in = newScanner(sample);
  • 10.
    ReaverseEach rev =newReaverseEach(); String word=""; String Output=""; while (in.hasNext()) { word = in.next(); Output = Output + rev.reverseString(word)+" "; } System.out.println("The original string is::"); System.out.println(sample); System.out.println(); System.out.println("The String with reversed words are printed below::"); System.out.println(Output); } public String reverseString(String str) { //String str = "molecule"; String reverse =""; int i=0; // printing the original string //System.out.println("Original String:: "+ str); // converting string to character array. char rev[] = str.toCharArray(); // appending characters to reverse string. for (i=rev.length-1;i>=0;i--) { reverse = reverse + rev[i]; } //System.out.println(); // Printing the reversed String //System.out.println("Reversed String is:: " + reverse); return reverse; } } Output: The original string is:: This string is being checked The String with reversed words are printed below:: sihTgnirtssigniebdekcehc
  • 11.
    10) Read afile content and write it to a new file in reverse order.(reverse line 1-10 to line 10-1) package Assignment; import java.io.*; importjava.util.LinkedList; publicclassReverseFile { publicstaticvoid main(String args[]) { try{ // using fileinputstream to read contents inputFile.txt FileInputStreamfstream = newFileInputStream("C:UsersSunil KumarDesktopWhite Box TrainingJava ProgramsAssignmentinputFile.txt"); DataInputStream in = newDataInputStream(fstream); BufferedReaderbr = newBufferedReader(newInputStreamReader(fstream)); String strLine; // using LinkedList to store the lines in the file. LinkedList<String> list = newLinkedList<String>(); //Reading input file line by line while ((strLine = br.readLine()) != null) { list.add(strLine); } // Opening the outPut.txt file using FileWriter. FileWriterfilestream = newFileWriter("C:UsersSunil KumarDesktopWhite Box TrainingJava ProgramsAssignmentoutputFile.txt"); BufferedWriter out = newBufferedWriter(filestream); // Writing the lines in reverse fashion into outputFile.txt int i; intlen = list.size(); for (i=len-1;i>=0;i--) { out.write(list.get(i)); out.write("n"); } out.close(); in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } }
  • 12.
    } Output: inputFile.txt First line. Second Line. ThirdLine. Fourth Line. Fifth Line. Sixth Line. Seventh Line. Eighth Line. Ninth Line. Tenth Line. outputFile.txt Tenth Line. Ninth Line. Eighth Line. Seventh Line. Sixth Line. Fifth Line. Fourth Line. Third Line. Second Line. First line. 11) Write a java program which provides API for database "select" and "Update". package MySQL; import java.sql.*; publicclassDBAccess { publicstatic Statement s = null; publicstatic Connection conn = null; publicResultSet execute(String query) { ResultSetrs = null; try {
  • 13.
    // Execute thequery and return the ResultSet s.executeQuery(query); rs = s.getResultSet(); } catch (Exception e) { System.err.println ("Cannot connect to database server"); System.out.println(e); //e.printStackTrace(); } returnrs; } publicint update(String query) { int count = 0; try { count = s.executeUpdate(query); } catch (Exception e) { System.err.println("Cannot conect to database server."); System.out.println(e); } return count; } publicstaticvoid main (String[] args) { //Connection conn = null; DBAccessdb = newDBAccess(); try { String userName = "root"; String password = "good"; // localhost - Name of the server. String url = "jdbc:mysql://localhost/test"; // Create one driver instance and create one or more connection instances. // Standard syntax of creating instance of singleton class. Class.forName ("com.mysql.jdbc.Driver").newInstance (); // Connection instance using the Driver. conn = DriverManager.getConnection (url, userName, password);
  • 14.
    System.out.println ("Database connectionestablished"); s = conn.createStatement (); int count; // Two types of methods present in the JDBC code - executeUpdate and executeQuery // Passing the query and updating the record. String query2 = "Update EMP set email='hare@gmail.com' where id = 2;"; count = db.update(query2); System.out.println("Updated record count = " + count); // Passing query and s executing query and returning rs. String query1 = "select * from EMP"; ResultSetrs = db.execute(query1); while (rs.next ()) { intidVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("email"); System.out.println ( "id = " + idVal + ", name = " +nameVal + ", email = " + catVal); ++count; } rs.close (); s.close (); s.close (); // System.out.println (count + " rows were inserted"); } catch (Exception e) { System.err.println ("Cannot connect to database server"); System.out.println(e); e.printStackTrace(); } finally { if (conn != null) {
  • 15.
    try { conn.close (); System.out.println ("Databaseconnection terminated"); } catch (Exception e) { /* ignore close errors */ } } } } } Output: Database connection established Updated record count = 1 id = 1, name = Sunil, email = abcded@gmail.com id = 2, name = Manish, email = hare@gmail.com id = 1, name = Balaji, email = abcded@gmail.com Database connection terminated