0% found this document useful (0 votes)
11 views39 pages

Java Programming Lab Syllabus and Projects

The document outlines a syllabus for a Java Programming Lab course, detailing various programming assignments and projects for students to complete using Java and IDEs like Eclipse or NetBeans. It includes tasks such as creating a simple calculator, developing applets, implementing multi-threading, and managing data structures like linked lists. Each assignment provides specific instructions and example code to guide students in their learning process.

Uploaded by

siriichandana27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views39 pages

Java Programming Lab Syllabus and Projects

The document outlines a syllabus for a Java Programming Lab course, detailing various programming assignments and projects for students to complete using Java and IDEs like Eclipse or NetBeans. It includes tasks such as creating a simple calculator, developing applets, implementing multi-threading, and managing data structures like linked lists. Each assignment provides specific instructions and example code to guide students in their learning process.

Uploaded by

siriichandana27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link].

com

1. Syllabus
CS408PC: JAVA PROGRAMMING LAB

[Link]. II Year II Sem. LTPC


0 021
1. Use Eclipse or Net bean platform and acquaint with the various menus. Create a test project, add a test class,
and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like
renaming variables, methods, and classes. Try debug step by step with a small program of about 10 to 15
lines which contains at least one if else condition and a for loop.
2. 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. Handle any possible exceptions like
divided by zero.
3. a) Develop an applet in Java that displays a simple message.
b) Develop an applet in Java that receives an integer in one text field, and computes its factorial Value and
returns it in another text field, when the button named “Compute” is clicked.
4. Write a Java 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 Num 2 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 Number
Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception. Display the
exception in a message dialog box.
5. Write a Java program that implements a multi-thread application that has three threads. First thread
generates random integer every 1 second and if the value is even, second thread computes the square of the
number and prints. If the value is odd, the third thread will print the value of cube of the number.
6. Write a Java program for the following:
Create a doubly linked list of elements.
Delete a given element from the above list.
Display the contents of the list after deletion.
7. Write a Java program that simulates a traffic light. The program lets the user select one of three lights: red,
yellow, or green with radio buttons. On selecting a button, an appropriate message with “Stop” or “Ready”
or “Go” should appear above the buttons in selected color. Initially, there is no message shown.
8. Write a Java program to create an abstract class named Shape that contains two integers and an empty
method named print Area (). Provide three classes named Rectangle, Triangle, and Circle such that each one
of the classes extends the class Shape. Each one of the classes contains only the method print Area () that
prints the area of the given shape.
9. Suppose that a table named [Link] 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 Labels in Grid Layout.
10. Write a Java program that handles all mouse events and shows the event name at the center of the window
when a mouse event is fired (Use Adapter classes).
11. Write a Java program that loads names and phone numbers from a text file where the data is organized as
one line per record and each field in a record are separated by a tab (\t). It takes a name or phone number as
input and prints the corresponding other value from the hash table (hint: use hash tables).
12. Write a Java program that correctly implements the producer – consumer problem using the concept of
interthread communication.
13. Write a Java program to list all the files in a directory including the files present in all its subdirectories.
[Link]

PROGRAMS
Week 1.

Aim: Use Eclipse or Net bean platform and acquaint with the various menus. Create a test project, add a test class,
and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like renaming
variables, methods, and classes. Try debug step by step with a small program of about 10 to 15 lines which contains
at least one if else condition and a for loop.

Solution:

 Step 1 - Install JDK in the computer.


 Step 2 - Set the path in the Environment Variables from Advanced Setting of computer
 Step 3 - Download Eclipse from Eclipse website
 Step 4 - Install the Eclipse (follow the screen to install eclipse)
[Link]

Select the sultable version based on your OS.

Then download get starts.


[Link]

Double click on the Eclipse Application.

Click on Run in the Security Warning box.

Then, the installation process begins.


[Link]

Click on Eclipse IDE for Java Developers.


[Link]

Click on Install button.

Click on Accept Now.


[Link]

Then the Eclipse installation begins.

Click on Accept
[Link]

Click on Select All and Accept Selected.

After completing, click on Launch to start the Eclipse IDE.


[Link]
[Link]

CREATING PROJECT AND CLASSES IN ECLIPSE IDE

Browse the Workspace for storing the java project and click on Launch.

Select "Create a new Java project".

Type the project name and click on Finish.


[Link]

Now, create the class in src directory from Package Explorer window.
[Link]

Type the class name and click on Finish.

Type the java code.


[Link]

Click on Play button to run or execute the java code.


[Link]

Week 2:

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. Handle any possible exceptions like divided by zero.

Source Code:
import [Link].*;
import [Link].*;
import [Link].*;

/*
* <applet code="Calculator" width=500 height=500></applet>
* */

public class Calculator extends Applet implements ActionListener


{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(10,89,90);
setBackground(k);
t1=new TextField(50);
GridLayout gl=new GridLayout(6,3);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
mod=new Button("%");
clear=new Button("Clear");
EQ=new Button("=");
[Link](this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link]

[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str=[Link]();
char ch=[Link](0);

if ( [Link](ch))
[Link]([Link]()+str);
else
if([Link]("+"))
{
v1=[Link]([Link]());
OP='+';
[Link]("");
}
else if([Link]("-"))
{
v1=[Link]([Link]()); OP='-';
[Link]("");
}
else if([Link]("*"))
{
v1=[Link]([Link]());
OP='*';
[Link]("");
}
else if([Link]("/"))
{
v1=[Link]([Link]());
OP='/';
[Link]("");
}
else if([Link]("%")){
v1=[Link]([Link]());
OP='%';
[Link]("");
}

if([Link]("=")){
v2=[Link]([Link]());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
[Link](""+result);
}
if([Link]("Clear"))
{
[Link]("");
}
}
}
[Link]

Output:
[Link]

Week 3:

a) Develop an applet in Java that displays a simple message.


b) Develop an applet in Java that receives an integer in one text field, and computes its factorial Value and
returns it in another text field, when the button named “Compute” is clicked.

Source code for question a:

// Import the packages to access the classes and methods in awt and applet classes.
import [Link].*;
import [Link].*;

/* <applet code="Applet1" width=200 height=300></applet>*/

public class AppletExample extends Applet


{
// Paint method to display the message.
public void paint(Graphics g)
{
[Link]("Hello World!",20,20);
}
}

Output:
[Link]

Source code for question b:


import [Link].*;
import [Link].*;
import [Link];

/*<applet code="[Link]" height=300 width=300></applet>*/

public class Factorial extends Applet implements ActionListener{


Label l1,l2;
TextField t1,t2;
Button b1;
public void init(){
l1=new Label("Enter any integer value: ");
add(l1);
t1=new TextField(5);
add(t1);
b1=new Button("Calculate");
add(b1);
[Link](this);
l2=new Label("Factorial of given integer number is ");
add(l2);
t2=new TextField(10);
add(t2);
}
public void actionPerformed(ActionEvent e){
if([Link]()==b1){
int fact=fact([Link]([Link]()));
[Link]([Link](fact));
}
}
int fact(int f) {
int s=0; if(f==0)
return 1;
else
return f*fact(f-1);
}
}

Output:
[Link]

Week 4:

Write a Java 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 Num 2 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 Number Format Exception. If
Num2 were Zero, the program would throw an Arithmetic Exception. Display the exception in a message dialog box.

Source code:

import [Link].*;
import [Link].*;
import [Link].*;

/*<applet code="DivisionExample"width=230 height=250></applet>*/

public class DivisionExample extends Applet implements ActionListener {


String msg;
TextField num1, num2, res;
Label l1, l2, l3;
Button div;

public void init() {


l1 = new Label("Dividend");
l2 = new Label("Divisor");
l3 = new Label("Result");
num1 = new TextField(10);
num2 = new TextField(10);
res = new TextField(10);
div = new Button("Click");
[Link](this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}

public void actionPerformed(ActionEvent ae) {


String arg = [Link]();
int num1 = 0, num2 = 0;
if ([Link]("Click")) {
if ([Link]().isEmpty() | [Link]().isEmpty())
{
msg = "Enter the valid numbers!";
repaint();
} else {
try {
num1 = [Link]([Link]());
num2 = [Link]([Link]());

int num3 = num1 / num2;

[Link]([Link](num3));
msg = "Operation Succesfull!!!";
repaint();
} catch (NumberFormatException ex) {
[Link](ex);
[Link]("");
msg = "NumberFormatException - Non-numeric";
[Link]

repaint();
} catch (ArithmeticException e) {
[Link]("Can't be divided by Zero" + e);
[Link]("");
msg = "Can't be divided by Zero";
repaint();
}
}
}
}

public void paint(Graphics g) {


[Link](msg, 30, 70);
}
}
Output:
[Link]
[Link]

Week 5:
Write a Java program that implements a multi-thread application that has three threads. First thread generates random
integer every 1 second and if the value is even, second thread computes the square of the number and prints. If the
value is odd, the third thread will print the value of cube of the number.

Source code:

import [Link];

class RandomNumberThread extends Thread {


public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = [Link](100);
[Link]("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
SquareThread sThread = new SquareThread(randomInteger);
[Link]();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
[Link]();
}
try {
[Link](1000);
}
catch (InterruptedException ex) {
[Link](ex);
}
}
}
}
class SquareThread extends Thread {
int number;

SquareThread(int randomNumbern) {
number = randomNumbern;
}

public void run() {


[Link]("Square of " + number + " = " + (number * number));
}
}
class CubeThread extends Thread {
int number;

CubeThread(int randomNumber) {
number = randomNumber;
}

public void run() {


[Link]("Cube of " + number + " = " + number * number *
number);
}
}
public class MultiThreadingTest {
public static void main(String args[]) {
RandomNumberThread rnThread = new RandomNumberThread();
[Link]();
}
}
[Link]

Output:
[Link]

Week6:

6. Write a Java program for the following:


Create a doubly linked list of elements
Delete a given element from the above list.
Display the contents of the list after deletion.

public class DoubleLinkedList {

class Node {
int data;
Node previous;
Node next;

public Node(int data) {


[Link] = data;
}
}

Node head, tail = null;

public void addNode(int data) {


Node newNode = new Node(data);

if (head == null) {
head = tail = newNode;
[Link] = null;
[Link] = null;
} else {
[Link] = newNode;
[Link] = tail;
tail = newNode;
[Link] = null;
}
}
public void display() {
Node current = head;
if (head == null) {
[Link]("List is empty");
return;
}
[Link]("Nodes of doubly linked list: ");
while (current != null) {

[Link]([Link] + " ");


current = [Link];
}
}
public static void main(String[] args) {

DoubleLinkedList dList = new DoubleLinkedList();


[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);

[Link]();
}
}
[Link]

Output:
[Link]

Week 7:

Write a Java program that simulates a traffic light. The program lets the user select one of three lights: red,
yellow, or green with radio buttons. On selecting a button, an appropriate message with “Stop” or “Ready”
or “Go” should appear above the buttons in selected color. Initially, there is no message shown.

Source code:
import [Link];
import [Link].*;
import [Link].*;

/*
* <applet code = "TrafficLightsExample" width = 1000 height = 500>
* </applet>
* */

public class TrafficLightsExample extends Applet implements ItemListener{

CheckboxGroup grp = new CheckboxGroup();


Checkbox redLight, yellowLight, greenLight;
Label msg;
public void init(){
redLight = new Checkbox("Red", grp, false);
yellowLight = new Checkbox("Yellow", grp, false);
greenLight = new Checkbox("Green", grp, false);
msg = new Label("");

[Link](this);
[Link](this);
[Link](this);

add(redLight);
add(yellowLight);
add(greenLight);
add(msg);
[Link](new Font("Serif", [Link], 20));
}
public void itemStateChanged(ItemEvent ie) {
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

if([Link]() == true) {
[Link]([Link]);
[Link]([Link]);
[Link]("STOP");
}
else if([Link]() == true) {
[Link]([Link]);
[Link]([Link]);
[Link]("READY");
}
else{
[Link]([Link]);
[Link]([Link]);
[Link]("GO");
}
}
}
[Link]

Output:
[Link]

Week 8:

Write a Java program to create an abstract class named Shape that contains two integers and an empty
method named print Area (). Provide three classes named Rectangle, Triangle, and Circle such that each
one of the classes extends the class Shape. Each one of the classes contains only the method print Area ()
that prints the area of the given shape.

Source code:

import [Link].*;

abstract class Shape {


int length, breadth, radius;

Scanner input = new Scanner([Link]);

abstract void printArea();

class Rectangle extends Shape {


void printArea() {
[Link]("*** Finding the Area of Rectangle ***");
[Link]("Enter length and breadth: ");
length = [Link]();
breadth = [Link]();
[Link]("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea() {
[Link]("\n*** Finding the Area of Triangle ***");
[Link]("Enter Base And Height: ");
length = [Link]();
breadth = [Link]();
[Link]("The area of Triangle is: " + (length * breadth)/2);
}
}
class Cricle extends Shape {
void printArea() {
[Link]("\n*** Finding the Area of Cricle ***");
[Link]("Enter Radius: ");
radius = [Link]();
[Link]("The area of Cricle is: " + 3.14f * radius * radius);
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Rectangle rec = new Rectangle();
[Link]();

Triangle tri = new Triangle();


[Link]();

Cricle cri = new Cricle();


[Link]();
}
}
[Link]

Output:
[Link]

Week 9:

Suppose that a table named [Link] 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 Labels in Grid Layout.

Source code:

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

class A extends JFrame {


public A() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try {
FileInputStream fin = new
FileInputStream("C:\\Users\\User\\eclipse-workspace\\LabManual\\src\\[Link]");
Scanner sc = new Scanner(fin).useDelimiter(",");
String[] arrayList;
String a;
while ([Link]()) {
a = [Link]();
arrayList = [Link](",");
for (String i : arrayList) {
add(new JLabel(i));
}
}
} catch (Exception ex) {
}
setDefaultLookAndFeelDecorated(true);
pack();
setVisible(true);
}
}

public class TableTest {

public static void main(String[] args) {


A a = new A();
}
}
[Link]

Output:
[Link]

Week 10:

Write a Java program that handles all mouse events and shows the event name at the center of the window
when a mouse event is fired (Use Adapter classes).

Source code:
import [Link].*;
import [Link].*;
import [Link].*;

/*<applet code="MouseDemo" width=300 height=300>


</applet>*/
public class MouseDemo extends Applet implements MouseListener, MouseMotionListener {
int mx = 0;
int my = 0;
String msg = "";

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me) {


mx = 20;
my = 40;
msg = "Mouse Clicked";
repaint();
}

public void mousePressed(MouseEvent me) {


mx = 30;
my = 60;
msg = "Mouse Pressed";
repaint();
}

public void mouseReleased(MouseEvent me) {


mx = 30;
my = 60;
msg = "Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent me) {


mx = 40;
my = 80;
msg = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent me) {


mx = 40;
my = 80;
msg = "Mouse Exited";
repaint();
}

public void mouseDragged(MouseEvent me) {


mx = [Link]();
my = [Link]();
showStatus("Currently mouse dragged" + mx + " " + my);
[Link]

repaint();
}

public void mouseMoved(MouseEvent me) {


mx = [Link]();
my = [Link]();
showStatus("Currently mouse is at" + mx + " " + my);
repaint();
}

public void paint(Graphics g) {


[Link]("Handling Mouse Events", 30, 20);
[Link](msg, 60, 40);
}
}

Output:
[Link]

Week 11:

Write a java program that loads names and phone numbers from a text file where the data is organized as
one line per record and each field in a record are separated by a tab (\t).it takes a name or phone number as
input and prints the corresponding other value from the hash table(hint: use hash tables)

Source code:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class HashTab {


public static void main(String[] args) {
HashTab prog11 = new HashTab();
Hashtable<String, String> hashData = [Link]("[Link]");
[Link]("File data into Hashtable:\n" + hashData);
[Link](hashData, "raja");
[Link](hashData, "123");
[Link](hashData, "----");
}

private void printTheData(Hashtable<String, String> hashData, String input) {


String output = null;
if (hashData != null) {
Set<String> keys = [Link]();
if ([Link](input)) {
output = [Link](input);
} else {
Iterator<String> iterator = [Link]();
while ([Link]()) {
String key = [Link]();
String value = [Link](key);
if ([Link](input)) {
output = key;
break;
}
}
}
}
[Link]("Input given:" + input);
if (output != null) {
[Link]("Data found in HashTable:" + output);
} else {
[Link]("Data not found in HashTable");
}
}

private Hashtable<String, String> readFromFile(String fileName) {


Hashtable<String, String> hashData = new Hashtable<String, String>();
try {
File f = new File("D:\\java\\" + fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
while ((line = [Link]()) != null) {
[Link]

String[] details = [Link]("\t");


[Link](details[0], details[1]);
}
} catch (FileNotFoundException e) {
[Link]();
} catch (IOException e) {
[Link]();
}
return hashData;
}
}

Output:
[Link]

Week – 12
Write a Java program that correctly implements the producer – consumer problem using the concept of
interthread communication.

Source Code:
class ItemQueue {
int item;
boolean valueSet = false;

synchronized int getItem()

{
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
[Link]("Consummed:" + item);
valueSet = false;
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
notify();
return item;
}

synchronized void putItem(int item) {


while (valueSet)
try {
wait();
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
[Link] = item;
valueSet = true;
[Link]("Produced: " + item);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
notify();
}
}

class Producer implements Runnable{


ItemQueue itemQueue;
Producer(ItemQueue itemQueue){
[Link] = itemQueue;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
[Link](i++);
}
}
}
[Link]

class Consumer implements Runnable{

ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
[Link] = itemQueue;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
[Link]();
}
}
}

class ProducerConsumer{
public static void main(String args[]) {
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);

}
}

Output:
[Link]

Week – 13

Write a Java program to list all the files in a directory including the files present in all its subdirectories.

Source Code:

import [Link];
import [Link].*;

public class ListingFiles {

public static void main(String[] args) {

String path = null;


Scanner read = new Scanner([Link]);
[Link]("Enter the root directory name: ");
path = [Link]() + ":\\";
File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
[Link]("Root directory does not exists!");
printLine();
} else {
String ch = "y";
while ([Link]("y")) {
printFiles(path);
[Link]("Do you want to open any sub-directory
(Y/N): ");
ch = [Link]().toLowerCase();
if ([Link]("y")) {
[Link]("Enter the sub-directory name: ");
path = path + "\\\\" + [Link]();
File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
[Link]("The sub-directory does not
exists!");
printLine();
int lastIndex = [Link]("\\");
path = [Link](0, lastIndex);
}
}
}
}
[Link]("***** Program Closed *****");
}
public static void printFiles(String path) {
[Link]("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList) {
if ([Link]())
[Link]("- " + [Link]());
else
[Link]("> " + [Link]());
}
}
public static void printLine() {
[Link]("----------------------------------------");
}
}
[Link]

Output:

You might also like