0% found this document useful (0 votes)
5 views36 pages

JAVA LAB CSM NEWl

The document is a lab manual for a Java Programming course at AAR Mahaveer Engineering College, detailing course objectives, outcomes, and specific programming experiments. It outlines the educational objectives and outcomes for students, emphasizing analytical, technical, soft skills, and professional ethics. Additionally, it provides general laboratory instructions and a list of experiments to be conducted, along with source code examples demonstrating various Java programming concepts.

Uploaded by

anishs8544
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)
5 views36 pages

JAVA LAB CSM NEWl

The document is a lab manual for a Java Programming course at AAR Mahaveer Engineering College, detailing course objectives, outcomes, and specific programming experiments. It outlines the educational objectives and outcomes for students, emphasizing analytical, technical, soft skills, and professional ethics. Additionally, it provides general laboratory instructions and a list of experiments to be conducted, along with source code examples demonstrating various Java programming concepts.

Uploaded by

anishs8544
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/ 36

AAR MAHAVEER ENGINEERING COLLEGE(8P)

(Approved by AICTE, Affiliated to JNTU ,Hyderabad)


Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

DEPARTMENT OF COMPUTERSCIENCE ENGINEERING(AI&ML)

JAVA PROGRAMMING
LAB MANUAL
Subject Code :AM603PC

Regulation:R22/JNTUH

IIYear IISem(2024-25)
(R22A0585)
AAR MAHAVEERENGINEERING COLLEGE (8P) Affiliated to
JNTUH,Vyasapuri,(V),Bandlaguda(M)R.RDist,TS-500005

1
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

PROGRAMME EDUCATIONAL OBJECTIVES(PEOs)

PEO1–ANALYTICALSKILLS

To facilitate the graduates with the ability to visualize, gather information,


articulate, analyze, solve complex problems, and make decisions. These are essential to
address the challenges of complex and computation intensive problems increasing their
productivity.

PEO2–TECHNICALSKILLS

To facilitate the graduates with the technical skills that prepare them for immediate
employment and pursue certification providing a deeper understanding of the technology in
advanced areas of computer science and related fields, thus encouraging to pursue higher
education and research based on their interest.

PEO3 –SOFT SKILLS

To facilitate the graduates with the soft skills that include fulfilling the mission,
setting goals, showing self-confidence by communicating effectively, having a positive
attitude, get involved in team-work, being a leader, managing their career and their life.

PEO4 –PROFESSIONALETHICS

To facilitate the graduates with the knowledge of professional and ethical


responsibilities by paying attention to grooming, being conservative with style, following
dress codes, safety codes, and adapting themselves to technological advancements.

2
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

PROGRAM SPECIFIC OUTCOMES(PSOs)


After the completion of the course, B. Tech Information Technology, the graduates will have the
following Program Specific Outcomes:

1. Fundamentals and critical knowledge of the Computer System:-Able to Understand the


working principles of the computer System and its components , Apply the knowledge to
build, asses, and analyze the software and hardware aspects of it .

2. The comprehensive and Applicative knowledge of Software Development:


Comprehensive skills of Programming Languages, Software process models,
methodologies, and able to plan, develop, test, analyze, and manage the software and
hardware intensive systems in heterogeneous platforms individually or working in teams.

3. Applications of Computing Domain & Research: Able to use the professional,


managerial, interdisciplinary skill set, and domain specific tools in development processes,
identify the research gaps, and provide innovative solutions to them.

3
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

PROGRAM OUT COMES(POs)

Engineering Graduates should possess the following:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multi disciplinary environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

4
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

GENERALLABORATORYINSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before(to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record up dated up to the last session experiments and other utensils (if any)needed
in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results/output in the lab observation note
book, and get certified by the concerned faculty.
6. Al the students should be polite in laboratory and cooperative with the laboratory staff, must
maintain the discipline and decency in the.
7. Computer labs are established with sophisticated and high end branded systems, which should
be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment , misbehaviors with the staff and systems etc., will
attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
foundloiteringoutsidethelab/classwithoutpermissionduringworkinghourswillbetreated
seriously and punished appropriately.
10. StudentsshouldLOGOFF/SHUTDOWNthecomputersystembeforehe/sheleavesthelab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept
properly.

HEADOFTHE DEPARTMENT PRINCIPAL


5
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

JAVAPROGRAMMINGLAB
B. Tech. II Year II Sem

Course Objectives:

● To understand OOP principles.


● To understand the Exception Handling mechanism.
● To understand Java collection framework.
● To understand multithreaded programming.
● To understand swing controls in Java.

Course Outcomes:
● Able to write the programs for solving real world problems using Java OOP principles.
● Able to write programs using Exceptional Handling approach.
● Able to write multithreaded applications.
● Able to write GUI programs using swing controls in Java.

List of Experiments:
1. Use Eclipse or Net bean platform and acquaint yourself 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
debugstepbystepwithasmallprogramofabout10to15lineswhichcontainsatleastoneifelseconditi
on and a for loop.

2. Write a Java program to demonstrate the OOP principles.[i.e., Encapsulation, Inheritance,


Polymorphism and Abstraction]

3. Write a Java program to handle checked and unchecked exceptions. Also, demonstrate the
usage of custom exceptions in real time scenario.

4. Write a Java program on Random Access File class to perform different read and write
operations.

5. WriteaJavaprogramtodemonstratetheworkingofdifferentcollectionclasses.[Usepackage
structure to store multiple classes].

6
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

6. Write a program to synchronize the threads acting on the same object. [Consider the
example of any reservations like railway, bus, movie ticket booking, etc.]

7. Write a program to perform CRUD operations on

8. The student table in a database using JDBC.

9. 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.

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]

REFERENCEBOOKS:
1. Java for Programmers , P.J.Deitel and H. M. Deitel , 10thEditionPearsoneducation.
2. Thinking in Java, Bruce Eckel, Pearson Education.
3. Java Programming, D.S.Malikand P.S.Nair,CengageLearning.
4. Core Java, Volume1,9thedition,CayS.HorstmannandGCornell, Pearson.

7
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

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.

Source Code:

Sample_Program.java

/* Sample java program to check given number is prime or not */


//Importing packages
Import java.lang.System;
Import java.util.Scanner;
// Creating Class
Class Sample_Program{
// main method
Public static void main(Stringargs[]){
inti, count=0,n;
// creating scanner object
Scannersc= new Scanner(System.in);
// get input number from user
System.out.print("Enter Any Number : ");
n=sc.nextInt();
// logic to check prime or not
for(i=1;i<=n;i++){
if(n%i==0){
count++;
}
}
if(count==2)
System.out.println(n+" is prime");
else
System.out.println(n+" is not prime");

8
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

}
}

Output:

9
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

WEEk-2

Write a Java program to demonstrate the OOP principles. [i.e.,


Encapsulation, Inheritance, Polymorphism and Abstraction]

Source code:

/* Encapsulation:
The fields of the class are private and accessed through getter and setter methods.*/
class Person {
// private fields
private String name;
privateint age;
// constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/* Abstraction:
The displayInfo() method provides a simple interface to interact with the object.*/
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

/* Inheritance:
Employee is a subclass of Person, inheriting its properties and methods.*/
10
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

class Employee extends Person {


// private field
private double salary;
// constructor
public Employee(String name, int age, double salary) {
super(name, age);
this.salary = salary;
}
// getter and setter methods
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}

/* Polymorphism:
Overriding the displayInfo() method to provide a specific implementation for
Employee.*/
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Salary: " + salary);
}
}

public class OopPrinciplesDemo {


public static void main(String[] args) {
// Demonstrating encapsulation and abstraction
Person person = new Person("Madhu", 30);
System.out.println("Person Info:");
person.displayInfo();
System.out.println("====================");

// Demonstrating inheritance and polymorphism


Employee employee = new Employee("Naveen", 26, 50000);
System.out.println("Employee Info:");
employee.displayInfo();
}
}

11
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

Output:

12
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

Week- 3
Write a Java program to handle checked and unchecked exceptions. Also,
demonstrate the usage of custom exceptions in real time scenario.

Source Code:

ExceptionsDemo.java

importjava.io.File;
importjava.io.FileReader;
importjava.io.FileNotFoundException;

// Custom Exception
classInvalidAgeException extends Exception {
publicInvalidAgeException(String message) {
super(message);
}
}

public class ExceptionsDemo {


// Method to demonstrate custom exception
public static void register(String name, int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("User must be at least 18 years old.");
} else {
System.out.println("Registration successful for user: " + name);
}
}
public static void main(String[] args) {
//Handling Checked Exception
try {
File file = new File("myfile.txt");
// This line can throw FileNotFoundException
FileReaderfr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
//Handling Unchecked Exception
try {
int[] arr = {1, 2, 3};

13
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

// Accessing an out-of-bound index


System.out.println(arr[6]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
}
// Finally block to perform cleanup operations
finally {
System.out.println("Cleanup operations can be performed here.");
}
// Demonstrate custom exception handling
System.out.println("Demonstrating Custom Exception:");
try {
// Invalid age for registration
register("Madhu", 17);
} catch (InvalidAgeException e) {
System.out.println("Custom Exception Caught: " + e.getMessage());
}
}
}

Output:

14
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

WEEK - 4
Write a Java program on Random Access File class to perform different read and
write operations.

Source Code:

RandomAccessFileExample.java

import java.io.*;
public class RandomAccessFileExample {
public static void main(String[] args) {
try {
// Create a RandomAccessFile object with read-write mode
RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
// Write data to the file
String data1 = "Hello";
String data2 = "World";
file.writeUTF(data1);
file.writeUTF(data2);
// Move the file pointer to the beginning of the file
file.seek(0);
// Read data from the file
String readData1 = file.readUTF();
String readData2 = file.readUTF();
System.out.println("Data read from file:");
System.out.println(readData1);
System.out.println(readData2);
// Move the file pointer to the ending of the file
file.seek(file.length());
// Append new data to the file
String newData = "Java!";
file.writeUTF(newData);
// Move the file pointer to the beginning of the file
file.seek(0);
// Read data from the file again after appending
readData1 = file.readUTF();
readData2 = file.readUTF();
String readData3 = file.readUTF();
System.out.println("Data read from file after appending:");
System.out.println(readData1);

15
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

System.out.println(readData2);
System.out.println(readData3);
// Close the file
file.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}

Output:

16
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

Week -5

Aim:
Write a Java program to demonstrate the working of different collection classes. [Use
package structure to store multiple classes].

Source Code:

ListExample.java

packagecollections;
importjava.util.ArrayList;
publicclassListExample{
publicstaticvoidmain(String[]args){
ArrayList<String> list =newArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
// to display
System.out.println("List Example:");
for(String fruit : list){
System.out.println(fruit);
}
}
}

SetExample.java

packagecollections;
importjava.util.HashSet;
publicclassSetExample{
publicstaticvoidmain(String[]args){

17
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

HashSet<String> set =newHashSet<>();


set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Apple");// This won't be added since sets don't allow duplicates
// To display
System.out.println("Set Example:");
for(String fruit : set){
System.out.println(fruit);
}
}
}

MapExample.java

packagecollections;
importjava.util.HashMap;
publicclassMapExample{
publicstaticvoidmain(String[]args){
HashMap<Integer,String> map =newHashMap<>();
map.put(1,"Apple");
map.put(2,"Banana");
map.put(3,"Orange");
// To display
System.out.println("Map Example:");
for(Map.Entry<Integer,String> entry :map.entrySet()){
System.out.println(entry.getKey()+": "+entry.getValue());
}
}
}

CollectionsDemo.java

18
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

packagecollections;

publicclassCollectionsDemo{
publicstaticvoidmain(String[]args){
ListExample.main(args);
SetExample.main(args);
MapExample.main(args);
}
}

Output:

19
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

20
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

21
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

Weeek-6

class BookingSystem

private int availableSeats;

public BookingSystem(int availableSeats)

this.availableSeats = availableSeats;

public synchronized void bookSeat(int seatsRequested, String name)

if (seatsRequested <= availableSeats)

System.out.println(seatsRequested + " seat(s) booked for " + name);

availableSeats -= seatsRequested;

} else

System.out.println("Sorry, " + name + ". Not enough seats available.");

22
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

class BookingThread extends Thread

private BookingSystem bookingSystem;

private int seatsRequested;

private String name;

public BookingThread(BookingSystembookingSystem, int seatsRequested, String name)

this.bookingSystem = bookingSystem;

this.seatsRequested = seatsRequested; this.name = name; } public void run()

bookingSystem.bookSeat(seatsRequested, name);

public class Main

23
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

public static void main(String[] args)

BookingSystem bookingSystem = new BookingSystem(10); // 10 seats available


BookingThread thread1 = new BookingThread(bookingSystem, 3, "Alice"); BookingThread
thread2 = new BookingThread(bookingSystem, 4, "Bob"); BookingThread thread3 = new
BookingThread(bookingSystem, 5, "Charlie"); thread1.start();

thread2.start();

thread3.start();

24
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

WEEK-7

Aim:
Write a program to perform CRUD operations on the student table in a database using JDBC.

Source Code:

InsertData.java

importjava.sql.*;
importjava.util.Scanner;
publicclassInsertData{
publicstaticvoidmain(String[]args){
try{
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
Statement s =con.createStatement();

// To read insert data into student table


Scannersc=newScanner(System.in);
System.out.println("Inserting Data into student table : ");
System.out.println("________________________________________");
System.out.print("Enter student id : ");
intsid=sc.nextInt();
System.out.print("Enter student name : ");
Stringsname=sc.next();
System.out.print("Enter student address : ");
Stringsaddr=sc.next();
// to execute insert query
s.execute("insert into student values("+sid+",'"+sname+"','"+saddr+"')");
System.out.println("Data inserted successfully into student table");

s.close();
con.close();
}catch(SQLException err){
System.out.println("ERROR: "+ err);
}catch(Exception err){
System.out.println("ERROR: "+ err);

25
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

}
}
}

UpdateData.java

importjava.sql.*;
importjava.util.Scanner;
publicclassUpdateData{
publicstaticvoidmain(String[]args){
try{
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
Statement s =con.createStatement();

// To read insert data into student table


Scannersc=newScanner(System.in);
System.out.println("Update Data in student table : ");
System.out.println("________________________________________");
System.out.print("Enter student id : ");
intsid=sc.nextInt();
System.out.print("Enter student name : ");
Stringsname=sc.next();
System.out.print("Enter student address : ");
Stringsaddr=sc.next();
// to execute update query
s.execute("update student set s_name='"+sname+"',s_address = '"+saddr+"' where s_id =
"+sid);
System.out.println("Data updated successfully");
s.close();
con.close();
}catch(SQLException err){
System.out.println("ERROR: "+ err);
}catch(Exception err){
System.out.println("ERROR: "+ err);
}
}

26
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

DeleteData.java

importjava.sql.*;
importjava.util.Scanner;
publicclassDeleteData{
publicstaticvoidmain(String[]args){
try{
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
Statement s =con.createStatement();

// To read insert data into student table


Scannersc=newScanner(System.in);
System.out.println("Delete Data from student table : ");
System.out.println("________________________________________");
System.out.print("Enter student id : ");
intsid=sc.nextInt();
// to execute delete query
s.execute("delete from student where s_id = "+sid);
System.out.println("Data deleted successfully");
s.close();
con.close();
}catch(SQLException err){
System.out.println("ERROR: "+ err);
}catch(Exception err){
System.out.println("ERROR: "+ err);
}
}
}

DisplayData.java

27
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

importjava.sql.*;
importjava.util.Scanner;
publicclassDisplayData{
publicstaticvoidmain(String[]args){
try{
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
Statement s =con.createStatement();

// To display the data from the student table


ResultSetrs=s.executeQuery("select * from student");
if(rs!=null){
System.out.println("SID \t STU_NAME \t ADDRESS");
System.out.println("________________________________________");
while(rs.next())
{
System.out.println(rs.getString(1)+" \t "+rs.getString(2)+" \t "+rs.getString(3));
System.out.println("________________________________________");
}
s.close();
con.close();
}
}catch(SQLException err){
System.out.println("ERROR: "+ err);
}catch(Exception err){
System.out.println("ERROR: "+ err);
}

}
}

Output:

28
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

29
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

30
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

Week-8

Aim:
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:

MyCalculator.java

/* Program to create a Simple Calculator */


importjava.awt.*;
importjava.awt.event.*;
publicclassMyCalculatorextendsFrameimplementsActionListener{
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator(){
lbl1=newLabel("Number 1: ");
lbl1.setBounds(50,100,100,30);

tf1=newTextField();
tf1.setBounds(160,100,100,30);

lbl2=newLabel("Number 2: ");
lbl2.setBounds(50,170,100,30);

tf2=newTextField();
tf2.setBounds(160,170,100,30);

btn1=newButton("+");
btn1.setBounds(50,250,40,40);

btn2=newButton("-");
btn2.setBounds(120,250,40,40);

31
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

btn3=newButton("*");
btn3.setBounds(190,250,40,40);

btn4=newButton("/");
btn4.setBounds(260,250,40,40);

lbl3=newLabel("Result : ");
lbl3.setBounds(50,320,100,30);

tf3=newTextField();
tf3.setBounds(160,320,100,30);

btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);

add(lbl1);add(lbl2);add(lbl3);
add(tf1);add(tf2);add(tf3);
add(btn1);add(btn2);add(btn3);add(btn4);

setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);

publicvoidactionPerformed(ActionEventae){

num1 =Double.parseDouble(tf1.getText());
num2 =Double.parseDouble(tf2.getText());

if(ae.getSource()== btn1)
{
result= num1 + num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource()== btn2)
{
result= num1 - num2;
tf3.setText(String.valueOf(result));

32
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

}
if(ae.getSource()== btn3)
{
result= num1 * num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource()== btn4)
{
result= num1 / num2;
tf3.setText(String.valueOf(result));
}
}

publicstaticvoidmain(Stringargs[]){
MyCalculatorcalc=newMyCalculator();
}
}

Output:

33
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

34
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

WEEK-9

Aim:
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:

MouseEventPerformer.java

importjavax.swing.*;
importjava.awt.*;
importjavax.swing.event.*;
importjava.awt.event.*;
classMouseEventPerformerextendsJFrameimplementsMouseListener
{
JLabel l1;
publicMouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(newFlowLayout(FlowLayout.CENTER));
l1 =newJLabel();
Font f =newFont("Verdana",Font.BOLD,20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
add(l1);
addMouseListener(this);
setVisible(true);
}
publicvoidmouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
publicvoidmouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
publicvoidmouseReleased(MouseEvent m)

35
AAR MAHAVEER ENGINEERING COLLEGE(8P)
(Approved by AICTE, Affiliated to JNTU ,Hyderabad)
Vysapuri,Bandlaguda,Post:Keshavagiri,Hyderabad-500005

{
l1.setText("Mouse Released");
}
publicvoidmousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
publicvoidmouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
publicstaticvoidmain(String[]args){
MouseEventPerformermep=newMouseEventPerformer();
}
}

Output:

36

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy