You are on page 1of 83

JAVA PROGRAMMING

Science and Engineering

LAB

Department of Computer

JAVA PROGRAMMING LAB (13A05408)


Week 1 :
1) Write a Java program that prompts the user for an integer and then prints out all
prime numbers up to that integer.
Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input value n
Step4: Implement a method for performing the logic to generate prime numbers up to
the value of n.
Step5: Display output.
Step6: End.
Source code:
import java.lang.*;
import java.io.*;
class prime
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
for(int r=0;r<n;r++)
{
int t=0;
for(int i=1;i<r;i++)
{
if (r%i==0)
{
t++;
}
}
if(t<2)
{
System.out.print(r);
1

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

System.out.print(" ");
}
}
}
}

Sample output:
Enter a Nmuber 10
The Prime numbers up to 10 are
2 3 5 7

Expected Input & Output:

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. what is object?
2. What is class?
3. What is object oriented programming?
4. Differentiate C++ vs Java?
5. What is Encapsulation?
6. What is Polymorphism?
7. What is Dynamic Binding?
8. Does java is Platform InDependent?Why?
9. What is Inheritence
10.What is Abtraction?
Week 2:
1) Write a Java program that prints all real solutions to the quadratic equation ax2
+ bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b24ac is negative, display a message stating that there are
no real solutions.
Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values.
Step4: Implement a method for performing logic to obtain solution for the given
quadratic equation.
Step5: Display output.
Step6: End.
Source code:
import java.io.*;
import java.io.*;
class root
{

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

public static void main(String args[])throws IOException


{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(br.readLine());
int b=Integer.parseInt(br.readLine());
int c=Integ
er.parseInt(br.readLine());
int d=((b*b)-(4*a*c));
if(d>0)
{
System.out.print("roots are real and distinct");
}
if(d==0)
{
System.out.print("roots are real");
}
if(d<0)
{
System.out.print("there is no solution");
}
}
}
Sample Output:
Enter a b c values : 2 4 2
The roots are real and equal
Expected Input & Output:

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

2) Write a Java program for sorting a given list of names in ascending order.
Algorithm:
Step1:
Step2:
Step3:
Step4:
order.
Step5:
Step6:

Begin
Create a class and initialize class members and methods.
Read input values.
Implement a method for performing the logic to sort the values in ascending
Display output.
End.

Source code:
import java.lang.*;
import java.io.*;
class asc
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter how many strings");
int n=Integer.parseInt(br.readLine());
String x[]=new String[n];
System.out.print("enter "+n+" strings");
for(int i=0;i<n;i++)
{
x[i]=br.readLine();
}
String s=new String();
for(int i=0;i<n;i++)

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

{
for(int j=0;j<n;j++)
{
if(x[i].compareTo(x[j])<6)
{
s=x[i];
x[i]=x[j];
x[j]=s;
}
}
}
System.out.print("string in alphebetical order are");
for(int i=0;i<n;i++)
{
System.out.println(x[i]);
}
}
}
Sample Output:
Tharun
Dillip
Prasad
Sravan
Harish
Ali
string in alphebetical order are
Ali
Dillip
Harish
Prasad
Sravan
Tharun
Expected Input & Output:

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

3) Write a java program to accept a string from user and display number of vowels,
consonants, digits and special characters present in each of the words of the given
text.
Algorithm:
Step1:
Step2:
Step3:
Step4:
special
Step5:
Step6:

Begin
Create a class and initialize class members and methods.
Read input values
Implement a method for identifying the number of vowels, consonants, digits and
characters present in the text.
Display output.
End.

Source code:
import java.io.*;
class q5vowels
{
public static void main(String args[]) throws IOException
{
String str;
int vowels = 0, digits = 0, blanks = 0;

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

char ch;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a String : ");
str = br.readLine();
for(int i = 0; i < str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch
== 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowels ++;
else if(Character.isDigit(ch))
digits ++;
else if(Character.isWhitespace(ch))
blanks ++;
}

System.out.println("Vowels : " + vowels);


System.out.println("Digits : " + digits);
System.out.println("Blanks : " + blanks);

}
Sample Output :
Java Lab Programming 2015
Vowel : 6
Digits : 4
Blanks : 3
Expected Input & Output:

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. What is JVM ? Why is Java called the Platform Independent Programming Language
2. What is the Difference between JDK and JRE ?
3. What does the static keyword mean ? Can you override private or static method in
Java ?
4. Can you access non static variable in static context ?
5. What are the Data Types supported by Java ? What is Autoboxing and Unboxing ?
6. What is Function Overriding and Overloading in Java ?
7. What is a Constructor, Constructor Overloading in Java and Copy-Constructor
8. Does Java support multiple inheritance ?
9. What is the difference between an Interface and an Abstract class ?
10. What are pass by reference and pass by value ?

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Week 3 :
1) Write a java program to make rolling a pair of dice 10,000 times and counts the
number of times doubles of are rolled for each different pair of doubles.
Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values
Step4: Implement the method to perform a logic for rolling a pair of dice 10,000 times.
Step5: Implement another method for counting the number of times doubles are rolled
for each different pair of doubles.
Step6: Display output.
Step7`: End.
Source code:

public class DiceRollStats {

10

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

static final int NUMBER_OF_EXPERIMENTS = 10000;


public static void main(String[] args) {

double average; // The average number of rolls to get a given total.


TextIO.putln("Total On Dice
Average Number of Rolls");
TextIO.putln("-----------------------------------");
for ( int dice = 2; dice <= 12; dice++ ) {
average = getAverageRollCount( dice );
TextIO.put(dice,10);
TextIO.put("
");
TextIO.putln(average);
}
static double getAverageRollCount( int roll ) {
// Find the average number of times a pair of dice must
// be rolled to get a total of "roll". Roll MUST be
// one of the numbers 2, 3, ..., 12.
int rollCountThisExperiment; // Number of rolls in one experiment.
int rollTotal; // Total number of rolls in all the experiments.
double averageRollCount; // Average number of rolls per experiment.
rollTotal = 0;
for ( int i = 0; i < NUMBER_OF_EXPERIMENTS; i++ ) {
rollCountThisExperiment = rollFor( roll );
rollTotal += rollCountThisExperiment;
}
averageRollCount = ((double)rollTotal) / NUMBER_OF_EXPERIMENTS;
return averageRollCount;

}
static int rollFor( int N ) {
// Roll a pair of dice repeatedly until the total on the
// two dice comes up to be N. N MUST be one of the numbers
// 2, 3, ..., 12. (If not, this routine will go into an
// infinite loop!). The number of rolls is returned.
int die1, die2; // Numbers between 1 and 6 representing the dice.
int roll;
// Total showing on dice.
int rollCt;
// Number of rolls made.
rollCt = 0;
do {
11

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
rollCt++;
} while ( roll != N );
return rollCt;
}
} // end DiceRollStats

Sample Output:
Total On Dice

Average Number of Rolls : 674

Expected Input & Output:

2) Write java program that inputs 5 numbers, each between 10 and 100 inclusive.
As each number is read display it only if its not a duplicate of any number already
read display the complete set of unique values input after the user enters each new
value.

Algorithm:
12

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values
Step4: Implement a method to perform a logic for identifying the duplicate of a number
if it already exists.
Step5: Display output.
Step6: End.
Source code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sid[] = new int[5];
int count = 0;
int x = 0;
int num = 0;
while (x < sid.length)
{
System.out.println("Enter number: ");
num = input.nextInt();
if ((num >= 10) && (num <= 100)) {
boolean digit = false;
x++;
for (int i = 0; i < sid.length; i++)
{ if (sid[i] == num)
digit = true;
}
if (!digit) {
sid[count] = num;
count++;
}

13

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

else
System.out.printf("the number was entered before \n");
}
else
System.out.println("number must be between 10 and 100");
for (int i =0; i < x; i++) {
System.out.print(sid[i] +" ");
}
}
}

System.out.println();

Sample Out :
Enter Numbers 5 56 65 56 56 98
the number was entered before is 56
number must be between 10 and 100 are
5 56 65 98
Expected Input & Output:

14

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

3) Write a java program to read the time intervals (HH:MM) and to compare system
time if the system time between your time intervals print correct time and exit
else try again to repute the same thing By using StringToknizer class.

Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input time intervals in Hour and minute formats.
15

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Step4: Implement a method to perform a logic for comparing the entered time and our
time and check whether both timing are correct or not by using StringTokenizer Class.
Step5: Display output.
Step6: End.
Source Code:

16

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

17

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output :
the time intervals (HH:MM) :: 12 45
Present time is 12:45
the time entered and present time are same

Expected Input & Output:

Questions:
1. What is the difference between processes and threads ?
2. Explain different ways of creating a thread. Which one would you prefer and why ?
3. Explain the available thread states in a high-level
4. What is the difference between a synchronized method and a synchronized block ?
5. How does thread synchronization occurs inside a monitor ?

18

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

6. Whats a deadlock ?
7. How do you ensure that N threads can access N resources without deadlock ?
8. What are the basic interfaces of Java Collections Framework ?
9. Why Collection doesnt extend Cloneable and Serializable interfaces ?
10.What is an Iterator ?

19

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Week 4 :
1) Write a java program to split a given text file into n parts. Name each part as the
name of the original file followed by .part<n> where n is the sequence number of
the part file.
Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values
Step4: Implement a method to perform a logic for splitting a given text file into n parts
by using I/O functions.
Step5: Display output.
Step6: End.
Source code:
import java.io.*;
import java.util.Scanner;
public class split {
public static void main(String args[])
{
try{
// Reading file and getting no. of files to be generated
String inputfile = "C:/test.txt"; // Source File Name.
double nol = 2000.0; // No. of lines to be split and saved in each output file.
File file = new File(inputfile);
Scanner scanner = new Scanner(file);
int count = 0;
while (scanner.hasNextLine())
{
scanner.nextLine();
count++;
}

20

JAVA PROGRAMMING
Science and Engineering

LAB

System.out.println("Lines in the file: " + count);


le.

Department of Computer
// Displays no. of lines in the input fi

double temp = (count/nol);


int temp1=(int)temp;
int nof=0;
if(temp1==temp)
{
nof=temp1;
}
else
{
nof=temp1+1;
}
System.out.println("No. of files to be generated :"+nof); // Displays no. of files to be gene
rated.

// Actual splitting of file into smaller files


FileInputStream fstream = new FileInputStream(inputfile); DataInputStream in = new D
ataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine;
for (int j=1;j<=nof;j++)
{
FileWriter fstream1 = new FileWriter("C:/New Folder/File"+j+".txt");
le Location
BufferedWriter out = new BufferedWriter(fstream1);
for (int i=1;i<=nol;i++)
{
strLine = br.readLine();
if (strLine!= null)
{
out.write(strLine);
if(i!=nol)
{
out.newLine();
}

// Destination Fi

21

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

}
out.close();

in.close();
}catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

Sample Output :
Enter a Textfile :
Upload a text file say for ex: java.txt
Lines in the file: 4000
No. of files to be generated : 2

Expected Input & Output:

22

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

2) Write java program to create a super class called Figure that receives the
dimensions of two dimensional objects. It also defines a method called area that
computes the area of an object. The program derives two subclasses from Figure.
The first is Rectangle and second is Triangle. Each of the sub class overridden
area() so that it returns the area of a rectangle and a triangle respectively.
Algorithm:
Step1: Begin
Step2: Create a super class Figure that receives the dimensions of two dimensional
objebts
Step3: Define a method called area that computes the area of an object
Step4: Program should derive two subclasses from Figure. The first is Rectangle and
second is Triangle.
Step5: Each sub class computes area seperately
Step6: Display the output
Step7: End

Source Code:

23

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

24

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output:
Enter the dimensions of two objects:
20 40 20 40
The Area of Rectangle is 120 sq.mts
The Area of Rectangle is 40 sq.mts
Expected Input & Output:

25

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

3) Write a Java program that creates three threads. First thread displays Good
Morning every one second, the second thread displays Hello every two seconds
and the third thread displays Welcome every three seconds.
Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values
Step4: Using threads implement 3 threads methods to display messages like GOOD
MORNING, HELLO, WELCOME in specified time intervals.
Step5: Display output.
Step6: End.
Source code:
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(10);
System.out.println("good morning");
}
}
catch(Exception e)
{}
}
}
class B extends Thread
{
synchronized public void run()
{
try
{

26

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

while(true)
{
sleep(20);
System.out.println("hello");
}
}
catch(Exception e)
{}
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(30);
System.out.println("welcome");
}
}
catch(Exception e)
{}
}
}
class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
Sample Output :

27

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Good Morning
Good Morning
Hello
Welcome
Good Morning
Good Morning
Hello
Welcome
Good Morning
Good Morning
Hello
Welcome
Good Morning
Good Morning
Hello
Welcome
Good Morning
Expected Input & Output:

28

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. What differences exist between Iterator and ListIterator ?
2. What is difference between fail-fast and fail-safe
3. How HashMap works in Java ?
4. What is the importance of hashCode() and equals() methods ?
5. What differences exist between HashMap and Hashtable ?
6. What is difference between Array and ArrayList ?
7. What is difference between ArrayList and LinkedList ?
8. What is Comparable and Comparator interface ?
9. What is Java Priority Queue ?
10.What do you know about the big-O notation and can you give
some examples with respect to different data structures ?
Week 5:
1) Write a Java program that correctly implements producer consumer problem
using the concept of inter thread communication.
Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values
Step4: Implement 2 different threads for allocating the resources and consuming the
resources.
Step5: Provide inter thread communication between them to resolve the problem.
Step6: Display output.
Step7: End.
Source code:

29

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

class Q
{
boolean valueSet=false;
int n;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Exception is:"+e);
}
System.out.println("got:"+n);
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println
("\n Exception in put:"+e);
}
this.n=n;
valueSet=true;
System.out.println("\nput:"+n);
notify();
}
}
class Producer implements Runnable
{
30

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
q.put(i++);
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
q.get();
}
}
class ProdConsDemo
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("\n press ctrl+c to stop");
}
}
Sample Output:

31

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Exception is: got:


Exception in put : put

Expected Input & Output:

2) Write a java program to find and replace pattern in given file


Algorithm:
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:
Step7:
Step8:

Begin
Create a class and initialize class members and methods.
Read input value.
Implement a method to read the data from the input device.
Implement another method for finding the given pattern in the file.
Implement another method for replacing the pattern with the text.
Display output.
End.

32

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Source code:
import
import
import
import
import
import
import

java.io.BufferedReader;
java.io.IOException;
java.io.Reader;
java.util.Arrays;
java.util.LinkedList;
java.util.List;
java.util.StringTokenizer;

public abstract class StringHelper {


public static String replaceAll(String source, final String findToken, final String replac
eToken) {
if (source == null) { return null; }
StringBuilder sb = null;
int pos;
do {
if ((pos = source.indexOf(findToken)) < 0) {
break;
}
if (sb == null) {
sb = new StringBuilder();
}
if (pos > 0) {
sb.append(source.substring(0, pos));
}
sb.append(replaceToken);
source = source.substring(pos + findToken.length());
} while (source.length() > 0);
if (sb == null) {
return source;
} else {
sb.append(source);
return sb.toString();
}
}
}

33

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output :
Given String is Java Manual Programming
Inserted String is :: Lab
Final String is Java Lab Programming

Expected Input & Output:

3) Use inheritance to create an exception super class called EexceptionA and


exception subclass ExceptionB and ExceptionC, where ExceptionB inherits from
ExceptionA and ExceptionC inherits from ExceptionB. Write a java program to
demonstrate that the catch block for type ExceptionA catches exception of type
ExceptionB and ExceptionC

Algorithm:
Step1: Begin
Step2: Create a super and sub classes using inheritance and initialize class members
and methods.
Step3: Perform the exception handling functions for the above classes.
34

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Step4: Display output.


Step5: End.
Source code:
Create exception ExceptionA and define require constructors and methods:
public class ExceptionA extends Exception {
public ExceptionA(String message){
super(message);
}
}
Create exception ExceptionB and define require constructors and methods:
public class ExceptionB extends ExceptionA {
public ExceptionB(String message){
super(message);
}
}
Create exception ExceptionC and define require constructors and methods:
public class ExceptionC extends ExceptionB {
public ExceptionC(String message){
super(message);
}
}
Create TestException class which
catches ExceptionB and ExceptionC using ExceptionA as below:
public class TestException {
public static void main(String[] args){
try{
getExceptionB();
}catch(ExceptionA ea){
ea.printStackTrace();
}
try{
getExceptionC();
}catch(ExceptionA ea){
35

JAVA PROGRAMMING
Science and Engineering
}

LAB

Department of Computer

ea.printStackTrace();

}
public static void getExceptionB() throws ExceptionB{
throw new ExceptionB("Exception B");
}
public static void getExceptionC() throws ExceptionC{
throw new ExceptionC("Exception C");
}
}
Sample Output :
The output for the above program is simulated after running the program with compiler.
Expected Input & Output:

36

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. When does an Object becomes eligible for Garbage collection in Java ?
2. Does Garbage collection occur in permanent generation space in JVM ?
3. What are the two types of Exceptions in Java ? Which are the differences between
them ?
4. What is the difference between Exception and Error in java ?
5. What is the difference between throw and throws ?
6. What is the importance of finally block in exception handling ?
7. What will happen to the Exception object after exception handling ?
8. How does finally block differ from finalize() method ?
9. What is an Applet ?
10.Explain the life cycle of an Applet
Week 6 :
1) Write a java program to convert an ArrayList to an Array.
Algorithm:
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:

Begin
Create a class and initialize class members and methods.
Read input values
Implement the method to perform a logic for converting an array list to an array..
Display output.
End.
37

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Source code:
import java.util.*;
public class ArrayListTOArray {
public static void main(String[] args) {
/*ArrayList declaration and initialization*/
ArrayList<String> arrlist= new ArrayList<String>();
arrlist.add("String1");
arrlist.add("String2");
arrlist.add("String3");
arrlist.add("String4");
/*ArrayList to Array Conversion */
String array[] = new String[arrlist.size()];
for(int j =0;j<arrlist.size();j++){
array[j] = arrlist.get(j);
}

/*Displaying Array elements*/


for(String k: array)
{
System.out.println(k);
}

}
Sample Output :
The ArrayList of the program is :
Java
Applets
Beans
Servlet
The Array for the above List is
Java Applets Beans Servlet

38

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Expected Input & Output:

2) Write a Java Program for designing a Flag using Applets and Threads
Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values
Step4: Implement the method to perform a logic for designing a flag using applets and
threads.
Step5: Display output.
Step6: End.
Source code:
import java.io.*;
import java.applet.*;
import java.awt.*;
public class flag extends Applet
{
public void paint(Graphics g)
39

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

{
g.fillOval(60,450,120,50);
g.fillRect(110,60,10,400);
g.setColor(Color.red);
g.fillRect(120,80,150,30);
g.setColor(Color.white);
g.fillRect(120,110,150,30);
g.setColor(Color.green);
g.fillRect(120,140,150,30);
g.setColor(Color.black);
g.drawRect(120,80,150,90);
g.setColor(Color.blue);
g.drawOval(180,110,30,30);
int t=0;
int x=195,y=125;
double x1,y1;
double r=15;
double d;
for(int i=1;i<=24;i++)
{
d=(double)t*3.14/180.0;
x1=x+(double)r*Math.cos(d);
y1=y+(double)r*Math.sin(d);
g.drawLine(x,y,(int)x1,(int)y1);
t+=360/24;
}
}
}
Sample Output :
The ouput for the above program can be simulated by running & executing applets
Expected Input & Output:

40

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

3. Write a Java Program for Bouncing Ball (The ball while moving down has to
increase the size and decrease the size while moving up)
Algorithm:
Step1: Begin
Step2: Create a applet code for bouncing ball
Step3: Initialize Motion class
Step4: Implement the method to perform a logic for bouncing ball such that (The ball
while moving down has to increase the size and decrease the size while moving up)
Step5: Display output.
Step6: End.

Source Code:

41

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

42

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output :
Output can be taken after simulating the output by running Applet program

Expected Input & Output:

43

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. What happens when an applet is loaded ?
2. What is the difference between an Applet and a Java Application ? .
3. What are the restrictions imposed on Java applets ?
4. What are untrusted applets ?
5. What is the difference between applets loaded over the internet and applets loaded
via the file system ?
6. What is the applet class loader, and what does it provide ?
7. What is the applet security manager, and what does it provide ?
8. What is the difference between a Choice and a List ?
9. What is a layout manager ?
10.
What is the difference between a Scrollbar and a JScrollPane ?
Week 7 :
1. Write a Java Program for stack operation using Buttons and JOptionPane
input and Message dialog box.

44

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Algorithm:
Step1: Begin
Step2: Create a applet code for stack
Step3: Initialize JOption Pane
Step4: Implement the method to perform stack operation using Buttons and JOptionPane
input and Message dialog box.
Step5: Display output.
Step6: End.

Source Code:

45

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

46

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output :
Enter your option
1. Insertion
2. Deletion
3. Display
4. Exit
1.Enter an element : 5
Element Inserted
Enter your option
1. Insertion
2. Deletion
3. Display
4. Exit
3 The elements are 5
Enter your option
1. Insertion
2. Deletion
3. Display
4. Exit
4
Expected Input & Output:

47

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

2. Write a Java Program to Addition, Division, Multiplication and subtraction


using JOptionPane dialog Box and Textfields.
Algorithm:
Step1: Begin
Step2: Create a applet code Addition, Division, Multiplication and subtraction using
JOptionPane dialog Box
Step3: Initialize JOption Pane
Step4: Implement the method to perform Addition, Division, Multiplication and
subtraction using Buttons and JOptionPane input and Message dialog box.
Step5: Display output.
Step6: End.

48

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Source Code:

49

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

50

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output:
Enter the Numbers :
20 5
Addition is 25
Subtraction is 15
Multiplication os 100

Expected Input & Output:

51

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. Which Swing methods are thread-safe ?
2. Name three Component subclasses that support painting.
3. What is clipping ?
4. What is the difference between a MenuItem and a CheckboxMenuItem ?
5. How are the elements of a BorderLayout organized ?
6. How are the elements of a GridBagLayout organized ?
7. What is the difference between a Window and a Frame ?
8. What is the relationship between clipping and repainting ?
9. What is the relationship between an event-listener interface and an event-adapter
class ?
10.How can a GUI component handle its own events ?
Week 8:
1. Write a Java Program for the blinking eyes and mouth should open while
blinking.
Algorithm:
Step1: Begin
Step2: Create a applet code for blinking eyes
Step3: Similarly perform the same for opening mouth while blinking
Step4: Implement the method to blinking eyes and mouth should open while blinking.
Step5: Display output.
Step6: End.

Source Code:

52

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

53

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output:
Simulated through Applets
Expected Input & Output:

54

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

2. Implement a Java Program to add a new ball each time the user clicks the
mouse. Provided a maximum of 20 balls randomly choose a color for each ball.
Algorithm:
Step1: Begin
Step2: Create a new ball
Step3: Click the ball through mouse
Step4: Implement the method to generate maximum of 20 balls of your random color .
Step5: Display output.
55

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Step6: End.
Source Code:

56

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output :
Output can be simulated by running applets
Expected Input & Output:

57

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1 What is URL Encoding and URL Decoding ?
2 What is a JSP Page ?
3 How are the JSP requests handled ?
4 What are the advantages of JSP ?
5 What are Directives ? What are the different types of Directives available in JSP ?
6 What are JSP actions ?
7 What are Scriptlets ?
8 What are Decalarations ?
9 What are Expressions ?
10 What is meant by implicit objects and what are they ?

58

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Week 9:
1) Suppose that a table named Table.txt is stored in a text file. The first line in the
file is the header, and the remaining lines correspond to rows in the table. The
elements are separated by commas. Write a java program to display the table using
Jtable component.
Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values

59

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Step4: Implement the method to perform a logic for displaying a table using Jtable
component.
Step5: Display output.
Step6: End.
Source code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Table1 extends JFrame
{
int i=0;
int j=0,k=0;
Object data[][]=new Object[5][4];
Object list[][]=new Object[5][4];
JButton save;
JTable table1;
FileInputStream fis;
DataInputStream dis;
public Table1()
{
String d= " ";
Container con=getContentPane();
con.setLayout(new BorderLayout());
final String[] colHeads={"Name","Roll Number","Department","Percentage"};
try
{
String s=JOptionPane.showInputDialog("Enter the File name present in the current
directory");
FileInputStream fis=new FileInputStream(s);
DataInputStream dis = new DataInputStream(fis);
while ((d=dis.readLine())!=null)
{
StringTokenizer st1=new StringTokenizer(d,",");
while (st1.hasMoreTokens())
{
for (j=0;j<4;j++)
60

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

{
data[i][j]=st1.nextToken();
System.out.println(data[i][j]);
}
i++;
}
System.out.println("______________");
}
}
catch (Exception e)
{
System.out.println("Eception raised" +e.toString());
}
table1=new JTable(data,colHeads);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll=new JScrollPane(table1,v,h);
con.add(scroll,BorderLayout.CENTER);
}
public static void main(String args[])
{
Table1 t=new Table1();
t.setBackground(Color.green);
t.setTitle("Display Data");
t.setSize(500,300);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Sample Output :
Enter a text file :
Java.txt
The data has 2000 tokens
The full length data can be simulated by applets

61

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Expected Input & Output:

2. Write a program that creates a user interface to perform integer divisions. The
user enters two numbers in the text fields, Num1 and Num2. The division of Num1
and Num2 is displayed in the Result field when the Divide button is clicked. If
Num1 or Num2 were not an integer, the program would throw a
NumberFormatException. If Num2 were Zero, the program would throw an
ArithmeticException Display the exception in a message dialog box.
Algorithm:
Step1: Begin
Step2: Create a class interface to perform integer divisions
62

JAVA PROGRAMMING
Science and Engineering
Step3:
Step4:
Step5:
Step6:

LAB

Department of Computer

Read two text fields for reading integer values


Implement the method to perform integer divisions
Display output.
End.

Source Code:

63

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

64

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output :
Simulated through applets

Expected Input & Output:

Questions:
1 What is the structure of the HTTP response ?
2 What is a cookie ? What is the difference between session and cookie ?
3 Which protocol will be used by browser and servlet to communicate ?
4 What is HTTP Tunneling ?
5 Whats the difference between sendRedirect and forward methods

65

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Week 10 :

66

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

1. Write a Java Program to implement the opening of a door while opening man
should present before hut and closing man should disappear.
Algorithm:
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:

Begin
Create an applet to implement opening door
Simulate opening a door while man enters a hut
Simulate closing a door while man exits a hut
Display output.
End.

Source Code:

67

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output:
Simulated through Applets
Expected Input & Output:
68

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

2. Write a Java code by using JtextField to read decimal value and converting a
decimal number into binary number then print the binary value in another
JtextField
Algorithm:
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:

Begin
Read a decimal value
Convert the decimal to binary value
Print the binary value using JTextField.
Display output.
End.

Source Code:

69

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

70

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output :
Enter a Decimal value : 10
The Binary value is 1010
The Binary value is :
This is displayed using JTextField
Expected Input & Output:

71

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. What is Applet?
2. What is JPanel?
72

JAVA PROGRAMMING
Science and Engineering
3.
4.
5.
6.

What
What
What
What

is
is
is
is

LAB

Department of Computer

Appletviewer?
Jdk?
Procedure to create applets?
Servlet?

Week 11 :
1)Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field to
display the result.
Algorithm:
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:

Begin
Create a class and initialize class members and methods.
Read input values
Implement a method to perform a logic for designing a simple calculator .
Display output.
End.

Source code:

//<applet code="Calculator.class" height="150" width="700"> </applet>


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends Applet implements ActionListener
{
JTextField t1,t2,t3;
JLabel l1,l2,l3;
JButton b1,b2,b3,b4;
JPanel p1,p2;
public void init()
{
p1=new JPanel();
73

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

p2=new JPanel();
p1.setBackground(Color.gray);
p2.setBackground(Color.gray);
setBackground(Color.lightGray);
l1=new JLabel("Enter the First number :");
p1.add(l1);
t1=new JTextField(10);
p1.add(t1);
l2=new JLabel("Enter the Second number :");
p1.add(l2);
t2=new JTextField(10);
p1.add(t2);
l3=new JLabel("Result");
p1.add(l3);
t3=new JTextField(10);
p1.add(t3);
b1=new JButton("ADD");
p2.add(b1);
b1.addActionListener(this);
b2=new JButton("SUB");
p2.add(b2);
b2.addActionListener(this);
b3=new JButton("MUL");
p2.add(b3);
b3.addActionListener(this);
b4=new JButton("DIVISION");
p2.add(b4);
b4.addActionListener(this);
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);
t1.setBackground(Color.yellow);
t2.setBackground(Color.yellow);
t3.setBackground(Color.yellow);
}
public void actionPerformed(ActionEvent ae)
{
try
{
if (ae.getSource()==b1)
{
74

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int sum=x+y;
t3.setText(" "+sum);
}
if (ae.getSource()==b2)
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int sub=x-y;
t3.setText(" "+sub);
}
if (ae.getSource()==b3)
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int mul=x*y;
t3.setText(" "+mul);
}
if (ae.getSource()==b4)
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int div=x/y;
t3.setText(" "+div);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
}
Sample Output :
Simulated using Applets
Expected Input & Output:

75

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

2) Write a Java program for handling mouse events.


Algorithm:
Step1: Begin
Step2: Create a class and initialize class members and methods.
Step3: Read input values
Step4: Implement the method to perform mouse events by using event handling
functions.
Step5: Display output.

76

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Step6: End.
Source code:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Mouseevents"width=200 height=100>
</applet>*/
public class Mouseevents extends Applet implements
MouseListener,MouseMotionListener
{
String msg="";
int x=0,y=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
x=10;
y=20;
msg="mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
x=10;
y=20;
msg="mouse entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
x=10;
y=20;
msg="mouse exited";
repaint();
}
77

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

public void mousePressed(MouseEvent me)


{
x=me.getX();
y=me.getY();
msg="down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="*";
showStatus("dragging mouse at"+x+","+y);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("moving mouse at"+me.getX()+","+me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
Sample Output :

Simulated through Graphical User Interface (Applets)

78

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Expected Input & Output:

79

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. What is the purpose of Graphics package?
2. What are Mouse Events?
3. What is purpose os MouseMotionListener ?
4. What is an Interface?
5. Why drawstring is used?
6. Describe about MouseMoved Event?

Week 12:
1. Write a java program establish a JDBC connection, create a table student with
properties name, register number, mark1,mark2, mark3. Insert the values into the
table by using the java and display the information of the students at front end.
Algorithm:
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:

Begin
Create a JDBC Connection
Create student with properties anme,marks
Insert values using JTable
Display output.
End.

Source Code:

80

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

81

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Sample Output :
Simulated using JDBC Connections,Applets and displayed at front end

Expected Input & Output:

82

JAVA PROGRAMMING
Science and Engineering

LAB

Department of Computer

Questions:
1. What is JDBC ?
2. Explain the role of Driver in JDBC
3. What is the purpose Class.forName method ?
4. What is the advantage of PreparedStatement over Statement ?
5. What is the use of CallableStatement ?
6. What does Connection pooling mean ?
7. What is RMI ?
8. What is the basic principle of RMI architecture ?
9. What are the layers of RMI Architecture ?
10. What is the role of Remote Interface in RMI ?

83

You might also like