SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Operators
OperatorsOperators
Operatorsvvpadhu
 
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 APIjagriti srivastava
 
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 180Mahmoud Samir Fayed
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and EffectsRaymond Roestenburg
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Interface
InterfaceInterface
Interfacevvpadhu
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonLifna C.S
 
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 88Mahmoud Samir Fayed
 
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 181Mahmoud Samir Fayed
 
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 185Mahmoud Samir Fayed
 
Computer java programs
Computer java programsComputer java programs
Computer java programsADITYA BHARTI
 
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 202Mahmoud Samir Fayed
 

Was ist angesagt? (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
 

Andere mochten auch

3.4 selection sort
3.4 selection sort3.4 selection sort
3.4 selection sortKrish_ver2
 
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 examplesSunil Kumar Gunasekaran
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questionsArun Banotra
 
3 searching algorithms in Java
3 searching algorithms in Java3 searching algorithms in Java
3 searching algorithms in JavaMahmoud Alfarra
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manualAnil Bishnoi
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data StructureJeanie Arnoco
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-SortTareq Hasan
 
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 TimeAndres Mendez-Vazquez
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap SortMohammed Hussein
 
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 6Jeanie Arnoco
 

Andere mochten auch (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
 

Ähnlich wie 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.pdfeyewatchsystems
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory archana singh
 
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.pdfarri2009av
 
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.pdfRahul04August
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfRohitkumarYadav80
 
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.pdfakkhan101
 
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.docxandreecapon
 
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.pdfrushabhshah600
 
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.docxajoy21
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
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.pdfarishmarketing21
 
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.pdfactocomputer
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 

Ähnlich wie 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
 

Mehr von 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 shotsSunil Kumar Gunasekaran
 
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 SystemSunil 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 coveredSunil 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 applicationsSunil Kumar Gunasekaran
 
Fitnesse user acceptance test - Presentation
Fitnesse   user acceptance test - PresentationFitnesse   user acceptance test - Presentation
Fitnesse user acceptance test - PresentationSunil Kumar Gunasekaran
 

Mehr von 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
 

Kürzlich hochgeladen

ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 

Kürzlich hochgeladen (20)

ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 

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