SlideShare a Scribd company logo
1 of 15
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

More Related Content

What's hot

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 

What's hot (20)

Operators
OperatorsOperators
Operators
 
Array properties
Array propertiesArray properties
Array properties
 
GANs
GANsGANs
GANs
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Manual specialization
Manual specializationManual specialization
Manual specialization
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Interface
InterfaceInterface
Interface
 
Java programs
Java programsJava programs
Java programs
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
 
Python array
Python arrayPython array
Python array
 
The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
The Ring programming language version 1.5.4 book - Part 33 of 185
The Ring programming language version 1.5.4 book - Part 33 of 185The Ring programming language version 1.5.4 book - Part 33 of 185
The Ring programming language version 1.5.4 book - Part 33 of 185
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Computer java programs
Computer java programsComputer java programs
Computer java programs
 
The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202
 

Viewers also liked

JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 

Viewers also liked (12)

Java Sorting Algorithms
Java Sorting AlgorithmsJava Sorting Algorithms
Java Sorting Algorithms
 
3.4 selection sort
3.4 selection sort3.4 selection sort
3.4 selection sort
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
3 searching algorithms in Java
3 searching algorithms in Java3 searching algorithms in Java
3 searching algorithms in Java
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manual
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data Structure
 
Selection sort
Selection sortSelection sort
Selection sort
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
 
06 Analysis of Algorithms: Sorting in Linear Time
06 Analysis of Algorithms:  Sorting in Linear Time06 Analysis of Algorithms:  Sorting in Linear Time
06 Analysis of Algorithms: Sorting in Linear Time
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
 
Introduction to programming using Visual Basic 6
Introduction to programming using Visual Basic 6Introduction to programming using Visual Basic 6
Introduction to programming using Visual Basic 6
 

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

Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
eyewatchsystems
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
ravikapoorindia
 
Write a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfWrite a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdf
arri2009av
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
Rahul04August
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
akkhan101
 
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxMETA-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
andreecapon
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
rushabhshah600
 
Refer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdfRefer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdf
arishmarketing21
 
FileName EX06_1java Programmer import ja.pdf
FileName EX06_1java Programmer  import ja.pdfFileName EX06_1java Programmer  import ja.pdf
FileName EX06_1java Programmer import ja.pdf
actocomputer
 

Similar to Java programs - bubble sort, iterator, linked list, hash set, reverse string, reverse number fibonnacci (20)

Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
 
Write a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfWrite a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdf
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxMETA-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 
Write an application that stores 12 integers in an array. Display the.docx
 Write an application that stores 12 integers in an array. Display the.docx Write an application that stores 12 integers in an array. Display the.docx
Write an application that stores 12 integers in an array. Display the.docx
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Refer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdfRefer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdf
 
Array list
Array listArray list
Array list
 
FileName EX06_1java Programmer import ja.pdf
FileName EX06_1java Programmer  import ja.pdfFileName EX06_1java Programmer  import ja.pdf
FileName EX06_1java Programmer import ja.pdf
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 

More from Sunil Kumar Gunasekaran

Sample Technical Requirement Document (TRD)
Sample Technical Requirement Document (TRD)Sample Technical Requirement Document (TRD)
Sample Technical Requirement Document (TRD)
Sunil Kumar Gunasekaran
 
Sql commands worked out in sql plus with screen shots
Sql commands worked out in sql plus with screen shotsSql commands worked out in sql plus with screen shots
Sql commands worked out in sql plus with screen shots
Sunil Kumar Gunasekaran
 
Test Life Cycle - Presentation - Important concepts covered
Test Life Cycle - Presentation - Important concepts coveredTest Life Cycle - Presentation - Important concepts covered
Test Life Cycle - Presentation - Important concepts covered
Sunil Kumar Gunasekaran
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
Sunil Kumar Gunasekaran
 
Fitnesse user acceptance test - Presentation
Fitnesse   user acceptance test - PresentationFitnesse   user acceptance test - Presentation
Fitnesse user acceptance test - Presentation
Sunil Kumar Gunasekaran
 

More from Sunil Kumar Gunasekaran (20)

CQL - Cassandra commands Notes
CQL - Cassandra commands NotesCQL - Cassandra commands Notes
CQL - Cassandra commands Notes
 
Java J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus ChecklistJava J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus Checklist
 
Amazon search test case document
Amazon search test case documentAmazon search test case document
Amazon search test case document
 
Actual test case document
Actual test case documentActual test case document
Actual test case document
 
Sample Technical Requirement Document (TRD)
Sample Technical Requirement Document (TRD)Sample Technical Requirement Document (TRD)
Sample Technical Requirement Document (TRD)
 
Sql reference from w3 schools
Sql reference from w3 schools Sql reference from w3 schools
Sql reference from w3 schools
 
Sql commands worked out in sql plus with screen shots
Sql commands worked out in sql plus with screen shotsSql commands worked out in sql plus with screen shots
Sql commands worked out in sql plus with screen shots
 
Wells fargo banking system ER Diagram
Wells fargo banking system ER DiagramWells fargo banking system ER Diagram
Wells fargo banking system ER Diagram
 
Business Requirements Document for Acounts Payable System
Business Requirements Document for Acounts Payable SystemBusiness Requirements Document for Acounts Payable System
Business Requirements Document for Acounts Payable System
 
Automation Testing Syllabus - Checklist
Automation Testing Syllabus - ChecklistAutomation Testing Syllabus - Checklist
Automation Testing Syllabus - Checklist
 
Unix short
Unix shortUnix short
Unix short
 
Unix made easy
Unix made easyUnix made easy
Unix made easy
 
Test process - Important Concepts
Test process - Important ConceptsTest process - Important Concepts
Test process - Important Concepts
 
Testing http methods using Telnet
Testing http methods using TelnetTesting http methods using Telnet
Testing http methods using Telnet
 
Test Life Cycle - Presentation - Important concepts covered
Test Life Cycle - Presentation - Important concepts coveredTest Life Cycle - Presentation - Important concepts covered
Test Life Cycle - Presentation - Important concepts covered
 
Scrum writeup - Agile
Scrum writeup - Agile Scrum writeup - Agile
Scrum writeup - Agile
 
Scrum, V Model and RUP Models Overview
Scrum, V Model and RUP Models OverviewScrum, V Model and RUP Models Overview
Scrum, V Model and RUP Models Overview
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Fitnesse user acceptance test - Presentation
Fitnesse   user acceptance test - PresentationFitnesse   user acceptance test - Presentation
Fitnesse user acceptance test - Presentation
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 

Recently uploaded

Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Recently uploaded (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

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

  • 1. 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
  • 2. 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. 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. 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]; } }
  • 5. // 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;
  • 6. 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
  • 7. }// 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
  • 8. 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:
  • 9. 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);
  • 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 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()); } }
  • 12. } 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 {
  • 13. // 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);
  • 14. 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) {
  • 15. 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