0% found this document useful (0 votes)
92 views42 pages

Java Programming Lab

The document is a lab manual for the Java Programming Lab at KPR College of Arts Science and Research for the academic year 2025-2026. It outlines the program's educational objectives, outcomes, specific outcomes, general laboratory instructions, software and hardware requirements, course objectives, and a series of programming exercises. The manual includes detailed coding examples and procedures for various Java programming tasks, emphasizing hands-on training and ethical coding practices.
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)
92 views42 pages

Java Programming Lab

The document is a lab manual for the Java Programming Lab at KPR College of Arts Science and Research for the academic year 2025-2026. It outlines the program's educational objectives, outcomes, specific outcomes, general laboratory instructions, software and hardware requirements, course objectives, and a series of programming exercises. The manual includes detailed coding examples and procedures for various Java programming tasks, emphasizing hands-on training and ethical coding practices.
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
You are on page 1/ 42

Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

SCHOOL OF COMPUTING SCIENCE


DEPARTMENT OF COMPUTER TECHNOLOGY

LAB MANUAL
JAVA PROGRAMMING LAB
BACHELOR OF COMPUTER TECHNOLOGY
ACADEMIC YEAR: 2025-2026
ODD SEMESTER

Prepared by:
Dr. D. Maheshwari
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Programme Educational Objectives (PEOs)


The B.Sc. Computer Technology programme describe accomplishments that
graduates are expected to attain within five to seven years after graduation
PEO1 To enhance the broad knowledge in core area related to computer
software and hardware technologies
PEO2 To develop and acquire in-depth knowledge in software design and
implementation to meet the requirement of corporate
PEO3 To facilitate the graduates to pursuing professional careers or
researcher or entrepreneurs in computing technologies
PEO4 To enrich the learners to develop communication, professional
skills and to inculcate team spirit
PEO5 To stimulate the graduates to build awareness on social
responsibility ,ethical practices and human values in-built in the
discipline
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Program Outcomes (POs)


On successful completion of the B.Sc. Computer Technology
PO1 Disciplinary knowledge: Capable to apply the knowledge of mathematics,
algorithmic principles and computing fundamentals in the modelling and
design of computer based systems of varying complexity
PO2 Scientific reasoning/ Problem analysis: Ability to critically analyse,
categorizes, formulate and solve the problems that emerges in the field of
computer science.
PO3 Problem solving: Able to provide software solutions for complex scientific
and business related problems or processes that meet the specified needs
with appropriate consideration for the public health and safety and the
cultural, societal and environmental considerations..
PO4 Environment and sustainability: Understand the impact of software
solutions in environmental and societal context and strive for sustainable
development
PO5 Modern tool usage: Use contemporary techniques, skills and tools
necessary for integrated solutions
PO6 Ethics: Function effectively with social, cultural and ethical responsibility
as an individual or as a team member with positive
attitude
PO7 Cooperation / Team Work: Function effectively as member or leader on
multidisciplinary teams to accomplish a common objective
PO8 Communication Skills: An ability to communicate effectively with diverse
types of audience and also able to prepare and present technical documents
to different groups.
PO9 Self-directed and Life-long Learning: Graduates will recognize the need
for self-motivation to engage in lifelong learning to be in par with changing
technology
P10 Enhance the research culture and uphold the scientific integrity and
objectivity
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Program Specific Outcomes (PSOs)


After the successful completion of B.Sc. Computer Technology programme the
students are expected to
PSO1 Ability to apply core area knowledge in computing system in
appropriate to the discipline
PSO2 Acquired knowledge in software and hardware skills and
implementation challenges in varying techniques
PSO3 Ability to engage in life-long learning and adopt fast changing
technology to prepare for professional development
PSO4 Improve to exhibit professionally or team leader or entrepreneur
PSO5 Realize technological advances impart society and the social, ethical
difficulties of computer technology and their practice.
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

GENERAL LABORATORY INSTRUCTIONS


1. Students should report to the laboratory at least 5 minutes before (to the starting
time).
2. Students are advised to plan the tasks well before starting and to come prepared
with details of the program to the lab.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the required details for a program (Problem
statement, Aim, Algorithm, Procedure, Program and Expected Output) filled in for
the lab session.
b. Proper Dress code and Identity card.
4. Students are advised to sign in the laboratory login register mentioning TIME-IN,
and to occupy the computer system allotted to them by the faculty.
5. Record your laboratory observations in the lab observation book, and get the
relevant faculty to certify your work.
6. Students should maintain discipline and decency in the laboratory by being polite
and cooperative with the staff.
7. A computer lab is equipped with sophisticated and high-end branded systems,
which should be utilized properly.
8. It is mandatory for students and faculty to keep their mobile phones turned off
during lab sessions. Staff and system misbehaviors, misuse of equipment, etc., will
be punished severely.
9. In the case of an urgent need to leave the lab / class, students must ask faculty
permission; loitering outside without permission during working hours will be taken
seriously and punished accordingly.
10. LOG OFF/SHUT DOWN the computer before leaving the lab after completing
all aspects of the task (experiment). It is his/her responsibility to maintain the system
/ seat properly.
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

SOFTWARE AND HARDWARE REQUIREMENTS

HARDWARE:

Intel based Desktop PC

SOFTWARE:

System Software: Flavor of any Windows

Application Software’s: NetBeans IDE and JDK 1.7


Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

33P: JAVA PROGRAMMING LAB


B. Sc. Computer Technology
Course Objectives:
The main objectives of this course are to:
 The main objective of JAVA Programming Lab is to provide the students a
strong foundation on programming concepts and its applications through
hands-on training.
 To practice the Basic concepts, Branching and Looping Statements and
Strings in C programming
 To implement and gain knowledge in Arrays, functions, Structures,
Pointers and File handling
Course Outcomes:
1. Understand the basic concepts of Java Programming with emphasis on ethics
and principles of professional coding
2. Demonstrate the creation of objects, classes and methods and the concepts of
constructor, methods overloading, Arrays, branching and looping
3. Create data files and Design a page using AWT controls and Mouse Events
in Java programming Implement the concepts of code reusability and
debugging.
4. Develop applications using Strings, Interfaces and Packages and applets
5. Construct Java programs using Multithreaded Programming and Exception
Handling
Programs:
Program 1
Write a Java Applications to extract a portion of a character string and print
the extracted string.
Program 2
Write a Java Program to implement the concept of multiple inheritance using
Interfaces.
Program 3
Write a Java Program to create an Exception called pay-out-of-bounds and
throw the exception
Program 4
Write a Java Program to implement the concept of multithreading with the use
of any three multiplication tables and assign three different priorities to them.
Program 5
Write a Java Program to draw several shapes in the created windows
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Program 6
Write a Java Program to create a frame with four text fields name, street, city
and pin code with suitable tables. Also add a button called my details. When
the button is clicked its corresponding values are to be appeared in the text
fields.
Program 7
Write a Java Program to demonstrate the Multiple Selection List-box.
Program 8
Write a Java Program to create a frame with three text fields for name, age
and qualification and a text field for multiple line for address
Program 9
Write a Java Program to create Menu Bars and pull down menus.
Program 10
Write a Java Program to create frames which respond to the mouse clicks. For
each events with mouse
Program 11
Write a Java Program to draw circle, square, ellipse and rectangle at the
mouse click positions.
Program 12
Write a Java Program which open an existing file and append text to that file.
Text Book (s)
1 Programming with Java – A Primer - E. Balagurusamy, 3rd Edition, TMH
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

INDEX
S. No. Date Name of the Program Page No. Signature

1 String Extraction

2 Multiple Inheritance

3 Own Exception

4 Multithread

5 Shapes

6 My Details Using Frame

7 Multiple Selection List Box

8 Text Field For Multiple Line

9 Menu Creation

10 Mouse Events using Frame

11 Shapes at Mouse Click Positions

12 Program to append text to the file


Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 1
String Extraction
Date :

Aim
To Write a Java Applications to extract a portion of a character string and print the
extracted string.
Procedure
Step 1: Start the program
Step 2: Create a class stringextract
Step 3: Initialize and Assign string object s1
Step 4: Use charAt() function to extract the single character for the given
index value
Step 5: Use getChars() function to extract the one or more character for the
given started index value, ended index value and store in to the array
object buf[]
Step 6: Use ToCharArray() fuction to convert String object into Character
Array.
Step 7: Print the output
Step 9: Stop the process

Coding
/* Java Applications to extract a portion of a character string and print the
extracted string. */
import java.io.*;
import java.lang.*;
public class stringextract
{
public static void main(String args[])
{
String s1= "Computer Science with Data Analytics";
System.out.println("Single Character Extraction");
char ch;
ch="Computer".charAt(3);
System.out.println ("The Index 3rd character=: "+ch);
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

System.out.println("Extract More than One Character");


int start = 5;
int end=16;
char buf[]=new char [end-start];
s1.getChars(start, end, buf, 0);
System.out.println(buf);
System.out.println("String object into Character Array");
char[]c = "Hello".toCharArray();
System.out.println(c);
}
}

OUTPUT

Single Character Extraction


The Index 3rd character=: p
Extract More than One Character
ter Science
String object into Character Array
Hello
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 2
Multiple Inheritance
Date :

Aim
To Write a Java Program to implement the concept of multiple inheritance
using Interfaces
Procedure
Step 1: Start the process
Step 2: Create an interface area with a member variable pi=3.14
Step 3: Create an interface area1 with a method float compute(float x, float
y)
Step 4: Define a class rectangle that implements the interfaces area and
area1
Step 5: Call the method compute to calculate the area of rectangle using
rectarea=x*y
Step 6: Return the value of rectarea
Step 7: Define a class circle that implements the interfaces area and area1
Step 8: Call the method compute to calculate the area of circle using
cirarea=pi*x*x
Step 9: Return the value of cirarea
Step 10: Create a class interdemo and declare objects for the two classes
Step 11: Display the results
Step 12: Stop the Process

Coding
/* Java Program to implement the concept of multiple inheritance using
Interfaces*/
import java.io.*;
import java.lang.*;
public interface area
{
static final float pi=3.14f;
}
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

public interface area1


{
float compute(float x, float y);
}
public class rectangle implements area,area1
{
public float compute(float x, float y)
{
float rectarea=x*y;
return(rectarea);
}
}
public class cir implements area,area1
{
public float compute(float x, float y)
{
float cirarea= pi*x*x;
return(cirarea);
}
}
public class interdemo
{
public static void main(String[] args)
{
rectangle r=new rectangle();
cir c=new cir();
System.out.println("\n Multiple inheritance using interface");
System.out.println("Area of rectangle="+r.compute(10f,20f));
System.out.println("Area of circle="+c.compute(10f,10f));
}
}

OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 3
Own Exception
Date :

Aim
To Write a Java Program to create an Exception called pay- out-of-bounds
and throw the exception
Procedure
Step 1: Start the program
Step 2: Create a class myexp that extends the in built class Exception
Step 3: Define the constructors for the class
Step 4: Create a class mainexp
Step 5: Declare and initialize the variables inside the main function
Step 6: Get the input values using readLine() method within the try block
Step 7: If salpermonth>10000.1 then throw an exception “pay out of bounds”
Step 8 : Otherwise display “correct salary paid for each month”
Step 9: Stop the process.
Coding
/* Java Program to create an Exception called pay-out-of-bounds and throw the
exception*/
import java.io.*;
import java.lang.*;
import java.io.DataInputStream;
public class myexp extends Exception
{
public myexp() { }
public myexp(String msg)
{
super(msg);
}
}
class mainexp1
{
public static void main(String args[])
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

{
float salary=0.0f;
int month=0;
float salpermon=0.0f;
DataInputStream in=new DataInputStream(System.in);
try
{
System.out.println("Enter the string:");
salary=Float.valueOf(in.readLine());
System.out.println("Enter the month");
month=Integer.parseInt(in.readLine());
}
catch(Exception e) {}
try
{
salpermon=salary/month;
if(salpermon>10000.1)
{
throw new myexp("Pay out bound");
}
else
{
System.out.println("Correct salary paid for each month");
System.out.println("_______");
}
}
catch(myexp e)
{
System.out.println("Caught my exception");
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

System.out.println(e.getMessage());
e.getMessage();
}
}
}
OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 4
Date :
Multithreading
Aim
To Write a Java Program to implement the concept of multithreading with the
use of any three multiplication tables and assign three different priorities to them
Procedure
Step1 : Start the process
Step 2: Create a class aThread that extends the inbuilt class Thread
Step 3: Define a method run() to display the multiplication table 7
Step 4: Create a class bThread that extends the inbuilt class Thread
Step 5: Define a method run() to display the multiplication table 13
Step6 : Create a class cThread that extends the inbuilt class Thread
Step 7: Define a method run() to display the multiplication table 13
Step8 : Create a class mThread in which main method is defined
Step9 : Declare objects for the three classes
Step10: Set Priority values for the three threads as follows:
c.setPriority(Thread.MAX_PRIORITY);
b.setPriority(Thread.MIN_PRIORITY);
a.setPriority(Thread.MIN_PRIORITY);
Step11: Call the start() method to execute different Threads
Step12: Stop the process.
Coding
/*Java Program to implement the concept of multithreading with the use of any three
multiplication tables and assign three different priorities to them */
import java.io.*;
import java.lang.*;
public class aThread extends Thread {
public void run()
{

System.out.println("Thread A started");
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

for(int i=1;i<5;i++)
System.out.println(i+"*"+"7="+(i*7));
System.out.println("Thread A exit");
}
}
public class bThread extends Thread {
public void run()
{
System.out.println("Thread B started");
for(int i=1;i<=5;i++)
System.out.println(i+"*"+"13="+(i*13));
System.out.println("Thread B exit");
}
}
public class cThread extends Thread {
public void run()
{
System.out.println("Thread C started");
for(int i=1;i<=5;i++)
System.out.println(i+"*"+"13="+(i+13));
System.out.println("Thread C exit");
}
}
public class mThread {
public static void main(String args[])
{
aThread a=new aThread();
bThread b=new bThread();
cThread c=new cThread();
c.setPriority(Thread.MAX_PRIORITY);
b.setPriority(Thread.MIN_PRIORITY);
a.setPriority(Thread.MIN_PRIORITY);
c.start();
b.start();
a.start();
}
}
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 5
Shapes
Date :
Aim
To Write a Java Program to draw several shapes in the created windows
Procedure
Step 1: Start the process
Step 2: import the packages required
Step 3: Define a class Shapes that extends the inbuilt class Applet
Step 4: Define a method void Paint()
Step 5: Name the applet window as “My shapes”
Step 6: Set the color of square as black using setColor() method.
Step 7: Draw a Square using the function fillRect(80,80,80,80)
Step 8: Set the color of Circle as blue
Step 9: Draw a Circle using the function fillOval(80,150,80,150)
Step 10: Set the Color of Oval as green
Step 11: Draw an Oval using the function fillRect(160,150,50,50)
Step 12: Set the Color of rectangle as orange
Step 13: Draw a Rectangle using the function fillRect(420,200,220,230)
Step 14: Display the result in applet window
Step15: Stop the Process

Coding:
// Java Program to draw several shapes in the created windows
import java.applet.*;
import java.awt.*;
public class shapes extends Applet
{
public static void Paint(Graphics g)
{
String str1 = "My shapes";
g.setColor(Color.red);
g.drawString(str1,20,20);
g.setColor(Color.black);
g.fillRect(80,80,80,80);
g.setColor(Color.blue);
g.fillOval(80,150,80,150);
g.setColor(Color.green);
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

g.fillOval(160,150,50,50);
g.setColor(Color.orange);
g.fillRect(420,200,220,230);
}
}

OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 6
My Details using Frames
Date :

Aim
To Write a Java Program to create a frame with four text fields name, street,
city and pin code with suitable tables. Also add a button called my details. When the
button is clicked its corresponding values are to be appeared in the text fields.
Procedure
Step 1: Start the Process
Step 2: Create a class framedemo that extends the inbuilt class Frame
Step 3: Declare and initialize the controls to design the frame.
Step 4: Create object for the class Frame goto step 4
 Using constructor mframe()
 Create an object for 4 labels
 Using add() method all the following to applet window
 Labels,Textarea,Textfield,Button,Layout
 Use actionlistner to perform the event
Step 5: Check the condition get source equal to button object set the following
text to the
Textfield and text area,object name,age,qualification and address will
display in
multiple line using the method append()
Step 6: Use paint() method to display the details again and again
Step 7: Stop the program

Coding
/*Java Program to create a frame with four text fields name, street, city and pin code
with suitable tables. Also add a button called my details. When the button is clicked
its corresponding values are to be appeared in the text fields */
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class framedemo extends Frame
{
Button b1;
Label L1=new Label("Name");
Label L2=new Label("Street");
Label L3=new Label("City");
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Label L4=new Label("Pincode");


TextField Name=new TextField(15);
TextField City=new TextField(15);
TextField Street=new TextField(15);
TextField Pincode=new TextField(15);
FlowLayout f=new FlowLayout();
framedemo()
{
Label L=new Label("output of mydetails:",Label.CENTER);
add(L);
add(L1);add(name);
add(L2);add(city);
add(L3);add(street);
add(L4);add(pincode);
setLayout(f);
b1=new Button("My details");
b1.addActionListener(new AL());
add(b1);
}
public class AL implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
name.setText("Poornima");
city.setText("Coimbatore");
street.setText("Kumaran Nagar");
pincode.setText("641118");
}
}
public void actionPerformed(ActionEvent e)
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
public void paint(Graphics g)
{
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

g.drawString("My Details",50,20);
}
public static void main(String[] args)
{
framedemo fd=new framedemo();
fd.setBounds(1,1,300,300);
fd.setVisible(true);
}
}
OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 7
Date :
Multiple Selection List-box
Aim
To Write a Java Program to demonstrate the Multiple Selection List-box.
Procedure
Step 1: Start the process
Step 2: Create a classname such as MS list
Step 3: Using unit() method to initialize all components
 Create object for list,textfield,button
 Add textbox in the applet window with to items
 Add textfield in the applet using add() method
 Add button in the applet window add actionlistner event,goto
step 4
Step 4: Create string object outstr
 Check the condition current event equal to button onject
 Initialize list box select items to 3
 Using loop increment I value one by one upto length of 8
 Concatenation outstr[i]=concatenation outstr[i]+s[i];
Step 5: Display the selected items in the textfield
Step 6: Stop the process

Coding
// Java Program to demonstrate the Multiple Selection List-box
import java.applet.Applet;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MSList extends Applet implements ActionListener
{
List ls;
TextField tf;
Button b1;
public void init()
{
tf=new TextField(60);
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

add(tf);
ls=new List(10,true);
ls.add("coimbatore");
ls.add("ooty");
ls.add("chennai");
ls.add("salem");
ls.add("tirupur");
ls.add("erode");
ls.add("tirchy");
ls.add("sakthi");
ls.add("madras");
ls.add("bombay");
add(ls);
b1=new Button("show selected");
b1.addActionListener(this);
add(b1);
}
String[]s;
public void actionPerformed(ActionEvent ae)
{
String outstr=new String("your selected");
if(ae.getSource()==b1)
{
s=ls.getSelectedItems();
for(int i=0;i<s.length;i++)
{
outstr+=" "+s[i];
}
tf.setText(outstr);
}
}
}
OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 8
Date :
Text Field For Multiple Line
Aim
To Write a Java Program to create a frame with three text fields for name, age and
qualification and a text field for multiple line for address
Procedure
Step 1: Start the Process
Step 2: Create a class framedemo that extends the inbuilt class Frame
Step 3: Declare and initialize the controls to design the frame.
Step 4: Create object for the class Frame goto step 4
I. Using constructor mframe()
II. Create an object for 4 labels
III. Using add() method all the following to applet window
IV. Labels, Textarea, Textfield, Button, Layout
V. Use actionlistner to perform the event

Step 5: Check the condition get source equal to button object set the following text
to the Textfield and text area,object name,age,qualification and address will
display in multiple line using the method append()
Step 6: Use paint() method to display the details again and again
Step 7: Stop the program
Coding
import java.awt.*;
import java.awt.event.*;
public class framedemo extends Frame
{
Button b1;
Label l1=new Label("Name :");
Label l2=new Label("Age :");
Label l3=new Label("Qualification :");
Label l4=new Label ("Address :");
TextField Name= new TextField(15);
TextField Age=new TextField(15);
TextField Qualification=new TextField(15);
TextField Address=new TextField(50);
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

FlowLayout f= new FlowLayout();

framedemo()
{
Label l= new Label("Output of My Details",Label.CENTER);
add(l);
add(l1);add(Name);
add(l2);add(Age);
add(l3);add(Qualification);
add(l4);add(Address);
setLayout(f);
b1=new Button("My Details");
b1.addActionListener(new AL());
add(b1);
addWindowListener(new WH());
}
class WH extends WindowAdapter
{
public void windowClosing(ActionEvent e)
{ System.exit(0);
} }
public class AL implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==b1)
{
Name.setText("Alex");
Age.setText("25");
Qualification.setText("BE - CSE");
Address.setText("11 A, Kumaran Nagar , Pincode- 641148");
} } }
public void paint(Graphics g)
{
g.drawString("Mydetails",50,20);
}
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

public static void main(String args[])


{
framedemo fd= new framedemo();
fd.setBounds(1,1,300,300);
fd.setVisible(true);
}
}

OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 9
Menu Creation
Date :
Aim
To Write a Java Program to create Menu Bars and pull down menus.
Procedure
Step 1: Start the program
Step 2: Create a Class MenuCreate
Step 3: Create a Frame object f , MenuBar Object mb, Menu object M1 with
the name File
Step 4: Create Menu object submenu with the name Sub Menu
Step 5: Create MenuItem object i1, i2, i3,i4 and i5 with name as New, Open,
Save, Print and Exit
Step 6: Add the MenuItem to Menu
Step 7: Add Submenu as i4 and i5
Step 8 : Add all Menu details to MenuBar
Step 9: Set MenuBar, Size. Layout , visibility to the Frame
Step 10: Using main method to call the constructor MenuCreate()
Step 11 : Stop the program

Coding
// Create Menu Bars and pull down menus
import java.awt.*;
class MenuCreate
{
MenuCreate()
{
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu m1=new Menu("File");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("New");
MenuItem i2=new MenuItem("Open");
MenuItem i3=new MenuItem("Save");
MenuItem i4=new MenuItem("Print");
MenuItem i5=new MenuItem("Exit");
m1.add(i1);
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

m1.add(i2);
m1.add(i3);
submenu.add(i4);
submenu.add(i5);
m1.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuCreate();
}
}

OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 10
Mouse Click Event
Date :

Aim
To Write a Java Program to create frames which respond to the mouse clicks.
For each events with mouse.
Procedure
Step 1: Start the process
Step 2: Create a main class such as MLExample
Step 3: Create a object for class event example goto Step 5 MLExample to
receive the arguments value and display the value using window adapter
event
Step 4: Use Actionlistener event to the following event and display the
message
 Mouse clicked
 Mouse entered
 Mouse pressed
 Mouse exit
 Mouse released
Step 5: Use the paint() method to display the mouse event again and again
Step6: Use paint() method to display the mouse event
Step 7: Display the result
Step 8: Stop the process

Coding
/*Java Program to create frames which respond to the mouse clicks. For each
events with mouse */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MLExample extends Frame implements MouseListener{
String strEvent=" ";
MLExample(String title)
{
super(title);
addWindowListener(new MyWindowAdapter(this));
addMouseListener(this);
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
strEvent="Mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent e)
{
strEvent="Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e)
{
strEvent="Mouse Released";
repaint();
}
public void mouseEntered(MouseEvent e)
{
strEvent="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e)
{
strEvent="Mouse Exited";
repaint();
}
public void paint(Graphics g)
{
g.drawString(strEvent,50,50);
}
public static void main(String[] args) {
MLExample mw=new MLExample ("window with mouse event example");
}
}
class MyWindowAdapter extends WindowAdapter
{
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

MLExample mw=null;
MyWindowAdapter(MLExample mw)
{
this.mw=mw;
}
public void windowClosing(WindowEvent we)
{
mw.setVisible(false);
}
}
OUTPUT
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 11
Shapes in Mouse Click Position
Date :
Aim
To Write a Java Program to draw circle, square, ellipse and rectangle at the
mouse click positions
Procedure
Step 1: Start the process
Step 2: Create a class bclick
Step 3: initialize the variable x,y,z as using unit() method
Step 4: Use mouselistner,increment the value of a depending on the number
of time mouse is clicked
Step 5: Get the x and y value from the method get x() and get y()
Step 6: Use paint() method click, it remainder of c divide by 4 is equal to
 Draw circle
 Draw square
 Draw ellipse
 Draw rectangle
Step 7: Display all shapes using mouse click position
Step 8: Stop the process

Coding
/* Java Program to draw circle, square, ellipse and rectangle at the mouse click
positions */
import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;

public class Bclick extends Applet {


int x = 0;
int y = 0;
int c = 0;
public void init() {
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

c++;
x= me.getX();
y= me.getY();
repaint();
}
});
}
public void paint(Graphics g)
{
if(c%4==1)
g.drawOval(x,y,100,100);
else if(c%4==2)
g.drawRect(x,y,50,50);
else if(c%4==3)
g.drawRect(x,y,25,50);
else if(c%4==0)
g.drawOval(x,y,50,80);
}

}
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

Exercise No: 12
Append Text to the File
Date:

Aim
To Write a Java Program which open an existing file and append text to that file.
Procedure
Step 1: Start the process
Step 2: Create a class raf
Step 3: Create an object for the RandomAccessFile in read/write mode with
the text file (city.txt)
Step 4: Find the length of the file using rfile seek=(rfile.length)
Step 5: Append the text in rfile using mode rfile writeBytes(“Mumbai”)
Step 6: Close the file
Step 7: open the text file city.txt to check the appended data.
Step 8: if data is appended at the end of the file then close the file.
Step 9: Stop the process.

Coding
// Java Program which open an existing file and append text to that file //
import java.io.*;
public class raf
{
public static void main(String args[])
{
RandomAccessFile rFile;
try
{
rFile=new RandomAccessFile("City.txt","rw");
rFile.seek(rFile.length());
rFile.writeBytes("Mumbai\n");
rFile.close();
Java Programming Lab (33P)

KPR College of Arts Science and Research


(Affiliated to Bharathiar University, Coimbatore)
Avinashi Road, Arasur, Coimbatore – 641 407

}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
OUTPUT

You might also like