Java
Assignments
Q18. What is open source? Is JAVA open source?
Q19. Define open JDK and Oracle JDK.
Q20. What is IDE. Name some JAVA IDE’s
Q21. What is code editor?
Q22. What is JAVA compiler?
Q23. What is your first experience to join COMPUHELP?
Q1. Write an object oriented Program in Java to add, subtract and multiply two numbers.
Q2. Write OOP Program to get the following:
am. subtract(10,5);
ans=am. multiply(10,5);
System.out.println(am.division(10,5));
Q3. Describe the following code:
Q4. Create following.
WAP to get the Information of a student like
Student Name
Student Rollno
Student Fee
Student Marks
and define the suitable methods to do the following tasks.
str=getName();
setRollno(177);
rollno=getRollno();
setFee(25000);
fee=getFee();
setMarks(45);
marks=getMarks();
setData(“Kajal”, 178, 5500, 65);
displayData();
Q1. Enter a string from the user and count the length of the entered string.
Q2. Enter a string “COMPUHELP” from the user and count the number of vowels in it.
Q3. Enter a string from the user in lower case and change all the vowels of the entered
string in upper case.
Q4. Enter a string from the user and count the number of words present in the entered
string.
Q5. Enter a String from the user and print those characters that they have space before
them.
Q6. Enter a string from the user and count how many times only two vowels occur
together in the entered string.
Q7. Enter a string from the user and print the first and last word of the entered string.
Q8. Enter a string from the user in uppercase and change each vowel present at the end of
the words of the entered string in lowercase.
Q9. Enter two strings from the user and check if both the strings are equal or not. If the two
strings are equal then print “strings are equal” otherwise print “strings are not equal”.
Q10. Enter a string from the user and concatenate the alternative words of the string
together.
Q11. Enter a string from the user in lowercase and capitalize each word of the string.
Q12. Enter a string “Compuhelp” from the user and print only “help” from the entered
string.
Q13. Enter a string from the user and find the first and last index number of the character
entered by the user.
1. Write
a Java Program to merge two arrays.
2. Write
a Java Program to fill (initialize at once) an array.
3. Write
a Java Program to extend an array after initialisation.
4. Write
a Java Program to sort an array and search an element inside it.
5. Write
a Java Program to remove an element of
array.
6. Write
a Java Program to remove one array from
another array.
7. Write
a Java Program to find common elements
from arrays.
8. Write
a Java Program to find an object or a
string in an Array.
9. Write
a Java Program to check if two arrays
are equal or not.
10. Write
a Java Program to compare two arrays.
Date
& Time
1. Write
a Java Program to format time in AM-PM
format.
2. Write
a Java Program to display name of a
month in (MMM) format .
3. Write
a Java Program to display hour and
minute.
4. Write
a Java Program to display current date
and time.
5. Write
a Java Program to format time in 24 hour
format.
6. Write
a Java Program to format time in MMMM
format.
7. Write
a Java Program to format seconds.
8. Write
a Java Program to display name of the months in short format.
9. Write
a Java Program to display name of the weekdays.
10. Write
a Java Program to add time to Date.
11. Write
a Java Program to display time in different country's format.
12. Write
a Java Program to display time in different languages.
13. Write
a Java Program to roll through hours & months.
14. Write
a Java Program to find which week of the year.
15. Write
a Java Program to display date in different formats .
Methods
1.
Write a Java Program to
overload methods.
Code : class MyClass {
int height;
MyClass() {
System.out.println("bricks");
height = 0;
}
MyClass(int i) {
System.out.println("Building new
House that is "
+ i + " feet tall");
height = i;
}
void info() {
System.out.println("House is "
+ height
+ " feet tall");
}
void info(String s) {
System.out.println(s + ": House is
"
+ height + " feet tall");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass t = new MyClass(0);
t.info();
t.info("overloaded method");
Code :
Code : Overloaded
constructor:
new MyClass();
}
}
Output : Building
new House that is 0 feet tall.
House
is 0 feet tall.
Overloaded
method: House is 0 feet tall.
Bricks
2.
Write a Java Program to
use method overloading for printing different types of array.
Code : public class MainClass {
public static void printArray(Integer[] inputArray) {
for (Integer element : inputArray){
System.out.printf("%s ",
element);
System.out.println();
}
}
public static void printArray(Double[] inputArray) {
for (Double element : inputArray){
System.out.printf("%s ",
element);
System.out.println();
}
}
public static void printArray(Character[] inputArray) {
for (Character element : inputArray){
System.out.printf("%s ",
element);
System.out.println();
}
}
public static void main(String args[]) {
Integer[] integerArray = { 1, 2, 3, 4, 5,
6 };
Double[] doubleArray = { 1.1, 2.2, 3.3,
4.4,
5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E',
'L', 'L', 'O' };
System.out.println("Array
integerArray contains:");
printArray(integerArray);
System.out.println("Output : nArray doubleArray contains:");
printArray(doubleArray);
System.out.println("Output : nArray characterArray contains:");
printArray(characterArray);
}
}
Output : Array
integerArray contains:
1
2
3
4
5
6
Array doubleArray contains:
1.1
2.2
3.3
4.4
5.5
6.6
7.7
Array characterArray contains:
H
E
L
L
O
3.
Write a Java Program to
use method for solving Tower of Hanoi problem.
Code : public
class MainClass {
public static void main(String[]
args) {
int nDisks = 3;
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int
topN, char from,
char inter, char to) {
if (topN == 1){
System.out.println("Disk 1
from "
+ from + " to " + to);
}else {
doTowers(topN - 1, from, to,
inter);
System.out.println("Disk
"
+ topN + " from " + from
+ " to " + to);
doTowers(topN - 1, inter, from,
to);
}
}
}
Output : Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C
4.
Write a Java Program to
use method for calculating Fibonacci series.
Code : public class MainClass {
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) +
fibonacci(number - 2);
}
public static void main(String[] args) {
for (int counter = 0; counter <= 10;
counter++){
System.out.printf("Fibonacci of
%d is: %dOutput : n",
counter, fibonacci(counter));
}
}
}
Output : Fibonacci
of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55
5.
Write a Java Program to
use method for calculating Factorial of a number.
Code : public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10;
counter++){
System.out.printf("%d! = %dOutput
: n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}
Output : 0! =
1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
6.
Write a Java Program to
use method overriding in Inheritance for subclasses.
Code : public class Findareas{
public static void main (String
[]agrs){
Figure f= new Figure(10 , 10);
Rectangle r= new Rectangle(9 , 5);
Figure figref;
figref=f;
System.out.println("Area is
:"+figref.area());
figref=r;
System.out.println("Area is
:"+figref.area());
}
}
class Figure{
double dim1;
double dim2;
Figure(double a , double b) {
dim1=a;
dim2=b;
}
Double area() {
System.out.println("Inside area for
figure.");
return(dim1*dim2);
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a ,b);
}
Double area() {
System.out.println("Inside area for
rectangle.");
return(dim1*dim2);
}
}
Output : Inside
area for figure.
Area
is :100.0
Inside
area for rectangle.
Area
is :45.0
7.
Write a Java Program to
display Object class using instanceOf keyword.
Code : import java.util.ArrayList;
import java.util.Vector;
public class Main {
public static void main(String[]
args) {
Object testObject = new ArrayList();
displayObjectClass(testObject);
}
public static void displayObjectClass(Object o) {
if (o instanceof Vector)
System.out.println("Object was an
instance
of the class java.util.Vector");
else if (o instanceof ArrayList)
System.out.println("Object was an
instance of
the class java.util.ArrayList");
else
System.out.println("Object was an
instance of the "
+ o.getClass());
}
}
Output : Object
was an instance of the class java.util.ArrayList.
8.
Write a Java Program to
use break to jump out of a loop in a method.
Code : public
class Main {
public static void main(String[] args) {
int[] intary = {
99,12,22,34,45,67,5678,8990 };
int no = 5678;
int i = 0;
boolean found = false;
for ( ; i < intary.length; i++) {
if (intary[i] == no) {
found = true;
break;
}
}
if (found) {
System.out.println("Found the no:
" + no
+ " at index: " + i);
}
else {
System.out.println(no + "not
found in the array");
}
}
}
Output : Found
the no: 5678 at index: 6
9.
Write a Java Program to
use continue in a method.
Code : public class Main {
public static void main(String[] args) {
StringBuffer searchstr = new
StringBuffer(
"hello how are you. ");
int length = searchstr.length();
int count = 0;
for (int i = 0; i 7lt; length; i++) {
if (searchstr.charAt(i) != 'h')
continue;
count++;
searchstr.setCharAt(i, 'h');
}
System.out.println("Found " +
count
+ " h's in the string.");
System.out.println(searchstr);
}
}
Output : Found
2 h's in the string.
hello how are you.
10.
Write a Java Program to
use Label in a method.
Code : public class Main {
public
static void main(String[] args) {
String strSearch = "This is the
string in which you
have to search for a substring.";
String substring = "substring";
boolean found = false;
int max = strSearch.length() -
substring.length();
testlbl:
for (int i = 0; i < = max; i++) {
int length = substring.length();
int j = i;
int k = 0;
while (length-- != 0) {
if(strSearch.charAt(j++) !=
substring.charAt(k++){
continue testlbl;
}
}
found = true;
break testlbl;
}
if (found) {
System.out.println("Found the
substring .");
}
else {
System.out.println("did not find
the
substing in the string.");
}
}
}
Output : Found
the substring .
11.
Write a Java Program to
use enum& switch statement .
Code : enum Car {
lamborghini,tata,audi,fiat,honda
}
public class Main {
public static void main(String args[]){
Car c;
c = Car.tata;
switch(c) {
case lamborghini:
System.out.println("You choose
lamborghini!");
break;
case tata:
System.out.println("You choose
tata!");
break;
case audi:
System.out.println("You choose
audi!");
break;
case fiat:
System.out.println("You choose
fiat!");
break;
case honda:
System.out.println("You choose
honda!");
break;
default:
System.out.println("I don't know
your car.");
break;
}
}
}
Output : You
choose tata!
12.
Write a Java Program to
make enum constructor, instance variable & method.
Code : enum
Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("All car
prices:");
for (Car c : Car.values())
System.out.println(c + " costs
"
+ c.getPrice() + " thousand
dollars.");
}
}
Output : All
car prices:
lamborghini costs 900 thousand
dollars.
tata costs 2 thousand dollars.
audi costs 50 thousand dollars.
fiat costs 15 thousand dollars.
honda costs 12 thousand dollars.
13.
Write a Java Program to
use for and foreach loop for printing values of an array .
Code : public class Main {
public static void
main(String[] args) {
int[] intary = { 1,2,3,4};
forDisplay(intary);
foreachDisplay(intary);
}
public static void forDisplay(int[] a){
System.out.println("Display an array
using for loop");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "
");
}
System.out.println();
}
public static void foreachDisplay(int[] data){
System.out.println("Display an array
using for
each loop");
for (int a : data) {
System.out.print(a+ " ");
}
}
}
Output : Display
an array using for loop
1 2 3 4
Display an array using for each loop
1 2 3 4
14.
Write a Java Program to
make a method take variable lentgth argument as an input.
Code : public class Main {
static int sumvarargs(int...
intArrays){
int sum, i;
sum=0;
for(i=0; i< intArrays.length; i++) {
sum += intArrays[i];
}
return(sum);
}
public static void main(String args[]){
int sum=0;
sum = sumvarargs(new int[]{10,12,33});
System.out.println("The sum of the
numbers is: " + sum);
}
}
Output : The
sum of the numbers is: 55
15.
Write a Java Program to
use variable arguments as an input when dealing with method overloading.
Code : public
class Main {
static void vaTest(int ... no) {
System.out.print("vaTest(int ...):
"
+ "Number of args: " +
no.length +" Contents: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
static void vaTest(boolean ... bl) {
System.out.print("vaTest(boolean
...) " +
"Number of args: " + bl.length
+ " Contents: ");
for(boolean b : bl)
System.out.print(b + " ");
System.out.println();
}
static void vaTest(String msg, int ... no) {
System.out.print("vaTest(String, int
...): " +
msg +"no. of arguments: "+
no.length +" Contents: ");
for(int
n : no)
System.out.print(n + " ");
System.out.println();
}
public static void main(String args[]){
vaTest(1, 2, 3);
vaTest("Testing: ", 10, 20);
vaTest(true, false, false);
}
}
Output : vaTest(int
...): Number of args: 3 Contents: 1 2 3
vaTest(String, int ...): Testing:
no. of arguments: 2
Contents: 10 20
vaTest(boolean ...) Number of args:
3 Contents:
true false false
Files
1.
Write a Java Program to compare paths of two files.
Code : import java.io.File;
public class Main {
public static void main(String[] args) {
File file1 = new File("C:Code : FileCode :
demo1.txt");
File file2 = new File("C:Code : javaCode :
demo1.txt");
if(file1.compareTo(file2) == 0) {
System.out.println("Both paths
are same!");
} else {
System.out.println("Paths are not
same!");
}
}
}
Output : Paths
are not same!
2.
Write a Java
Program to create a new file.
Code : import
java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try{
File file = new File("C:Code
: myfile.txt");
if(file.createNewFile())
System.out.println("Success!");
else
System.out.println
("Error, file already
exists.");
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
Output : Success!
3.
Write a Java
Program to get last modification date of
a file.
Code : import
java.io.File;
import java.util.Date;
public class Main {
public static void main(String[] args) {
File file = new
File("Main.java");
Long lastModified = file.lastModified();
Date date = new Date(lastModified);
System.out.println(date);
}
}
Output : Tue
12 May 10:18:50 PDF 2009
4.
Write a Java
Program to create a file in a specified
directory.
Code : import java.io.File;
public
class Main {
public static void main(String[] args)
throws Exception {
File file = null;
File dir = new File("C:Code : ");
file = File.createTempFile
("JavaTemp",
".javatemp", dir);
System.out.println(file.getPath());
}
}
Output : C:Output
: JavaTemp37056.javatemp
5.
Write a Java
Program to check a file exist or not.
Code
: import
java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:Code : java.txt");
System.out.println(file.exists());
}
}
Output : true.
6.
Write a Java
Program to make a file read-only.
Code
: import
java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:Code : java.txt");
System.out.println(file.setReadOnly());
System.out.println(file.canWrite());
}
}
Output : true
false
7.
Write a Java
Program to renaming a file .
Code : import java.io.File;
public class Main {
public static void main(String[] args) {
File oldName = new File("C:Code
: program.txt");
File newName = new File("C:Code
: java.txt");
if(oldName.renameTo(newName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
}
Output : renamed.
8.
Write a Java
Program to get a file's size in bytes.
Code
: import
java.io.File;
public class Main {
public static long getFileSize(String
filename) {
File file = new File(filename);
if (!file.exists() || !file.isFile()) {
System.out.println("File doesnOutput
: 't exist");
return -1;
}
return file.length();
}
public static void main(String[] args) {
long size = getFileSize("c:Code
: java.txt");
System.out.println("Filesize in
bytes: " + size);
}
}
Output : File
size in bytes: 480
9.
Write a Java
Program to change the last modification
time of a file .
Code : import java.io.File;
import java.util.Date;
public class Main {
public static void main(String[] args)
throws Exception {
File fileToChange = new File
("C:Code : myjavafile.txt");
fileToChange.createNewFile();
Date filetime = new Date
(fileToChange.lastModified());
System.out.println(filetime.toString());
System.out.println
(fileToChange.setLastModified
(System.currentTimeMillis()));
filetime = new Date
(fileToChange.lastModified());
System.out.println(filetime.toString());
}
}
Output : Sat
Oct 18 19:58:20 GMT+05:30 2008
true
Sat Oct 18 19:58:20 GMT+05:30 2008
10.
Write a Java
Program to create a temporary file.
Code : import
java.io.*;
public class Main {
public
static void main(String[] args)
throws Exception {
File temp = File.createTempFile
("pattern",
".suffix");
temp.deleteOnExit();
BufferedWriter out = new BufferedWriter
(new FileWriter(temp));
out.write("aString");
System.out.println("temporary file
created:");
out.close();
}
}
Output : temporary
file created:
11.
Write a Java
Program to append a string in an
existing file.
Code
: import java.io.*;
public class Main {
public static void main(String[] args)
throws Exception {
try {
BufferedWriter out = new BufferedWriter
(new
FileWriter("filename"));
out.write("aString1Output : n");
out.close();
out =
new BufferedWriter(new FileWriter
("filename",true));
out.write("aString2");
out.close();
BufferedReader in = new BufferedReader
(new
FileReader("filename"));
String str;
while
((str = in.readLine()) != null) {
System.out.println(str);
}
}
in.close();
catch
(IOException e) {
System.out.println("exception occoured"+ e);
}
}
}
Output : aString1
aString2
12.
Write a Java
Program to copy one file into another
file.
Code : import java.io.*;
public class Main {
public static void
main(String[] args)
throws Exception {
BufferedWriter out1 = new BufferedWriter
(new FileWriter("srcfile"));
out1.write("string to be copiedOutput
: n");
out1.close();
InputStream in = new FileInputStream
(new File("srcfile"));
OutputStream out = new FileOutputStream
(new File("destnfile"));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
BufferedReader in1 = new BufferedReader
(new FileReader("destnfile"));
String str;
while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in.close();
}
}
Output : string
to be copied
13.
Write a Java
Program to delete a file.
Code : import
java.io.*;
public class Main {
public static void main(String[]
args) {
try {
BufferedWriter out = new
BufferedWriter
(new
FileWriter("filename"));
out.write("aString1Output : n");
out.close();
boolean success = (new File
("filename")).delete();
if (success) {
System.out.println("The file
has
been successfully deleted");
}
BufferedReader in = new BufferedReader
(new
FileReader("filename"));
String str;
while ((str = in.readLine())
!= null) {
System.out.println(str);
}
in.close();
}
catch (IOException e) {
System.out.println("exception
occoured"+ e);
System.out.println("File does
not exist
or you are trying to read a file
that
has been deleted");
}
}
}
}
Output : The
file has been successfully deleted
exception
occouredjava.io.FileNotFoundException:
filename (The system cannot find
the file specified)
File does not exist or you are
trying to read a
file that has been deleted
14.
Write a Java
Program to read a file.
Code : import java.io.*;
public class Main {
public static void main(String[] args)
{
try {
BufferedReader in = new BufferedReader
(new FileReader("c:Output : Output :
filename"));
String str;
while ((str = in.readLine()) != null)
{
System.out.println(str);
}
System.out.println(str);
}
catch (IOException e) {
}
}
}
}
Output : aString.
15.
Write a Java
Program to write to a file.
Code
: import
java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter out = new
BufferedWriter(new
FileWriter("outfilename"));
out.write("aString");
out.close();
System.out.println
("File created
successfully");
}
catch (IOException e) {
}
}
}
Output
: File created successfully.
Directories
1.
Write a Java
Program to create directories
recursively.
Code
: import java.io.File;
public class Main {
public static void main(String[] args) {
String directories = "D:\ \ a\ \ b\ \ c\ \ d\ \ e\ \ f\ \ g\ \ h\ \ i";
File file = new File(directories);
boolean result = file.mkdirs();
System.out.println("Status = "
+ result);
}
}
Output
: Status = true.
2.
Write a Java
Program to delete a directory.
Code
: import
java.io.File;
public
class Main {
public static void main(String[] argv)
throws Exception {
deleteDir(new File("c:Output :
Output : temp"));
}
public
static boolean deleteDir(File dir) {
if
(dir.isDirectory()) {
String[] children = dir.list();
for (int
i = 0; i < children.length; i++) {
boolean success = deleteDir
(new File(dir, children[i]));
if
(!success) {
return false;
}
}
}
return
dir.delete();
System.out.println("The directory is deleted.");
}
}
Output
: The directory is deleted.
3. Write
a Java Program to get the fact that a
directory is empty or not.
Code : import
java.io.File;
public class
Main {
public static void main(String[] args) {
File file = new File("Code : data");
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
System.out.println("The "
+ file.getPath() +
" is not empty!");
}
}
}
}
Output : The
D:Code : Code
: JavaCode
: file.txt
is not empty!.
3.
Write a Java
Program to get a directory is hidden or
not.
Code : import java.io.File;
public class
Main {
public static void main(String[] args) {
File file = new File("C:Code : Demo.txt");
System.out.println(file.isHidden());
}
}
Output :
True.
4.
Write a Java
Program to print the directory
hierarchy.
Code :
import java.io.File;
import
java.io.IOException;
public class FileUtil {
public static void main(String[] a)throws
IOException{
showDir(1, new File("d:Output : Output :
Java"));
}
static void showDir(int indent, File file)
throws IOException {
for (int i = 0; i 7lt; indent; i++)
System.out.print('-');
System.out.println(file.getName());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length;
i++)
showDir(indent + 4, files[i]);
}
}
}
Output :
-Java
-----codes
---------string.txt
---------array.txt
-----tutorial
6. Write
a Java Program to print the last
modification time of a directory.
Code : import
java.io.File;
import
java.util.Date;
public
class Main {
public static void main(String[] args) {
File file = new File("C:Code : Code : FileIOCode
: Code :
demo.txt");
System.out.println("last modifed:"
+
new Date(file.lastModified()));
}
}
Output :
last modifed:10:20:54.
7. Write
a Java Program to get the parent
directory of a file.
Code : import
java.io.File;
public class
Main {
public static void main(String[] args) {
File file = new File("C:Code : FileCode :
demo.txt");
String strParentDirectory =
file.getParent();
System.out.println("Parent directory
is : "
+ strParentDirectory);
}
}
Output :
Parent directory is : File.
8. Write
a Java Program to search all files
inside a directory.
Code :
import java.io.File;
public
class Main {
public static void main(String[] argv)
throws Exception {
File dir = new
File("directoryName");
String[] children = dir.list();
if (children == null) {
System.out.println("does not
exist or
is not a directory");
}
else {
for (int i = 0; i <
children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Output :
sdk
---vehicles
------body.txt
------color.txt
------engine.txt
---ships
------shipengine.txt
9. Write
a Java Program to get the size of a
directory.
Code :
import java.io.File;
import
org.apache.commons.io.FileUtils;
public
class Main {
public static void main(String[] args) {
long size = FileUtils.sizeOfDirectory
(new File("C:Code : Windows"));
System.out.println("Size: " +
size + " bytes");
}
}
Output :
Size: 2048 bytes.
10. Write
a Java Program to traverse a directory.
Code :
import java.io.File;
public
class Main {
public static void main(String[] argv)
throws Exception {
System.out.println("The Directory is
traversed.");
visitAllDirsAndFiles(C:Code : Code : Java);
}
public static void visitAllDirsAndFiles(File
dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i <
children.length; i++) {
visitAllDirsAndFiles
(new File(dir, children[i]));
}
}
}
}
Output : The Directory is traversed.
11. Write
a Java Program to find current working
directory.
Code : class Main {
public static void main(String[] args) {
String curDir =
System.getProperty("user.dir");
System.out.println("You currently
working in :"
+ curDir+ ": Directory");
}
}
Output :
You currently working in :C:Output :
Documents and SettingsOutput : userOutput:
My DocumentsOutput : NetBeansProjectsOutput : TestApp: Directory
12. Write
a Java Program to display root
directories in the system.
Code :
import java.io.*;
class
Main{
public static void main(String[] args){
File[] roots = File.listRoots();
System.out.println("Root directories
in your system are:");
for (int i=0; i < roots.length; i++) {
System.out.println(roots[i].toString());
}
}
}
Output
: Root directories in your system are:
C:Output
:
D:Output
:
E:Output
:
F:Output
:
G:Output
:
H:Output
:
13. Write
a Java Program to search for a file in a
directory.
Code :
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:");
FilenameFilter filter = new
FilenameFilter() {
public boolean accept
(File dir, String name) {
return name.startsWith("b");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir
does not
exist or is not a directory");
}
else {
for (int i=0; i7lt; children.length;
i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Output :
build
build.xml
14. Write
a Java Program to display all the files
in a directory.
Code :
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:");
String[] children = dir.list();
if (children == null) {
System.out.println( "Either dir
does
not exist or is not a
directory");
}
else {
for (int i=0; i< children.length;
i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Output
: build
build.xml
destnfile
detnfile
filename
manifest.mf
nbproject
outfilename
src
srcfile
test
15. Write
a Java Program to display all the
directories in a directory.
Code :
import java.io.*;
class
Main {
public static void main(String[] args) {
File dir = new File("F:");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter()
{
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("Either dir
does not exist
or is not a directory");
}
else {
for (int i=0; i< files.length; i++)
{
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}
Output :
14
F:Output
: C Drive Data Old HDD
F:Output
: Desktop1
F:Output
: harsh
F:Output
: hharsh final
F:Output
: hhhh
F:Output
: mov
F:Output
: msdownld.tmp
F:Output
: New Folder
F:Output
: ravi
F:Output
: ravi3
F:Output
: RECYCLER
F:Output
: System Volume Information
F:Output
: temp
F:Output
: work
Exceptions
1.
Write a Java
Program to use finally block for catching
exceptions.
Code : public
class ExceptionDemo2 {
public static void main(String[] argv) {
new ExceptionDemo2().doTheWork();
}
public void doTheWork() {
Object o = null;
for (int i=0; i7lt;5; i++) {
try {
o = makeObj(i);
}
catch (IllegalArgumentException e) {
System.err.println
("Error: ("+
e.getMessage()+").");
return;
}
finally {
System.err.println("All done");
if (o==null)
System.exit(0);
}
System.out.println(o);
}
}
public Object makeObj(int type)
throws IllegalArgumentException {
if (type == 1)
throw new IllegalArgumentException
("Don't like type " + type);
return new Object();
}
}
Output : All
done
java.lang.Object@1b90b39
Error: (Don't like type 1).
All done
2.
Write a Java
Program to use handle the exception
hierarchies.
Code : class
Animal extends Exception {
}
class Mammel extends Animal {
}
public class Human {
public static void main(String[] args) {
try {
throw new Mammel();
}
catch (Mammel m) {
System.err.println("It is
mammel");
}
catch (Animal a) {
System.err.println("It is
animal");
}
}
}
Output : It
is mammal.
3.
Write a Java
Program to use handle the exception
methods.
Code : public
static void main(String[] args) {
try {
throw new Exception("My
Exception");
} catch (Exception e) {
System.err.println("Caught
Exception");
System.err.println("getMessage():" + e.getMessage());
System.err.println("getLocalizedMessage():"
+ e.getLocalizedMessage());
System.err.println("toString():"
+ e);
System.err.println("printStackTrace():");
e.printStackTrace();
}
}
Output : Caught
Exception
getMassage(): My Exception
gatLocalisedMessage(): My Exception
toString():java.lang.Exception: My
Exception
print StackTrace():
java.lang.Exception: My Exception
at ExceptionMethods.main(ExceptionMeyhods.java:12)
4.
Write a Java
Program to use handle the runtime
exceptions.
Code : public
class NeverCaught {
static void f() {
throw new RuntimeException("From
f()");
}
static void g() {
f();
}
public static void main(String[] args) {
g();
}
}
Output : From
f( )
5.
Write a Java
Program to use handle the empty stack
exception .
Code : import java.util.Date;
import java.util.EmptyStackException;
import java.util.Stack;
public class ExceptionalTest {
public static void main(String[] args) {
int count = 1000000;
Stack s = new Stack();
System.out.println("Testing for
empty stack");
long s1 = System.currentTimeMillis();
for (int i = 0; i <= count; i++)
if (!s.empty())
s.pop();
long s2 = System.currentTimeMillis();
System.out.println((s2 - s1) + "
milliseconds");
System.out.println("Catching
EmptyStackException");
s1 = System.currentTimeMillis();
for (int i = 0; i <= count; i++) {
try {
s.pop();
}
catch (EmptyStackException e) {
}
}
s2 = System.currentTimeMillis();
System.out.println((s2 - s1) + "
milliseconds");
}
}
Output : Testing for empty stack
16 milliseconds
Catching EmptyStackException
3234 milliseconds
6.
Write a Java
Program to use catch to handle the
exception.
Code : public class Main{
public static void main (String args[]) {
int array[]={20,20,40};
int num1=15,num2=10;
int result=10;
try{
result = num1Code : num2;
System.out.println("The result
is" +result);
for(int i =5;i >=0; i--) {
System.out.println
("The value of array is"
+array[i]);
}
}
catch (Exception e) {
System.out.println("Exception
occoured : "+e);
}
}
}
Output
: The result is1
Exception
occoured : java.lang.ArrayIndexOutOfBoundsException: 5
7.
Write a Java
Program to use catch to handle chained
exception.
Code : public
class Main{
public static void main (String args[])throws
Exception {
int n=20,result=0;
try{
result=nCode : 0;
System.out.println("The result
is"+result);
}
catch(ArithmeticException ex){
System.out.println
("Arithmetic exception occoured:
"+ex);
try {
throw new NumberFormatException();
}
catch(NumberFormatException ex1) {
System.out.println
("Chained exception thrown
manually : "+ex1);
}
}
}
}
Output : Arithmetic
exception occoured :
java.lang.ArithmeticException: Code
: by zero
Chained exception thrown manually :
java.lang.NumberFormatException
8.
Write a Java
Program to use handle the exception with
overloaded methods .
Code : public
class Main {
double method(int i) throws Exception{
return iCode : 0;
}
boolean method(boolean b) {
return !b;
}
static double method(int x, double y) throws Exception {
return x + y ;
}
static double method(double x, double y) {
return x + y - 3;
}
public static void main(String[] args) {
Main mn = new Main();
try{
System.out.println(method(10, 20.0));
System.out.println(method(10.0, 20));
System.out.println(method(10.0,
20.0));
System.out.println(mn.method(10));
}
catch (Exception ex){
System.out.println("exception
occoure: "+ ex);
}
}
}
Output : 30.0
27.0
27.0
exception
occoure: java.lang.ArithmeticException: Code :
by zero
9.
Write a Java
Program to handle the checked
exceptions.
Code : public class Main {
public static void main (String args[]) {
try{
throw new Exception("throwing an
exception");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Output : throwing
an exception
10.
Write a Java
Program to pass arguments while throwing
checked exception.
Code : public class Main{
public static void main (String args[]) {
try {
throw new Exception("throwing an
exception");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Output : throwing
an exception
11.
Write a Java
Program to handle multiple exceptions
(devide by zero).
Code : public class Main {
public static void main (String args[]) {
int array[]={20,20,40};
int num1=15,num2=0;
int result=0;
try {
result = num1Code : num2;
System.out.println("The result
is" +result);
for(int i =2;i 7gt;=0; i--){
System.out.println
("The value of array is"
+array[i]);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println
("Error�.
Array is out of Bounds"+e);
}
catch (ArithmeticException e) {
System.out.println
("Can't be divided by
Zero"+e);
}
}
}
Output : Can't
be divided by Zerojava.lang.ArithmeticException: Code : by zero
12.
Write a Java
Program to handle multiple exceptions
(Array out of bound).
Code : public class Main {
public
static void main (String args[]) {
int
array[]={20,20,40};
int
num1=15,num2=10;
int
result=10;
try {
result = num1Code : num2;
System.out.println("The result is" +result);
for(int i =5;i >=0; i--) {
System.out.println
("The value of array is"
+array[i]);
}
}
catch
(ArrayIndexOutOfBoundsException e) {
System.out.println("Array is out of Bounds"+e);
}
catch
(ArithmeticException e) {
System.out.println ("Can't divide by Zero"+e);
}
}
}
Output : The
result is1
Array is out of
Boundsjava.lang.ArrayIndexOutOfBoundsException: 5
13.
Write a Java
Program to print stack of the Exception.
Code : public class Main{
public static void main (String args[]){
int array[]={20,20,40};
int num1=15,num2=10;
int result=10;
try{
result = num1Code : num2;
System.out.println("The result
is" +result);
for(int i =5;i *gt;=0; i--) {
System.out.println("The value
of array is"
+array[i]);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Output : The
result is1
java.lang.ArrayIndexOutOfBoundsException: 5
at testapp.Main.main(Main.java:28)
14.
Write a Java
Program to use exceptions with thread.
Code : class
MyThread extends Thread{
public void run(){
System.out.println("Throwing in
" +"MyThread");
throw new RuntimeException();
}
}
class Main {
public static void main(String[] args){
MyThread t = new MyThread();
t.start();
try{
Thread.sleep(1000);
}
catch (Exception x){
System.out.println("Caught
it" + x);
}
System.out.println("Exiting
main");
}
}
Output : Throwing
in MyThread
Exception in thread
"Thread-0" java.lang.RuntimeException
at testapp.MyThread.run(Main.java:19)
Exiting main
15.
Write a Java
Program to create user defined
Exception.
Code : class
WrongInputException extends Exception {
WrongInputException(String s) {
super(s);
}
}
class Input {
void method() throws WrongInputException {
throw new WrongInputException("Wrong
input");
}
}
class TestInput {
public static void main(String[] args){
try {
new Input().method();
}
catch(WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}
Output
: Wrong input
Data
Structures
1.
Write a Java
Program to print summation of n numbers.
Code
: import
java.io.IOException;
public class
AdditionStack {
static int num;
static int ans;
static Stack theStack;
public static void main(String[] args)
throws IOException {
num = 50;
stackAddition();
System.out.println("Sum=" +
ans);
}
public static void stackAddition() {
theStack = new Stack(10000);
ans = 0;
while (num > 0) {
theStack.push(num);
--num;
}
while (!theStack.isEmpty()) {
int newN = theStack.pop();
ans += newN;
}
}
}
class Stack {
private int maxSize;
private int[] data;
private int top;
public Stack(int s) {
maxSize = s;
data = new int[maxSize];
top = -1;
}
public void push(int p) {
data[++top] = p;
}
public int pop() {
return data[top--];
}
public int peek() {
return data[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
Output : Sum=1225
2.
Write a Java
Program to get the first and the last
element of a linked list.
Code : import java.util.LinkedList;
public class Main {
public
static void main(String[] args) {
LinkedList
lList = new LinkedList();
lList.add("100");
lList.add("200");
lList.add("300");
lList.add("400");
lList.add("500");
System.out.println("First element of LinkedList is :
" + lList.getFirst());
System.out.println("Last element of
LinkedList is :
" + lList.getLast());
}
}
Output : First
element of LinkedList is :100
Last element of LinkedList is :500
3.
Write a Java
Program to add an element at first and
last position of a linked list.
Code : Import java.util.LinkedList;
public class Main
{
public
static void main(String[] args) {
LinkedList lList = new LinkedList();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
System.out.println(lList);
lList.addFirst("0");
System.out.println(lList);
lList.addLast("6");
System.out.println(lList);
}
}
Output : 1,
2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6
4.
Write a Java
Program to convert an infix expression
to postfix expression.
Code
: import
java.io.IOException;
public class InToPost {
private Stack theStack;
private String input;
private String output = "";
public InToPost(String in) {
input = in;
int stackSize = input.length();
theStack = new Stack(stackSize);
}
public String doTrans() {
for (int j = 0; j < input.length();
j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
gotOper(ch, 1);
break;
case '*':
case 'Code : ':
gotOper(ch, 2);
break;
case '(':
theStack.push(ch);
break;
case ')':
gotParen(ch);
break;
default:
output = output + ch;
break;
}
}
while (!theStack.isEmpty()) {
output = output + theStack.pop();
}
System.out.println(output);
return output;
}
public void gotOper(char opThis, int prec1) {
while (!theStack.isEmpty()) {
char opTop = theStack.pop();
if (opTop == '(') {
theStack.push(opTop);
break;
}
else {
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1) {
theStack.push(opTop);
break;
}
else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch){
while (!theStack.isEmpty()) {
char chx = theStack.pop();
if (chx == '(')
break;
else
output = output + chx;
}
}
public static void main(String[] args)
throws IOException {
String input = "1+2*4Code : 5-7+3Code :
6";
String output;
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans();
System.out.println("Postfix is
" + output + 'Output : n');
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
Output : 124*5Code
: +7-36Code
: +
Postfix is 124*5Code : +7-36Code
: +
5.
Write a Java
Program to implement Queue.
Code : import java.util.LinkedList;
class
GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems())
list.addLast(q.dequeue());
}
}
public class GenQueueTest {
public static void main(String[] args) {
GenQueue<Employee> empList;
empList = new GenQueue<Employee>();
GenQueue<HourlyEmployee> hList;
hList = new
GenQueue<HourlyEmployee>();
hList.enqueue(new HourlyEmployee("T",
"D"));
hList.enqueue(new
HourlyEmployee("G", "B"));
hList.enqueue(new
HourlyEmployee("F", "S"));
empList.addItems(hList);
System.out.println("The employees'
names are:");
while (empList.hasItems()) {
Employee emp = empList.dequeue();
System.out.println(emp.firstName +
" "
+ emp.lastName);
}
}
}
class Employee {
public String lastName;
public String firstName;
public Employee() {
}
public Employee(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " +
lastName;
}
}
class HourlyEmployee extends
Employee {
public double hourlyRate;
public HourlyEmployee(String last, String first) {
super(last, first);
}
}
Output : The
employees' name are:
T D
G B
F S
6.
Write a Java
Program to reverse a string using stack.
Code
: import
java.io.IOException;
public class StringReverserThroughStack {
private String input;
private
String output;
public
StringReverserThroughStack(String in) {
input =
in;
}
public
String doRev() {
int
stackSize = input.length();
Stack
theStack = new Stack(stackSize);
for (int
i = 0; i < input.length(); i++) {
char
ch = input.charAt(i);
theStack.push(ch);
}
output =
"";
while
(!theStack.isEmpty()) {
char
ch = theStack.pop();
output = output + ch;
}
return
output;
}
public
static void main(String[] args)
throws
IOException {
String
input = "Java Source and Support";
String
output;
StringReverserThroughStack theReverser =
new
StringReverserThroughStack(input);
output =
theReverser.doRev();
System.out.println("Reversed: " + output);
}
class Stack
{
private
int maxSize;
private
char[] stackArray;
private
int top;
public
Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top =
-1;
}
public
void push(char j) {
stackArray[++top] = j;
}
public
char pop() {
return stackArray[top--];
}
public
char peek() {
return stackArray[top];
}
public
boolean isEmpty() {
return (top == -1);
}
}
}
Output : JavaStringReversal
Reversed:lasreveRgnirtSavaJ
7.
Write a Java
Program to search an element inside a
linked list.
Code
: import
java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList lList = new LinkedList();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
lList.add("2");
System.out.println("First index of 2
is:"+
lList.indexOf("2"));
System.out.println("Last index of 2
is:"+
lList.lastIndexOf("2"));
}
}
Output : First
index of 2 is: 1
Last index of 2 is: 5
8.
Write a Java
Program to implement stack.
Code : public class MyStack {
private int maxSize;
private long[] stackArray;
private int top;
public MyStack(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;
}
public long pop() {
return stackArray[top--];
}
public long peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
MyStack theStack = new MyStack(10);
theStack.push(10);
theStack.push(20);
theStack.push(30);
theStack.push(40);
theStack.push(50);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
Output : 50
40 30 20 10
9.
Write a Java
Program to swap two elements in a
vector.
Code : import
java.util.Collections;
import
java.util.Vector;
public class Main {
public static void main(String[]
args) {
Vector<String> v = new Vector();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
System.out.println(v);
Collections.swap(v, 0, 4);
System.out.println("After swapping");
System.out.println(v);
}
}
Output : 1 2
3 4 5
After swapping
5 2 3 4 1
10.
Write a Java
Program to update a linked list.
Code : import
java.util.LinkedList;
public class MainClass {
public static void main(String[] a) {
LinkedList officers = new LinkedList();
officers.add("B");
officers.add("B");
officers.add("T");
officers.add("H");
officers.add("P");
System.out.println(officers);
officers.set(2, "M");
System.out.println(officers);
}
}
Output : BBTHP
BBMHP
11.
Write a Java
Program to get the maximum element from
a vector.
Code : import
java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[]
args) {
Vector v = new Vector();
v.add(new Double("3.4324"));
v.add(new Double("3.3532"));
v.add(new Double("3.342"));
v.add(new Double("3.349"));
v.add(new Double("2.3"));
Object obj = Collections.max(v);
System.out.println("The max element
is:"+obj);
}
}
Output : The
max element is: 3.4324
12.
Write a Java
Program to execute binary search on a
vector.
Code
: import
java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector v = new Vector();
v.add("X");
v.add("M");
v.add("D");
v.add("A");
v.add("O");
Collections.sort(v);
System.out.println(v);
int index = Collections.binarySearch(v,
"D");
System.out.println("Element found at
: " + index);
}
}
Output : [A,
D, M, O, X]
Element found at : 1
13.
Write a Java
Program to get elements of a LinkedList.
Code : import java.util.*;
public class
Main {
private LinkedList list = new LinkedList();
public void
push(Object v) {
list.addFirst(v);
}
public Object top() {
return list.getFirst();
}
public Object pop() {
return list.removeFirst();
}
public static void main(String[] args) {
Main stack = new Main();
for (int i = 30; i < 40; i++)
stack.push(new Integer(i));
System.out.println(stack.top());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
Output : 39
39
38
37
14.
Write a Java
Program to delete many elements from a
linkedList.
Code : import java.util.*;
public class Main {
public static void main(String[] args) {
LinkedList<String> lList = new
LinkedList<String>();
lList.add("1");
lList.add("8");
lList.add("6");
lList.add("4");
lList.add("5");
System.out.println(lList);
lList.subList(2, 4).clear();
System.out.println(lList);
}
}
Output : [one,
two, three, four, five]
[one, two, three, Replaced,
five]
Collections
1.
Write a Java
Program to convert an array into a
collection.
Code : import
java.util.*;
import java.io.*;
public class
ArrayToCollection{
public static void main(String args[])
throws IOException{
BufferedReader in = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("How many
elements
you want to add to the array: ");
int n = Integer.parseInt(in.readLine());
String[] name = new String[n];
for(int i = 0; i < n; i++){
name[i] = in.readLine();
}
List list = Arrays.asList(name);
System.out.println();
for(String li: list){
String str = li;
System.out.print(str + " ");
}
}
}
Output : How
many elements you want to add to the array:
red white green
red white green
2.
Write a Java
Program to compare elements in a
collection.
Code : import
java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
class MainClass {
public static void main(String[] args) {
String[] coins = { "Penny",
"nickel", "dime",
"Quarter", "dollar"
};
Set set = new TreeSet();
for (int i = 0; i < coins.length; i++)
set.add(coins[i]);
System.out.println(Collections.min(set));
System.out.println(Collections.min(set,
String.CASE_INSENSITIVE_ORDER));
for(int i=0;i< =10;i++)
System.out.print(-);
System.out.println(Collections.max(set));
System.out.println(Collections.max(set,
String.CASE_INSENSITIVE_ORDER));
}
}
Output : Penny
dime
----------
nickle
Quarter
3.
Write a Java
Program to convert a collection into an
array.
Code : import
java.util.*;
public class CollectionToArray{
public static void main(String[] args){
List<String> list = new
ArrayList<String>();
list.add("This ");
list.add("is ");
list.add("a ");
list.add("good ");
list.add("program.");
String[] s1 = list.toArray(new
String[0]);
for(int i = 0; i < s1.length; ++i){
String contents = s1[i];
System.out.print(contents);
}
}
}
Output : This
is a good program.
4.
Write a Java
Program to print a collection.
Code : import
java.util.*;
public class TreeExample{
public static void main(String[] args) {
System.out.println("Tree Map
Example!Output : n");
TreeMap tMap = new TreeMap();
tMap.put(1, "Sunday");
tMap.put(2, "Monday");
tMap.put(3, "Tuesday");
tMap.put(4, "Wednesday");
tMap.put(5, "Thursday");
tMap.put(6, "Friday");
tMap.put(7, "Saturday");
System.out.println("Keys of tree
map: "
+ tMap.keySet());
System.out.println("Values of tree
map: "
+ tMap.values());
System.out.println("Key: 5 value:
" + tMap.get(5)+ "Output : n");
System.out.println("First key:
" + tMap.firstKey()
+ " Value: "
+ tMap.get(tMap.firstKey()) + "Output
: n");
System.out.println("Last key: "
+ tMap.lastKey()
+ " Value: "+
tMap.get(tMap.lastKey()) + "Output :
n");
System.out.println("Removing first
data: "
+ tMap.remove(tMap.firstKey()));
System.out.println("Now the tree map
Keys: "
+ tMap.keySet());
System.out.println("Now the
tree map contain: "
+ tMap.values() + "Output : n");
System.out.println("Removing last
data: "
+ tMap.remove(tMap.lastKey()));
System.out.println("Now the tree map
Keys: "
+ tMap.keySet());
System.out.println("Now
the tree map contain: "
+ tMap.values());
}
}
Output : C:Output : collection>javac TreeExample.java
C:Output : collection>java TreeExample
Tree Map Example!
Keys of tree map: [1, 2, 3, 4, 5, 6, 7]
Values of tree map: [Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]
Key: 5 value: Thursday
First key: 1 Value: Sunday
Last key: 7 Value: Saturday
Removing first data: Sunday
Now the tree map Keys: [2, 3, 4, 5, 6, 7]
Now the tree map contain: [Monday, Tuesday,
Wednesday,
Thursday, Friday, Saturday]
Removing last data: Saturday
Now the tree map Keys: [2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday,
Wednesday,
Thursday, Friday]
C:Output : collection>
5.
Write a Java
Program to make a collection read-only.
Code : import
java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] argv)
throws Exception {
List stuff = Arrays.asList(new String[] {
"a", "b" });
List list = new ArrayList(stuff);
list =
Collections.unmodifiableList(list);
try {
list.set(0, "new value");
}
catch (UnsupportedOperationException e) {
}
Set set = new HashSet(stuff);
set = Collections.unmodifiableSet(set);
Map map = new HashMap();
map = Collections.unmodifiableMap(map);
System.out.println("Collection is
read-only now.");
}
}
Output : Collection
is read-only now.
6. Write
a Java Program to remove a specific
element from a collection.
Code :
import
java.util.*;
public
class CollectionTest {
public static void main(String [] args)
{
System.out.println( "Collection
Example!Output : n" );
int size;
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 =
"White", str3 =
"Green", str4 =
"Blue";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Collection data:
");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() +
" ");
}
System.out.println();
collection.remove(str2);
System.out.println("After removing
[" + str2 + "]Output : n");
System.out.print("Now collection
data: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() +
" ");
}
System.out.println();
size = collection.size();
System.out.println("Collection size:
" + size + "Output : n");
}
}
Output :
Collection Example!
Collection
data: Blue White Green Yellow
After
removing [White]
Now
collection data: Blue Green Yellow
Collection
size: 3
6.
Write a Java
Program to reverse a collection.
Code : import
java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
class UtilDemo3 {
public static void main(String[] args) {
String[] coins = { "A",
"B", "C", "D", "E" };
List l = new ArrayList();
for (int i = 0; i < coins.length; i++)
l.add(coins[i]);
ListIterator liter = l.listIterator();
System.out.println("Before
reversal");
while (liter.hasNext())
System.out.println(liter.next());
Collections.reverse(l);
liter = l.listIterator();
System.out.println("After
reversal");
while (liter.hasNext())
System.out.println(liter.next());
}
}
Output :
Before reversal
A
B
C
D
E
After
reversal
E
D
C
B
A
8. Write
a Java Program to shuffle the elements
of a collection.
Code :
import java.util.ArrayList;
import
java.util.Collections;
import
java.util.List;
public
class Main {
public static void main(String[] argv)
throws Exception {
String[] alpha = { "A",
"E", "I", "O", "U" };
List list = new ArrayList(alpha);
Collections.shuffle(list);
System.out.println("list");
}
}
Output
: I
O
A
U
E
9. Write
a Java Program to get the size of a
collection.
Code :
import java.util.*;
public
class CollectionTest {
public static void main(String [] args)
{
System.out.println( "Collection
Example!Output : n" );
int size;
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 =
"White", str3 =
"Green", str4 =
"Blue";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Collection data:
");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() +
" ");
}
System.out.println();
size = collection.size();
if (collection.isEmpty()){
System.out.println("Collection is
empty");
}
else{
System.out.println( "Collection
size: " + size);
}
System.out.println();
}
}
Output :
Collection Example!
Collection data: Blue White
Green Yellow
Collection size: 4
10.
Write a Java Program to iterate through
elements of HashMap.
Code :
import java.util.*;
public
class Main {
public static void main(String[] args) {
HashMap< String, String> hMap =
new HashMap< String, String>();
hMap.put("1", "1st");
hMap.put("2", "2nd");
hMap.put("3", "3rd");
Collection cl = hMap.values();
Iterator itr = cl.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Output :
3rd
2nd
1st
11.
Write a Java Program to use different
types of Collections.
Code :
import java.util.Map;
import
java.util.Set;
import
java.util.SortedMap;
import
java.util.SortedSet;
import
java.util.TreeMap;
import
java.util.TreeSet;
import
java.util.ArrayList;
import
java.util.Collection;
import
java.util.HashMap;
import
java.util.HashSet;
import
java.util.Iterator;
import
java.util.LinkedHashMap;
import
java.util.LinkedHashSet;
import
java.util.LinkedList;
import
java.util.List;
public
class Main {
public static void main(String[] args) {
List lnkLst = new LinkedList();
lnkLst.add("element1");
lnkLst.add("element2");
lnkLst.add("element3");
lnkLst.add("element4");
displayAll(lnkLst);
List aryLst = new ArrayList();
aryLst.add("x");
aryLst.add("y");
aryLst.add("z");
aryLst.add("w");
displayAll(aryLst);
Set hashSet = new HashSet();
hashSet.add("set1");
hashSet.add("set2");
hashSet.add("set3");
hashSet.add("set4");
displayAll(hashSet);
SortedSet treeSet = new TreeSet();
treeSet.add("1");
treeSet.add("2");
treeSet.add("3");
treeSet.add("4");
displayAll(treeSet);
LinkedHashSet lnkHashset = new
LinkedHashSet();
lnkHashset.add("one");
lnkHashset.add("two");
lnkHashset.add("three");
lnkHashset.add("four");
displayAll(lnkHashset);
Map ma p1 = new HashMap();
map1.put("key1",
"J");
map1.put("key2",
"K");
map1.put("key3",
"L");
map1.put("key4",
"M");
displayAll(map1.keySet());
displayAll(map1.values());
SortedMap map2 = new TreeMap();
map2.put("key1",
"JJ");
map2.put("key2",
"KK");
map2.put("key3",
"LL");
map2.put("key4",
"MM");
displayAll(map2.keySet());
displayAll(map2.values());
LinkedHashMap map3 = new LinkedHashMap();
map3.put("key1",
"JJJ");
map3.put("key2",
"KKK");
map3.put("key3",
"LLL");
map3.put("key4",
"MMM");
displayAll(map3.keySet());
displayAll(map3.values());
}
static void displayAll(Collection col) {
Iterator itr = col.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.print(str + " ");
}
System.out.println();
}
}
Output :
element1 element2 element3 element4
x
y z w
set1
set2 set3 set4
1
2 3 4
one
two three four
key4
key3 key2 key1
M
L K J
key1
key2 key3 key4
JJ
KK LL MM
key1
key2 key3 key4
JJJ
KKK LLL MMM
12. Write
a Java Program to use enumeration to
display contents of HashTable.
Code :
import java.util.Enumeration;
import java.util.Hashtable;
public
class Main {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Output :
Three
Two
One
13. Write
a Java Program to get Set view of Keys
from Java Hashtable.
Code :
import java.util.Enumeration;
import
java.util.Hashtable;
public
class Main {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.keys();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Output :
3
2
1
15.
Write a Java
Program to find min & max of a List.
Code : import
java.util.*;
public
class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two
three Four five six
one three Four".split("
"));
System.out.println(list);
System.out.println("max: " +
Collections.max(list));
System.out.println("min: " +
Collections.min(list));
}
}
Output :
[one, Two, three, Four, five, six, one, three, Four]
max: three
min: Four
15. Write
a Java Program to find a sublist in a
List.
Code :
import java.util.*;
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two
three Four five
six one three Four".split("
"));
System.out.println("List
:"+list);
List sublist = Arrays.asList("three
Four".split(" "));
System.out.println("SubList
:"+sublist);
System.out.println("indexOfSubList:
"
+ Collections.indexOfSubList(list,
sublist));
System.out.println("lastIndexOfSubList: "
+ Collections.lastIndexOfSubList(list,
sublist));
}
}
Output :
List :[one, Two, three, Four, five, six, one, three, Four]
SubList
:[three, Four]
indexOfSubList:
2
lastIndexOfSubList:
7
16. Write
a Java Program to replace an element in
a list.
Code :
import java.util.*;
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two
three Four five six
one three Four".split("
"));
System.out.println("List
:"+list);
Collections.replaceAll(list,
"one", "hundread");
System.out.println("replaceAll:
" + list);
}
}
Output :
List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll:
[hundread, Two, three, Four, five, six,
hundread,
three, Four]
17. Write
a Java Program to rotate elements of the
List.
Code :
import java.util.*;
public
class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two
three Four five
six".split(" "));
System.out.println("List
:"+list);
Collections.rotate(list, 3);
System.out.println("rotate: " +
list);
}
}
Output :
List :[one, Two, three, Four, five, six]
rotate: [Four, five, six, one,
Two, three]
Networking
1.
Write a Java
Program to change the host name to its
specific IP address.
Code : import
java.net.InetAddress;
import
java.net.UnknownHostException;
public class GetIP {
public static void main(String[] args) {
InetAddress address = null;
try {
address = InetAddress.getByName
("www.javatutorial.com");
}
catch (UnknownHostException e) {
System.exit(2);
}
System.out.println(address.getHostName()
+ "="
+ address.getHostAddress());
System.exit(0);
}
}
Output : http:Code
: Code
: www.javatutorial.com
= 123.14.2.35
2. Write
a Java Program to get connected with web
server.
Code :
Output :
3. Write
a Java Program to check a file is
modified at a server or not.
4. Write
a Java Program to create a multithreaded
server.
5. Write
a Java Program to get the file size from
the server.
6. Write
a Java Program to make a socket
displaying message to a single client.
7. Write
a Java Program to make a srever to allow
the connection to the socket 6123.
8. Write
a Java Program to get the parts of an
URL.
9. Write
a Java Program to get the date of URL
connection.
10. Write
a Java Program to read and download a
webpage.
11. Write
a Java Program to find hostname from IP
Address.
12. Write
a Java Program to determine IP Address
& hostname of Local Computer.
13. Write
a Java Program to check whether a port
is being used or not.
14. Write
a Java Program to find proxy settings of
a System.
15. Write
a Java Program to create a socket at a
specific port.
Threading
1.
Write a Java
Program to check a thread is alive or
not.
Code : public
class TwoThreadAlive extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}
public
void printMsg() {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" +
name);
}
public
static void main(String[] args) {
TwoThreadAlive tt = new TwoThreadAlive();
tt.setName("Thread");
System.out.println("before start(),
tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(),
tt.isAlive()=" + tt.isAlive());
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
System.out.println("The end of main(),
tt.isAlive()=" + tt.isAlive());
}
}
Output :
before start(),tt.isAlive()=false
just
after start(), tt.isAlive()=true
name=main
name=main
name=main
name=main
name=main
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=main
name=main
The
end of main().tt.isAlive()=false
2. Write
a Java Program to check a thread has
stop or not.
Code :
public
class Main {
public static void main(String[] argv)
throws Exception {
Thread thread = new MyThread();
thread.start();
if (thread.isAlive()) {
System.out.println("Thread has
not finished");
}
else {
System.out.println("Finished");
}
long delayMillis = 5000;
thread.join(delayMillis);
if (thread.isAlive()) {
System.out.println("thread has
not finished");
}
else {
System.out.println("Finished");
}
thread.join();
}
}
class
MyThread extends Thread {
boolean stop = false;
public void run() {
while (true) {
if (stop) {
return;
}
}
}
}
Output :
Thread has not finished
Finished
3. Write
a Java Program to solve deadlock using
thread.
Code :
import java.util.*;
import
java.util.concurrent.*;
import
java.util.concurrent.locks.*;
public
class DeadlockDetectingLock extends ReentrantLock {
private static List deadlockLocksRegistry
= new ArrayList();
private static synchronized void
registerLock(DeadlockDetectingLock ddl) {
if (!deadlockLocksRegistry.contains(ddl))
deadlockLocksRegistry.add(ddl);
}
private static synchronized void
unregisterLock(DeadlockDetectingLock ddl) {
if (deadlockLocksRegistry.contains(ddl))
deadlockLocksRegistry.remove(ddl);
}
private List hardwaitingThreads = new
ArrayList();
private static synchronized void
markAsHardwait(List l, Thread t) {
if (!l.contains(t))
l.add(t);
}
private
static synchronized void
freeIfHardwait(List
l, Thread t) {
if (l.contains(t))
l.remove(t);
}
private
static Iterator getAllLocksOwned(Thread t) {
DeadlockDetectingLock current;
ArrayList results = new ArrayList();
Iterator itr =
deadlockLocksRegistry.iterator();
while (itr.hasNext()) {
current = (DeadlockDetectingLock)
itr.next();
if
(current.getOwner() == t)
results.add(current);
}
return results.iterator();
}
private
static Iterator
getAllThreadsHardwaiting(DeadlockDetectingLock
l) {
return l.hardwaitingThreads.iterator();
}
private
static synchronized boolean canThreadWaitOnLock
(Thread
t,DeadlockDetectingLock l) {
Iterator locksOwned = getAllLocksOwned(t);
while (locksOwned.hasNext()) {
DeadlockDetectingLock current
= (DeadlockDetectingLock)
locksOwned.next();
if (current == l)
return false;
Iterator waitingThreads
= getAllThreadsHardwaiting(current);
while (waitingThreads.hasNext()) {
Thread otherthread = (Thread)
waitingThreads.next();
if (!canThreadWaitOnLock(otherthread,
l)) {
return false;
}
}
}
return true;
}
public
DeadlockDetectingLock() {
this(false, false);
}
public
DeadlockDetectingLock(boolean fair) {
this(fair, false);
}
private
boolean debugging;
public
DeadlockDetectingLock(boolean fair, boolean debug) {
super(fair);
debugging = debug;
registerLock(this);
}
public
void lock() {
if (isHeldByCurrentThread()) {
if (debugging)
System.out.println("Already Own
Lock");
super.lock();
freeIfHardwait(hardwaitingThreads,
Thread.currentThread());
return;
}
markAsHardwait(hardwaitingThreads,
Thread.currentThread());
if (canThreadWaitOnLock(Thread.currentThread(),
this)) {
if (debugging)
System.out.println("Waiting For
Lock");
super.lock();
freeIfHardwait(hardwaitingThreads,
Thread.currentThread());
if (debugging)
System.out.println("Got New
Lock");
}
else {
throw new
DeadlockDetectedException("DEADLOCK");
}
}
public
void lockInterruptibly() throws InterruptedException {
lock();
}
locks.
public
class DeadlockDetectingCondition implements Condition {
Condition embedded;
protected
DeadlockDetectingCondition(ReentrantLock lock,
Condition embedded) {
this.embedded = embedded;
}
Public void await() throws
InterruptedException {
try {
markAsHardwait(hardwaitingThreads,
Thread.currentThread());
embedded.await();
}
finally {
freeIfHardwait(hardwaitingThreads,
Thread.currentThread());
}
}
public void awaitUninterruptibly() {
markAsHardwait(hardwaitingThreads,
Thread.currentThread());
embedded.awaitUninterruptibly();
freeIfHardwait(hardwaitingThreads,
Thread.currentThread());
}
public long awaitNanos(long nanosTimeout)
throws InterruptedException {
try {
markAsHardwait(hardwaitingThreads,
Thread.currentThread());
return
embedded.awaitNanos(nanosTimeout);
}
finally {
freeIfHardwait(hardwaitingThreads,
Thread.currentThread());
}
}
public boolean await(long time, TimeUnit
unit)
throws InterruptedException {
try {
markAsHardwait(hardwaitingThreads,
Thread.currentThread());
return embedded.await(time, unit);
}
finally {
freeIfHardwait(hardwaitingThreads,
Thread.currentThread());
}
}
public boolean awaitUntil(Date deadline)
throws InterruptedException {
try {
markAsHardwait(hardwaitingThreads,
Thread.currentThread());
return embedded.awaitUntil(deadline);
}
finally {
freeIfHardwait(hardwaitingThreads,
Thread.currentThread());
}
}
public void signal() {
embedded.signal();
}
public void signalAll() {
embedded.signalAll();
}
}
public
Condition newCondition() {
return new DeadlockDetectingCondition(this,
super.newCondition());
}
private
static Lock a = new DeadlockDetectingLock(false, true);
private
static Lock b = new DeadlockDetectingLock(false, true);
private
static Lock c = new DeadlockDetectingLock(false, true);
private
static Condition wa = a.newCondition();
private
static Condition wb = b.newCondition();
private
static Condition wc = c.newCondition();
private
static void delaySeconds(int seconds) {
try {
Thread.sleep(seconds * 1000);
}
catch (InterruptedException ex) {
}
}
private
static void awaitSeconds(Condition c, int seconds) {
try {
c.await(seconds, TimeUnit.SECONDS);
}
catch (InterruptedException ex) {
}
}
private
static void testOne() {
new Thread(new Runnable() {
public void run() {
System.out.println("thread one
grab a");
a.lock();
delaySeconds(2);
System.out.println("thread one
grab b");
b.lock();
delaySeconds(2);
a.unlock();
b.unlock();
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("thread two
grab b");
b.lock();
delaySeconds(2);
System.out.println("thread two
grab a");
a.lock();
delaySeconds(2);
a.unlock();
b.unlock();
}
}).start();
}
private
static void testTwo() {
new Thread(new Runnable() {
public void run() {
System.out.println("thread one
grab a");
a.lock();
delaySeconds(2) ;
System.out.println("thread one
grab b");
b.lock();
delaySeconds(10);
a.unlock();
b.unlock();
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("thread two
grab b");
b.lock();
delaySeconds(2);
System.out.println("thread two
grab c");
c.lock();
delaySeconds(10);
b.unlock();
c.unlock();
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("thread three
grab c");
c.lock();
delaySeconds(4);
System.out.println("thread three
grab a");
a.lock();
delaySeconds(10);
c.unlock();
a.unlock();
}
}).start();
}
private
static void testThree() {
new Thread(new Runnable() {
public void run() {
System.out.println("thread one
grab b");
b.lock();
System.out.println("thread one
grab a");
a.lock();
delaySeconds(2);
System.out.println("thread one
waits on b");
awaitSeconds(wb, 10);
a.unlock();
b.unlock();
}
}).start();
new Thread(new Runnable() {
public void run() {
delaySeconds(1);
System.out.println("thread two
grab b");
b.lock();
System.out.println("thread two
grab a");
a.lock();
delaySeconds(10);
b.unlock();
c.unlock();
}
}).start();
}
public
static void main(String args[]) {
int test = 1;
if (args.length > 0)
test = Integer.parseInt(args[0]);
switch (test) {
case 1:
testOne();
break;
case 2:
testTwo();
break;
case 3:
testThree();
break;
default:
System.err.println("usage: java
DeadlockDetectingLock [ test# ]");
}
delaySeconds(60);
System.out.println("--- End Program
---");
System.exit(0);
}
}
class
DeadlockDetectedException extends RuntimeException {
public DeadlockDetectedException(String s) {
super(s);
}
}
Output :
thread one grab a
Waiting
For Lock
Got
New Lock
thread
two grab b
Waiting
For Lock
Got
New Lock
thread
one grab b
Waiting
For Lock
thread
two grab a
Exception
in thread "Thread-1"
DeadlockDetectedException:DEADLOCK
at DeadlockDetectingLock.
lock(DealockDetectingLock.java:152)
at
java.lang.Thread.run(Thread.java:595)
4. Write
a Java Program to get the priorities of
running threads.
Code :
public
class SimplePriorities extends Thread {
private int countDown = 5;
private volatile double d = 0;
public SimplePriorities(int priority) {
setPriority(priority);
start();
}
public String toString() {
return super.toString() + ": "
+ countDown;
}
public void run() {
while(true) {
for(int i = 1; i < 100000; i++)
d = d + (Math.PI + Math.E) Code : (double)i;
System.out.println(this);
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
new
SimplePriorities(Thread.MAX_PRIORITY);
for(int i = 0; i < 5; i++)
new
SimplePriorities(Thread.MIN_PRIORITY);
}
}
Output :
Thread[Thread-0,10,main]: 5
Thread[Thread-0,10,main]:
4
Thread[Thread-0,10,main]:
3
Thread[Thread-0,10,main]:
2
Thread[Thread-0,10,main]:
1
Thread[Thread-1,1,main]:
5
Thread[Thread-1,1,main]:
4
Thread[Thread-1,1,main]:
3
Thread[Thread-1,1,main]:
2
Thread[Thread-1,1,main]:
1
Thread[Thread-2,1,main]:
5
Thread[Thread-2,1,main]:
4
Thread[Thread-2,1,main]:
3
Thread[Thread-2,1,main]:
2
Thread[Thread-2,1,main]:
1
.
.
.
5. Write
a Java Program to monitor a thread's
status.
Code :
class MyThread extends Thread{
boolean waiting= true;
boolean ready= false;
MyThread() {
}
public void run() {
String thrdName =
Thread.currentThread().getName();
System.out.println(thrdName + "
starting.");
while(waiting)
System.out.println("waiting:"+waiting);
System.out.println("waiting...");
startWait();
try {
Thread.sleep(1000);
}
catch(Exception exc) {
System.out.println(thrdName + "
interrupted.");
}
System.out.println(thrdName + "
terminating.");
}
synchronized void startWait() {
try {
while(!ready) wait();
}
catch(InterruptedException exc) {
System.out.println("wait()
interrupted");
}
}
synchronized void notice() {
ready = true;
notify();
}
}
public
class Main {
public static void main(String args[])
throws Exception{
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+"
Alive:="+thrd.isAlive()+"
State:=" + thrd.getState() );
}
}
Output :
main Alive=true State:=running
6. Write a Java Program to get the name of a running thread.
Code : public class TwoThreadGetName extends Thread
{
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}
public void printMsg() {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" +
name);
}
public static void main(String[] args) {
TwoThreadGetName tt = new
TwoThreadGetName();
tt.start();
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
}
Output :
name=main
name=main
name=main
name=main
name=main
name=thread
name=thread
name=thread
name=thread
7. Write
a Java Program to solve the producer
consumer problem using thread.
Code :
public class ProducerConsumerTest {
public
static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class
CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
}
catch (InterruptedException e) {
}
}
contents = value;
available = true;
notifyAll();
}
}
class
Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer
#"
+ this.number
+
" got: " + value);
}
}
}
class
Producer extends Thread {
private
CubbyHole cubbyhole;
private
int number;
public
Producer(CubbyHole c, int number) {
cubbyhole
= c;
this.number
= number;
}
public
void run() {
for
(int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer
#" + this.number
+
" put: " + i);
try
{
sleep((int)(Math.random()
* 100));
}
catch (InterruptedException e) { }
}
}
}
Output :
Producer #1 put: 0
Consumer
#1 got: 0
Producer
#1 put: 1
Consumer
#1 got: 1
Producer
#1 put: 2
Consumer
#1 got: 2
Producer
#1 put: 3
Consumer
#1 got: 3
Producer
#1 put: 4
Consumer
#1 got: 4
Producer
#1 put: 5
Consumer
#1 got: 5
Producer
#1 put: 6
Consumer
#1 got: 6
Producer
#1 put: 7
Consumer #1 got: 7
Producer
#1 put: 8
Consumer
#1 got: 8
Producer
#1 put: 9
Consumer
#1 got: 9
8. Write
a Java Program to set the priority of a
thread.
Code :
public class Main {
public static void main(String[] args)
throws
Exception {
Thread thread1 = new Thread(new
TestThread(1));
Thread thread2 = new Thread(new
TestThread(2));
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("The priority has
been set.");
}
}
Output :
The priority has been set.
9. Write
a Java Program to stop a thread.
Code :
import java.util.Timer;
import
java.util.TimerTask;
class
CanStop extends Thread {
private volatile boolean stop = false;
private int counter = 0;
public void run() {
while (!stop && counter <
10000) {
System.out.println(counter++);
}
if (stop)
System.out.println("Detected
stop");
}
public void requestStop() {
stop = true;
}
}
public
class Stopping {
public static void main(String[] args) {
final CanStop stoppable = new CanStop();
stoppable.start();
new Timer(true).schedule(new TimerTask()
{
public void run() {
System.out.println("Requesting
stop");
stoppable.requestStop();
}
}, 350);
}
}
Output :
Detected stop
10. Write
a Java Program to suspend a thread for a
while.
Code :
public class SleepingThread extends Thread {
private int countDown = 5;
private static int threadCount = 0;
public SleepingThread() {
super("" + ++threadCount);
start();
}
public String toString() {
return "#" + getName() +
": " + countDown;
}
public void run() {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
try {
sleep(100);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args)
throws InterruptedException {
for (int i = 0; i < 5; i++)
new SleepingThread().join();
System.out.println("The thread has
been suspened.");
}
}
Output :
The thread has been suspened.
11. Write
a Java Program to get the Id of the
running thread.
Code :
public class Main extends Object
implements Runnable {
private ThreadID var;
public
Main(ThreadID v) {
this.var = v;
}
public void run() {
try {
print("var getThreadID =" +
var.getThreadID());
Thread.sleep(2000);
print("var getThreadID =" +
var.getThreadID());
} catch (InterruptedException x) {
}
}
private static void print(String msg) {
String name =
Thread.currentThread().getName();
System.out.println(name + ": " +
msg);
}
public static void main(String[] args) {
ThreadID tid = new ThreadID();
Main shared = new Main(tid);
try {
Thread threadA = new Thread(shared,
"threadA");
threadA.start();
Thread.sleep(500);
Thread threadB = new Thread(shared,
"threadB");
threadB.start();
Thread.sleep(500);
Thread threadC = new Thread(shared,
"threadC");
threadC.start();
} catch (InterruptedException x) {
}
}
}
class
ThreadID extends ThreadLocal {
private int nextID;
public ThreadID() {
nextID = 10001;
}
private synchronized Integer getNewID() {
Integer id = new Integer(nextID);
nextID++;
return id;
}
protected Object initialValue() {
print("in initialValue()");
return getNewID();
}
public int getThreadID() {
Integer id = (Integer) get();
return id.intValue();
}
private static void print(String msg) {
String name =
Thread.currentThread().getName();
System.out.println(name + ": " +
msg);
}
}
Output :
threadA: in initialValue()
threadA:
var getThreadID =10001
threadB:
in initialValue()
threadB:
var getThreadID =10002
threadC:
in initialValue()
threadC:
var getThreadID =10003
threadA:
var getThreadID =10001
threadB:
var getThreadID =10002
threadC:
var getThreadID =10003
12. Write
a Java Program to check priority level
of a thread.
Code : public
class Main extends Object {
private
static Runnable makeRunnable() {
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
Thread t =
Thread.currentThread();
System.out.println("in
run() - priority="
+ t.getPriority()+ ",
name=" + t.getName());
try {
Thread.sleep(2000);
}
catch (InterruptedException x) {
}
}
}
};
return r;
}
public static void main(String[] args) {
System.out.println("in main() -
Thread.currentThread().
getPriority()=" +
Thread.currentThread().getPriority());
System.out.println("in main() -
Thread.currentThread()
.getName()="+
Thread.currentThread().getName());
Thread threadA = new
Thread(makeRunnable(), "threadA");
threadA.start();
try {
Thread.sleep(3000);
}
catch (InterruptedException x) {
}
System.out.println("in main() -
threadA.getPriority()="
+ threadA.getPriority());
}
}
Output :
in main() - Thread.currentThread().getPriority()=5
in
main() - Thread.currentThread().getName()=main
in
run() - priority=5, name=threadA
in
run() - priority=5, name=threadA
in
main() - threadA.getPriority()=5
in
run() - priority=5, name=threadA
in
run() - priority=5, name=threadA
in
run() - priority=5, name=threadA
13. Write
a Java Program to display all running
Thread.
Code :
public class Main extends Thread {
public static void main(String[] args) {
Main t1 = new Main();
t1.setName("thread1");
t1.start();
ThreadGroup currentGroup =
Thread.currentThread().getThreadGroup();
int noThreads =
currentGroup.activeCount();
Thread[] lstThreads = new
Thread[noThreads];
currentGroup.enumerate(lstThreads);
for (int i = 0; i < noThreads; i++)
System.out.println("Thread No:"
+ i + " = "
+ lstThreads[i].getName());
}
}
Output :
Thread No:0 = main
Thread
No:1 = thread1
14. Write
a Java Program to display thread status.
Code :
class MyThread extends Thread{
boolean waiting= true;
boolean ready= false;
MyThread() {
}
public void run() {
String thrdName =
Thread.currentThread().getName();
System.out.println(thrdName + "
starting.");
while(waiting)
System.out.println("waiting:"+waiting);
System.out.println("waiting...");
startWait();
try {
Thread.sleep(1000);
}
catch(Exception exc) {
System.out.println(thrdName + "
interrupted.");
}
System.out.println(thrdName + "
terminating.");
}
synchronized void startWait() {
try {
while(!ready) wait();
}
catch(InterruptedException exc) {
System.out.println("wait()
interrupted");
}
}
synchronized void notice() {
ready = true;
notify();
}
}
public
class Main {
public static void main(String args[])
throws Exception{
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+"
Alive:"
+thrd.isAlive()+" State:" +
thrd.getState() );
}
}
Output : MyThread
#1 Alive:false State:NEW
MyThread
#1 starting.
waiting:true
waiting:true
alive
alive
MyThread
#1 terminating.
alive
MyThread
#1 Alive:false State:TERMINATED
15. Write
a Java Program to interrupt a running
Thread.
Code :
public class GeneralInterrupt
extends Object
implements
Runnable {
public void run() {
try {
System.out.println("in run() -
about to work2()");
work2();
System.out.println("in run() -
back from work2()");
}
catch (InterruptedException x) {
System.out.println("in run() -
interrupted in work2()");
return;
}
System.out.println("in run() -
doing stuff after nap");
System.out.println("in run() -
leaving normally");
}
public void work2() throws InterruptedException
{
while (true) {
if
(Thread.currentThread().isInterrupted()) {
System.out.println("C
isInterrupted()="
+
Thread.currentThread().isInterrupted());
Thread.sleep(2000);
System.out.println("D
isInterrupted()="
+
Thread.currentThread().isInterrupted());
}
}
}
public void work() throws
InterruptedException {
while (true) {
for (int i = 0; i < 100000; i++) {
int j = i * 2;
}
System.out.println("A
isInterrupted()="
+
Thread.currentThread().isInterrupted());
if (Thread.interrupted()) {
System.out.println("B
isInterrupted()="
+
Thread.currentThread().isInterrupted());
throw new InterruptedException();
}
}
}
public static void main(String[] args) {
GeneralInterrupt si = new
GeneralInterrupt();
Thread t = new Thread(si);
t.start();
try {
Thread.sleep(2000);
}
catch (InterruptedException x) {
}
System.out.println("in main() -
interrupting other thread");
t.interrupt();
System.out.println("in main() -
leaving");
}
}
Output :
in run() - about to work2()
in
main() - interrupting other thread
in
main() - leaving
C is Interrupted()=true
in
run() - interrupted in work2()
Applets
1.
Write a Java
Program to create a basic Applet.
Code : import
java.applet.*;
import java.awt.*;
public class Main extends Applet{
public void paint(Graphics g){
g.drawString("Welcome in Java
Applet.",40,20);
}
}
Output : Now compile the above code and call the
generated class in your HTML code as follows:
<HTML>
<HEAD>
<Code : HEAD>
<BODY>
<div >
<APPLET CODE="Main.class"
WIDTH="800" HEIGHT="500">
<Code : APPLET>
<Code : div>
<Code : BODY>
<Code : HTML>
2.
Write a Java
Program to create a banner using Applet.
Code
: import java.awt.*;
import
java.applet.*;
public
class SampleBanner extends Applet
implements
Runnable{
String str = "This is a simple Banner
";
Thread t ;
boolean b;
public void init() {
setBackground(Color.gray);
setForeground(Color.yellow);
}
public void start() {
t = new Thread(this);
b = false;
t.start();
}
public void run () {
char ch;
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = str.charAt(0);
str = str.substring(1, str.length());
str = str + ch;
}
catch(InterruptedException e) {}
}
}
public void paint(Graphics g) {
g.drawRect(1,1,300,150);
g.setColor(Color.yellow);
g.fillRect(1,1,300,150);
g.setColor(Color.red);
g.drawString(str, 1, 150);
}
}
Output
: View
in Browser.
3.
Write a Java
Program to display clock using Applet.
Code : import java.awt.*;
import
java.applet.*;
import java.applet.*;
import
java.awt.*;
import
java.util.*;
public
class ClockApplet extends Applet implements Runnable{
Thread t,t1;
public void start(){
t = new Thread(this);
t.start();
}
public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
t1.sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour =
String.valueOf(cal.get(Calendar.HOUR));
String minute =
String.valueOf(cal.get(Calendar.MINUTE));
String second =
String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" +
minute + ":" + second, 20, 30);
}
}
Output :
4.
Write a Java
Program to create different shapes using
Applet.
Code : import java.applet.*;
import java.awt.*;
public
class Shapes extends Applet{
int x=300,y=100,r=50;
public void paint(Graphics g){
g.drawLine(30,300,200,10);
g.drawOval(x-r,y-r,100,100);
g.drawRect(400,50,200,100);
}
}
Output :
A line , Oval & a Rectangle will be drawn in the browser.
5.
Write a Java
Program to fill colors in shapes using
Applet.
Code : import java.applet.*;
import
java.awt.*;
public
class fillColor extends Applet{
public void paint(Graphics g){
g.drawRect(300,150,200,100);
g.setColor(Color.yellow);
g.fillRect( 300,150, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangle",500,150);
}
}
Output :
A Rectangle with yellow color filled in it willl be drawn in the
browser.
6.
Write a Java
Program togoto a link using Applet.
Code : import java.applet.*;
import
java.awt.*;
import
java.net.*;
import
java.awt.event.*;
public class tesURL extends
Applet implements ActionListener{
public void init(){
String link = "yahoo";
Button b = new Button(link);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){
Button src = (Button)ae.getSource();
String link = "http:Code : Code : www."+src.getLabel()+".com";
try{
AppletContext a = getAppletContext();
URL u = new URL(link);
a.showDocument(u,"_self");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
Output :
View in Browser.
7.
Write a Java
Program to create an event listener in
Applet
Code : import java.applet.*;
import
java.awt.event.*;
import
java.awt.*;
public
class EventListeners extends Applet
implements
ActionListener{
TextArea txtArea;
String Add, Subtract;
int i = 10, j = 20, sum =0,Sub=0;
public void init(){
txtArea = new TextArea(10,20);
txtArea.setEditable(false);
add(txtArea,"center");
Button b = new Button("Add");
Button c = new
Button("Subtract");
b.addActionListener(this);
c.addActionListener(this);
add(b);
add(c);
}
public void actionPerformed(ActionEvent e){
sum = i + j;
txtArea.setText("");
txtArea.append("i = "+ i +
"Output : t" + "j =
" + j + "Output : n");
Button source = (Button)e.getSource();
if(source.getLabel() == "Add"){
txtArea.append("Sum : " +
sum + "Output : n");
}
if(i >j){
Sub = i - j;
}
else{
Sub = j - i;
}
if(source.getLabel() ==
"Subtract"){
txtArea.append("Sub : " +
Sub + "Output : n");
}
}
}
Output
: View
in Browser.
8.
Write a Java Program to display image using Applet.
Code : import java.applet.*;
import java.awt.*;
public class appletImage extends Applet{
Image img;
MediaTracker tr;
public void paint(Graphics g) {
tr = new MediaTracker(this);
img = getImage(getCodeBase(),
"demoimg.gif");
tr.addImage(img,0);
g.drawImage(img, 0, 0, this);
}
}
Output :
View in Browser.
9.
Write a Java Program to open a link in a new window using Applet.
Code : import java.applet.*;
import
java.awt.*;
import
java.net.*;
import
java.awt.event.*;
public class
testURL_NewWindow extends Applet
implements
ActionListener{
public void init(){
String link_Text = "google";
Button b = new Button(link_Text);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){
Button source = (Button)ae.getSource();
String link = "http:Code : Code : www."+source.getLabel()+".com";
try {
AppletContext a = getAppletContext();
URL url = new URL(link);
a.showDocument(url,"_blank");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
Output : View in Browser.
10.
Write a Java
Program to play sound using Applet.
Code : import java.applet.*;
import
java.awt.*;
import
java.awt.event.*;
public
class PlaySoundApplet extends Applet
implements
ActionListener{
Button play,stop;
AudioClip audioClip;
public void init(){
play = new Button(" Play in Loop
");
add(play);
play.addActionListener(this);
stop = new Button(" Stop
");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(),
"Sound.wav");
}
public void actionPerformed(ActionEvent ae){
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play in Loop
"){
audioClip.play();
}
else if(source.getLabel() == " Stop
"){
audioClip.stop();
}
}
}
Output :
View in Browser.
11.
Write a Java Program to read a file using Applet.
Code : import java.applet.*;
import
java.awt.*;
import
java.io.*;
import
java.net.*;
public
class readFileApplet extends Applet{
String fileToRead = "test1.txt";
StringBuffer strBuff;
TextArea txtArea;
Graphics g;
public void init(){
txtArea = new TextArea(100, 100);
txtArea.setEditable(false);
add(txtArea, "center");
String prHtml = this.getParameter("fileToRead");
if (prHtml != null) fileToRead = new
String(prHtml);
readFile();
}
public void readFile(){
String line;
URL url = null;
try{
url = new URL(getCodeBase(),
fileToRead);
}
catch(MalformedURLException e){}
try{
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader
(new InputStreamReader(in));
strBuff = new StringBuffer();
while((line = bf.readLine()) != null){
strBuff.append(line + "Output
: n");
}
txtArea.append("File Name :
" + fileToRead + "Output : n");
txtArea.append(strBuff.toString());
}
catch(IOException e){
e.printStackTrace();
}
}
}
Output :
View in Browser.
12.
Write a Java
Program to write to a file using Applet.
Code
: import java.io.*;
import
java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
import
java.applet.Applet;
import
java.net.*;
public
class WriteFile extends Applet{
Button write = new
Button("WriteToFile");
Label label1 = new Label("Enter the
file name:");
TextField text = new TextField(20);
Label label2 = new Label("Write your
text:");
TextArea area = new TextArea(10,20);
public void init(){
add(label1);
label1.setBackground(Color.lightGray);
add(text);
add(label2);
label2.setBackground(Color.lightGray);
add(area);
add(write,BorderLayout.CENTER);
write.addActionListener(new
ActionListener (){
public void actionPerformed(ActionEvent
e){
new WriteText();
}
}
);
}
public
class WriteText {
WriteText(){
try {
String str = text.getText();
if(str.equals("")){
JOptionPane.showMessageDialog(null,
"Please enter the file
name!");
text.requestFocus();
}
else{
File f = new File(str);
if(f.exists()){
BufferedWriter out = new
BufferedWriter(new
FileWriter(f,true));
if(area.getText().equals("")){
JOptionPane.showMessageDialog
(null,"Please enter your
text!");
area.requestFocus();
}
else{
out.write(area.getText());
if(f.canWrite()){
JOptionPane.showMessageDialog(null,
"Text is written in
"+str);
text.setText("");
area.setText("");
text.requestFocus();
}
else{
JOptionPane.showMessageDialog(null,
"Text isn't written
in "+str);
}
out.close();
}
}
else{
JOptionPane.showMessageDialog
(null,"File not
found!");
text.setText("");
text.requestFocus();
}
}
}
catch(Exception x){
x.printStackTrace();
}
}
}
}
Output :
View in Browser.
13.
Write a Java
Program to use swing applet in JAVA.
Code : import javax.swing.*;
import
java.applet.*;
import
java.awt.*;
import
java.awt.event.*;
public
class SApplet extends Applet implements ActionListener {
TextField input,output;
Label label1,label2;
Button b1;
JLabel lbl;
int num, sum = 0;
public void init(){
label1 = new Label("please enter
number : ");
add(label1);
label1.setBackground(Color.yellow);
label1.setForeground(Color.magenta);
input = new TextField(5);
add(input);
label2 = new Label("Sum : ");
add(label2);
label2.setBackground(Color.yellow);
label2.setForeground(Color.magenta);
output = new TextField(20);
add(output);
b1 = new Button("Add");
add(b1);
b1.addActionListener(this);
lbl = new JLabel("Swing Applet Example.
");
add(lbl);
setBackground(Color.yellow);
}
public void actionPerformed(ActionEvent ae){
try{
num =
Integer.parseInt(input.getText());
sum = sum+num;
input.setText("");
output.setText(Integer.toString(sum));
lbl.setForeground(Color.blue);
lbl.setText("Output of the second
Text Box : "
+ output.getText());
}
catch(NumberFormatException e){
lbl.setForeground(Color.red);
lbl.setText("Invalid
Entry!");
}
}
}
Output :
View in Browser.
Simple
GUI
1.
Write a Java
Program to display text in different
fonts.
Code : import java.awt.*;
import
java.awt.event.*
import
javax.swing.*
public class Main extends
JPanel {
String[] type = {
"Serif","SansSerif"};
int[] styles = { Font.PLAIN, Font.ITALIC,
Font.BOLD,
Font.ITALIC + Font.BOLD };
String[] stylenames =
{ "Plain", "Italic",
"Bold", "Bold & Italic" };
public void paint(Graphics g) {
for (int f = 0; f < type.length;
f++) {
for (int s = 0; s <
styles.length; s++) {
Font font = new Font(type[f],
styles[s], 18);
g.setFont(font);
String name = type[f] + "
" + stylenames[s];
g.drawString(name, 20, (f * 4 +
s + 1) * 20);
}
}
}
public static void main(String[] a) {
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter()
{
public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
f.setContentPane(new Main());
f.setSize(400,400);
f.setVisible(true);
}
}
Output :
Different font names are displayed in a frame.
2.
Write a Java
Program to draw a line using GUI.
Code : import java.awt.*;
import
java.awt.event.*;
import
java.awt.geom.Line2D;
import
javax.swing.JApplet;
import
javax.swing.JFrame;
public
class Main extends JApplet {
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.gray);
int x = 5;
int y = 7;
g2.draw(new Line2D.Double(x, y, 200,
200));
g2.drawString("Line", x, 250);
}
public static void main(String s[]) {
JFrame f = new JFrame("Line");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent
e) {
System.exit(0);
}
});
JApplet applet = new Main();
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(300, 300));
f.setVisible(true);
}
}
Output :
Line is displayed in a frame.
3.
Write a Java
Program to display a message in a new
frame.
Code : import java.awt.*;
import
java.awt.font.FontRenderContext;
import
java.awt.geom.Rectangle2D;
import
javax.swing.JFrame;
import
javax.swing.JPanel;
public
class Main extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Serif",
Font.PLAIN, 48));
paintHorizontallyCenteredText(g2,
"Java Source", 200, 75);
paintHorizontallyCenteredText(g2,
"and", 200, 125);
paintHorizontallyCenteredText(g2,
"Support", 200, 175);
}
protected void
paintHorizontallyCenteredText(Graphics2D g2,
String s, float centerX, float baselineY) {
FontRenderContext frc =
g2.getFontRenderContext();
Rectangle2D bounds =
g2.getFont().getStringBounds(s, frc);
float width = (float) bounds.getWidth();
g2.drawString(s, centerX - width Code
: 2, baselineY);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new Main());
f.setSize(450, 350);
f.setVisible(true);
}
}
Output : JAVA and J2EE displayed in a new
Frame.
4.
Write a Java
Program to draw a polygon using GUI.
Code : import java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
public
class Main extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Polygon p = new Polygon();
for (int i = 0; i < 5; i++)
p.addPoint((int)
(100 + 50 * Math.cos(i * 2 * Math.PI Code
: 5)),
(int) (100 + 50 * Math.sin(i * 2 *
Math.PI Code : 5)));
g.drawPolygon(p);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Polygon");
frame.setSize(350, 250);
frame.addWindowListener(new
WindowAdapter() {
public void windowClosing(WindowEvent
e) {
System.exit(0);
}
});
Container contentPane =
frame.getContentPane();
contentPane.add(new Main());
frame.setVisible(true);
}
}
Output :
Polygon is displayed in a
frame.
5.
Write a Java
Program to display string in a
rectangle.
Code : import java.awt.*;
import
javax.swing.*
public
class Main extends JPanel {
public void paint(Graphics g) {
g.setFont(new Font("",0,100));
FontMetrics fm = getFontMetrics(new
Font("",0,100));
String s = "message";
int x = 5;
int y = 5;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int h = fm.getHeight();
int w = fm.charWidth(c);
g.drawRect(x, y, w, h);
g.drawString(String.valueOf(c), x, y +
h);
x = x + w;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Main());
frame.setSize(500, 700);
frame.setVisible(true);
}
}
Output :
Each character is
displayed in a rectangle.
6.
Write a Java
Program to display different shapes
using GUI.
Code :
import
java.awt.Shape;
import
java.awt.geom.*;
public
class Main {
public static void main(String[] args) {
int x1 = 1, x2 = 2, w = 3, h = 4,
x = 5, y = 6,
y1
= 1, y2 = 2, start = 3;
Shape line = new Line2D.Float(x1, y1, x2,
y2);
Shape arc = new Arc2D.Float(x, y, w, h,
start, 1, 1);
Shape oval = new Ellipse2D.Float(x, y, w,
h);
Shape rectangle = new
Rectangle2D.Float(x, y, w, h);
Shape roundRectangle = new
RoundRectangle2D.Float
(x, y, w, h, 1, 2);
System.out.println("Different shapes
are created:");
}
}
Output :
Different shapes are created.
7.
Write a Java
Program to draw a solid rectange using
GUI.
Code : import java.awt.Graphics;
import
javax.swing.JFrame;
import
javax.swing.JPanel;
public
class Main extends JPanel {
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(400, 400);
f.add(new Main());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public
void paint(Graphics g) {
g.fillRect (5, 15, 50, 75);
}
}
Output :
Solid rectangle is created.
8.
Write a Java
Program to create a transparent cursor.
Code : import java.awt.*;
import
java.awt.image.MemoryImageSource;
public
class Main {
public static void main(String[] argv)
throws Exception {
int[] pixels = new int[16 * 16];
Image image =
Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(16, 16, pixels, 0,
16));
Cursor transparentCursor =
Toolkit.getDefaultToolkit().
createCustomCursor(image, new Point(0,
0),
"invisibleCursor");
System.out.println("Transparent
Cursor created.");
}
}
Output :
Transparent Cursor
created.
9.
Write a Java
Program to check whether antialiasing is
enabled or not.
Code : import java.awt.Graphics;
import
java.awt.Graphics2D;
import
java.awt.RenderingHints;
import
javax.swing.JComponent;
import
javax.swing.JFrame;
public
class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new MyComponent());
frame.setSize(300, 300);
frame.setVisible(true);
}
}
class
MyComponent extends JComponent {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
RenderingHints rh =
g2d.getRenderingHints();
boolean bl = rh.containsValue
(RenderingHints.VALUE_ANTIALIAS_ON);
System.out.println(bl);
g2.setRenderingHint(RenderingHints.
KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
}
Output :
False
False
False
10.
Write a Java
Program to display colours in a frame.
Code : import java.awt.Graphics;
import
java.awt.event.WindowAdapter;
import
java.awt.event.WindowEvent;
import
java.awt.image.BufferedImage;
import
javax.swing.JComponent;
import
javax.swing.JFrame;
public
class Main extends JComponent {
BufferedImage image;
public void initialize() {
int
width = getSize().width;
int height = getSize().height;
int[] data = new int[width * height];
int index = 0;
for (int i = 0; i < height; i++) {
int red = (i * 255) Code : (height
- 1);
for (int j = 0; j < width; j++) {
int green = (j * 255) Code : (width
- 1);
int blue = 128;
data[index++] = (red < < 16)
| (green < < 8) | blue;
}
}
image = new BufferedImage
(width, height,
BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, width, height, data,
0, width);
}
public void paint(Graphics g) {
if (image == null)
initialize();
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) {
JFrame f = new JFrame("Display
Colours");
f.getContentPane().add(new Main());
f.setSize(300, 300);
f.setLocation(100, 100);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent
e) {
System.exit(0);
}
});
f.setVisible(true);
}
}
Output : Displays all the colours
in a frame.
11.
Write a Java
Program to display a pie chart using a
frame.
Code : import java.awt.Color;
import
java.awt.Graphics;
import
java.awt.Graphics2D;
import
java.awt.Rectangle;
import
javax.swing.JComponent;
import
javax.swing.JFrame;
class
Slice {
double value;
Color color;
public Slice(double value, Color color)
{
this.value = value;
this.color = color;
}
}
class
MyComponent extends JComponent {
Slice[] slices = { new Slice(5,
Color.black),
new Slice(33, Color.green),
new Slice(20, Color.yellow), new Slice(15,
Color.red) };
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(),
slices);
}
void drawPie(Graphics2D g, Rectangle area,
Slice[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length;
i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length;
i++) {
startAngle = (int) (curValue * 360 Code
: total);
int arcAngle = (int) (slices[i].value
* 360 Code : total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width,
area.height,
startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
public
class Main {
public static void main(String[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().add(new
MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Output : Displays a piechart in a frame.
12.
Write a Java
Program to draw text using GUI.
Code : import java.awt.Font;
import
java.awt.Graphics;
import
java.awt.Graphics2D;
import
java.awt.RenderingHints;
import
javax.swing.JFrame;
import
javax.swing.JPanel;
public
class Main extends JPanel{
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Font font = new Font("Serif",
Font.PLAIN, 96);
g2.setFont(font);
g2.drawString("Text", 40, 120);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new Main());
f.setSize(300, 200);
f.setVisible(true);
}
}
Output : Text is displayed in a frame.
JDBC
1.
Write a Java
Program to establishing a connection
with Database.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class
found");
int no_of_rows = 0;
try {
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","username",
"password");
Statement stmt =
con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
while (rs.next()) {
no_of_rows++;
}
System.out.println("There are "+
no_of_rows
+ " record in the table");
}
catch(SQLException e){
System.out.println("SQL exception
occured" + e);
}
}
}
Output :
JDBC Class found
There are 2 record in the table
2.
Write a Java
Program to Create, edit & alter
table using Java.
Code : import
java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws
Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","username",
"password");
Statement stmt = con.createStatement();
String query ="CREATE TABLE
employees
(id INTEGER PRIMARY KEY,
first_name CHAR(50),last_name
CHAR(75))";
stmt.execute(query);
System.out.println("Employee table
created");
String query1 = "aLTER TABLE
employees ADD
address CHAR(100) ";
String query2 = "ALTER TABLE
employees DROP
COLUMN last_name";
stmt.execute(query1);
stmt.execute(query2);
System.out.println("Address column
added to the table
& last_name column removed from the
table");
String query3 = "drop table
employees";
stmt.execute(query3);
System.out.println("Employees table
removed");
}
}
Output :
Employee table created
Address column added to the table &
last_name
column removed from the table
Employees table removed from the database
3.
Write a Java
Program to display contents of table .
Code : import java.sql.*;
public class jdbcResultSet {
public
static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not
found "+ e);
}
try {
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","username",
"password");
Statement stmt =
con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
System.out.println("id name
job");
while (rs.next()) {
int id = rs.getInt("id");
String name =
rs.getString("name");
String job =
rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception
occured" + e);
}
}
}
Output : id
name job
1
alok trainee
2
ravi trainee
4.
Write a Java
Program to update, edit & delete
rows .
Code : import java.sql.*;
public class updateTable {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not
found "+ e);
}
try {
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","username",
"password");
Statement stmt =
con.createStatement();
String query1="update emp set
name='ravi' where id=2";
String query2 = "delete from emp where id=1";
String query3 = "insert into emp
values
(1,'ronak','manager')";
stmt.execute(query1);
stmt.execute(query2);
stmt.execute(query3);
ResultSet rs =
stmt.executeQuery("SELECT * FROM emp");
System.out.println("id name
job");
while (rs.next()) {
int id = rs.getInt("id");
String name =
rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception
occured" + e);
}
}
}
Output :
id name job
2
ravi trainee
1
ronak manager
5.
Write a Java Program to search in the database using java
commands.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","username",
"password");
Statement stmt = con.createStatement();
String query[] ={"SELECT * FROM emp
where id=1",
"select name from emp where name
like 'ravi_'",
"select name from emp where name
like 'ravi%'"};
for(String q : query){
ResultSet rs = stmt.executeQuery(q);
System.out.println("Names for
query "+q+" are");
while (rs.next()) {
String name =
rs.getString("name");
System.out.print(name+" ");
}
System.out.println();
}
}
}
Output :
Names for query SELECT * FROM emp where id=1 are
ravi
Names
for query select name from emp where name like 'ravi_' are
ravi2 ravi3
Names
for query select name from emp where name like 'ravi%' are
ravi ravi2
ravi3 ravi123 ravi222
6.
Write a Java Program to sort elements of a column using java
commands.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","name","pass");
Statement stmt = con.createStatement();
String query = "select * from emp
order by name";
String query1="select * from emp
order by name, job";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Table contents
sorted by Name");
System.out.println("Id Name Job");
while (rs.next()) {
int id = rs.getInt("id");
String name =
rs.getString("name");
String job = rs.getString("job");
System.out.println(id + " " + name+" "+job);
}
rs = stmt.executeQuery(query1);
System.out.println("Table contents
after sorted
by Name & job");
System.out.println("Id Name Job");
while (rs.next()) {
int id = rs.getInt("id");
String name =
rs.getString("name");
String job =
rs.getString("job");
System.out.println(id + " " + name+" "+job);
}
}
}
Output : Table contents after sorting by
Name
Id
Name Job
1 ravi
trainee
5 ravi
MD
4 ravi
CEO
2 ravindra
CEO
2 ravish
trainee
Table
contents after sorting by Name & job
Id
Name Job
4 ravi
CEO
5 ravi
MD
1 ravi
trainee
2 ravindra
CEO
2 ravish
trainee
7.
Write a Java
Program to combine data from more than
one tables.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","username",
"password");
Statement stmt = con.createStatement();
String query ="SELECT
fname,lname,isbn from author
inner join books on author.AUTHORID =
books.AUTHORID";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Fname Lname
ISBN");
while (rs.next()) {
String fname =
rs.getString("fname");
String lname = rs.getString("lname");
int isbn =
rs.getInt("isbn");
System.out.println(fname + " " + lname+" "+isbn);
}
System.out.println();
System.out.println();
}
}
Output
: Fname
Lname ISBN
john grisham
123
jeffry archer
113
jeffry archer
112
jeffry archer
122
8.
Write a Java
Program to use commit statement in Java.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","name","pass");
Statement stmt = con.createStatement();
String query = "insert into emp
values(2,'name1','job')";
String query1 ="insert into emp
values(5,'name2','job')";
String query2 = "select * from
emp";
ResultSet rs = stmt.executeQuery(query2);
int no_of_rows = 0;
while (rs.next()) {
no_of_rows++;
}
System.out.println("No. of rows
before commit
statement = "+ no_of_rows);
con.setAutoCommit(false);
stmt.execute(query1);
stmt.execute(query);
con.commit();
rs = stmt.executeQuery(query2);
no_of_rows = 0;
while (rs.next()) {
no_of_rows++;
}
System.out.println("No. of rows
after commit
statement = "+ no_of_rows);
}
}
Output : No. of rows before commit statement = 1
No. of rows after commit statement = 3
9.
Write a Java
Program to us prepared statement in
Java.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","name","pass");
PreparedStatement updateemp =
con.prepareStatement
("insert into emp
values(?,?,?)");
updateemp.setInt(1,23);
updateemp.setString(2,"Roshan");
updateemp.setString(3, "CEO");
updateemp.executeUpdate();
Statement stmt = con.createStatement();
String query = "select * from
emp";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Id Name Job");
while (rs.next()) {
int id = rs.getInt("id");
String name =
rs.getString("name");
String job =
rs.getString("job");
System.out.println(id + " " + name+" "+job);
}
}
}
Output : Id Name
Job
23
Roshan CEO
10.
Write a Java
Program to set &rollback to a
savepoint.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","name","pass");
Statement stmt = con.createStatement();
String query1 = "insert into emp
values(5,'name','job')";
String query2 = "select * from
emp";
con.setAutoCommit(false);
Savepoint spt1 =
con.setSavepoint("svpt1");
stmt.execute(query1);
ResultSet rs = stmt.executeQuery(query2);
int no_of_rows = 0;
while (rs.next()) {
no_of_rows++;
}
System.out.println("rows before
rollback statement = "
+ no_of_rows);
con.rollback(spt1);
con.commit();
no_of_rows = 0;
rs = stmt.executeQuery(query2);
while (rs.next()) {
no_of_rows++;
}
System.out.println("rows after
rollback statement = "
+ no_of_rows);
}
}
Output :
rows before rollback statement = 4
rows after rollback statement = 3
11.
Write a Java
Program to execute a batch of SQL
statements using java.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertEmp1 = "insert into emp
values
(10,'jay','trainee')";
String insertEmp2 = "insert into emp
values
(11,'jayes','trainee')";
String insertEmp3 = "insert into emp
values
(12,'shail','trainee')";
con.setAutoCommit(false);
stmt.addBatch(insertEmp1);
stmt.addBatch(insertEmp2);
stmt.addBatch(insertEmp3);
ResultSet rs = stmt.executeQuery("select
* from emp");
rs.last();
System.out.println("rows before
batch execution= "
+ rs.getRow());
stmt.executeBatch();
con.commit();
System.out.println("Batch
executed");
rs = stmt.executeQuery("select *
from emp");
rs.last();
System.out.println("rows after batch
execution= "
+ rs.getRow());
}
}
Output :
rows before batch execution= 6
Batch executed
rows
after batch execution= = 9
12.
Write a Java
Program to use different row methods in
java.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String query = "select * from
emp";
ResultSet rs = stmt.executeQuery(query);
rs.last();
System.out.println("No of rows in
table="+rs.getRow());
rs.moveToInsertRow();
rs.updateInt("id", 9);
rs.updateString("name","sujay");
rs.updateString("job",
"trainee");
rs.insertRow();
System.out.println("Row
added");
rs.first();
rs.deleteRow();
System.out.println("first row
deleted");
}
}
Output : No of rows in table=5
Row added
first row deleted
13.
Write a Java
Program to use different column methods
in java.
Code : import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection
("jdbc:derby:Code : Code : localhost:1527Code
: testDb","name","pass");
Statement stmt = con.createStatement();
String query = "select * from emp
order by name";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd =
rs.getMetaData();
System.out.println("no of columns in
the table= "+
rsmd.getColumnCount());
System.out.println("Name of the
first column "+
rsmd.getColumnName(1));
System.out.println("Type of the
second column "+
rsmd.getColumnTypeName(2));
System.out.println("No of characters
in 3rd column "+
rsmd.getColumnDisplaySize(2));
}
}
Output :
no of columns in the table= 3
Name
of the first columnID
Type of the second columnVARCHAR
No of characters in 3rd column20