Java Lab Manual Aiml
Java Lab Manual Aiml
LAB MANUAL
Prepared By
Name: G.JYOTHSNA
Verified By
LAB MANUAL-INDEX
S.No Contents
1 Vision,Mission,PEOs,POs,PSOs&Cos
2 Institution Academic Calendar
3 Department Academic Calendar
4 Syllabus Copy
5 Index
6 Programs
7 Model Paper For LabInternal-1
Model Paper For LabInternal-2
Sri Indu College of Engineering & Technology
Sheriguda(V),R.R.Dist
INSTITUTION VISION
INSTITUTION MISSION
PRINCIPAL
Sri Indu College of Engineering & Technology
Sheriguda(V),R.R.Dist
DEPARTMENTVISION
DEPARTMENTMISSION
DM1Toofferhighqualityeducationinthecomputingfieldsbyprovidinganenvironmentwhere the
knowledge is gained and applied to participate in research, for both students andFaculty.
DM2To develop the problem solving skills in the students to be ready to deal with cutting
edgeTechnologiesof theindustry
DM3To make the students and faculty excel in their professional fields by inculcating
theCommunication Of skills, leadership skills, team building skills with the
organizationvariousco-curricularprogrammers
DM4To provide the students with theoretical and applied knowledge, and adopt an
education Approach that promotes lifelong learning and ethical growth.
HOD
Sri Indu College of Engineering& Technology
Sheriguda(V),R.R.Dist
DepartmentofComputerScience&Engineering(AIML&CS)
PROGRAMOUTCOMES(POs)&PROGRAMSPECIFICOUTCOMES (PSOs)
PROGRAMOUTCOMES(POs)
PO Description
EngineeringKnowledge: Tobeable to apply knowledge f computing,mathematics,
PO 1 Science and Engineering appropriatetothe discipline
ProblemAnalysis:To beableidentify,formulate
PO 2 &analyzeaproblem,andascertainanddefinethecomputing requirements appropriatetoits
solution.
Design & Development Solutions: To be able to design, implement, and evaluate
PO 3 acomputer‐basedsystem,process, component,orprogram tomeetdesired needs.
Investigationofcomplexproblems: Tobeabletoidentifyandanalyzeuserneeds
PO 4 andconsiderthem inthe selection, creation,evaluation and administrationof
Computer‐basedsystems forprovidingvalidsolutionstocomplexproblems.
Modern Tool Usage: To possess skills for creating and in using
PO 5 contemporarytechniques,skills, and toolsnecessaryforcomputingpractice.
Engineering&Society:Toapplyconceptualknowledgerelevanttoprofessionalengineeringp
PO 6 racticesinsocietal,health,safety,legalandculturalissuesandtheirconsequences
Environment&Sustainability: To beableto
PO 7 analyzethelocalandglobalimpactofcomputing on individuals, organizations, and
society and work towards sustainable development.
Ethics:Tounderstandcontemporaryprofessional,ethical,legal,securityandsocialissue
PO 8 sand responsibilities.
Individual & Team work: To Be able to function effectively as an individual and
PO 9 onteamsto accomplish a common goal.
Communication: To communicate precisely and effectively both in oral and
PO 10 writtenformwith a rangeof audiences.
DepartmentofComputerScience&Engineering(AIML)
SUBCODE: R22CSI2228
C22L3.1 Write programs for solving real world programs using collection frame work.
C22L3.2 Write programs using abstract classes and multithreaded programs.
C22L3.3 Able to write GUI programs using swing controls in java.
Faculty
TABLE OF CONTENTS
S.No Topics
3 Equipment
4 Configuration
5 Software
6 Ambience
7 Academic Calendar
8 Syllabus
9 Timetable
11 Lab schedule
13 Viva questions
14 Additional programs
1. DIMENSIONS OF THE LAB
Area of the lab in Sqmts : 66 Sqm
Open Office
6. AMBIENCE
Printers : 01
Projector : 00
Computer Tables : 30
Student Chairs : 30
Charts : 02
Photo Frames : 01
Switch/Hub : 03
White Boards : 01
A/C s : 01
LAB MANUAL
SYLLABUS
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 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 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. Write a Java program to demonstrate the working of different collection classes. [Use package
structure to store multiple classes].
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 the student table in a database using JDBC.
8. 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.
9. 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]
REFERENCE BOOKS:
1. Java for Programmers, P. J. Deitel and H. M. Deitel, 10th Edition Pearson education.
2. Thinking in Java, Bruce Eckel, Pearson Education.
3. Java Programming, D. S. Malik and P. S. Nair, Cengage Learning.
4. Core Java, Volume 1, 9th edition, Cay S. Horstmann and G Cornell, Pearson.
GENERAL LABORATORY INSTRUCTION
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.
a. Laboratory observation notes with all the details (Problem statement, Aim, Program, Expected
Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any) needed in
the lab.
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. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
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 found
loitering outside the lab / class without permission during working hours will be treated seriously and
punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept properly.
HOD PRINCIPAL
CORE LAB MANUAL
EXPERIMENT-1
Use Eclipse or Net bean platform and acquaint with the various menus. Create a test project, and
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.
Program:
int n = sc.nextInt();
int c = 0;
if (n % i == 0)
c++;
}}
if (c == 2) {
} else {
}
}
Output:
VIVA QUESTIONS:
2.Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation, Inheritance,
Polymorphism and Abstraction].
PROGRAM
Inheritance, polymorphism, abstraction, encapsulation,over riding, over loading all implemented in
single program.
Program:
Program:
class One {
System.out.println("One");
//inheritance
System.out.println("Two");
return x+y;
//Overload
return x+y;
//encapsulation example
class EncapTest {
return name;
}
name = newName;
//abstraction
System.out.println("\nbike is Running..");
class MainClass {
a.display();
Two b=new Two();
b.display();
System.out.println(b.add(4,2));
System.out.println(b.add(5.,2.)); //polymorphism
encap.setName("Sandeep's");
test.run();
}
Output:
One
Two
7.0
\
Name : Sandeep's
bike is Running.
Experiment-3
3.Write a Java program to handle checked and unchecked exceptions also demonstrate
the usage of custom exception in real time scenario
// Custom exception class
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// BankAccount class representing a bank account
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Method to withdraw money, handling InsufficientBalanceException
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount);
} else {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
}
// Method to simulate an unchecked exception (ArithmeticException)
public void divideByZero() {
int result = 10 / 0; // This will cause an ArithmeticException
}
}
// Main class to demonstrate exception handling
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Create a bank account with an initial balance
BankAccount account = new BankAccount(1000);
// Handle checked exception (InsufficientBalanceException)
try {
account.withdraw(1500);
} catch (InsufficientBalanceException e) {
System.out.println("Caught checked exception: " + e.getMessage());
}
// Handle unchecked exception (ArithmeticException)
try {
account.divideByZero();
} catch (ArithmeticException e) {
System.out.println("Caught unchecked exception: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}
3.Write a Java program to handle checked and unchecked exceptions also demonstrate
the usage of custom exception in real time scenario
// Custom exception class
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// BankAccount class representing a bank account
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Method to withdraw money, handling InsufficientBalanceException
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount);
} else {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
}
// Method to simulate an unchecked exception (ArithmeticException)
public void divideByZero() {
int result = 10 / 0; // This will cause an ArithmeticException
}
}
// Main class to demonstrate exception handling
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Create a bank account with an initial balance
BankAccount account = new BankAccount(1000);
// Handle checked exception (InsufficientBalanceException)
try {
account.withdraw(1500);
} catch (InsufficientBalanceException e) {
System.out.println("Caught checked exception: " + e.getMessage());
}
// Handle unchecked exception (ArithmeticException)
try {
account.divideByZero();
} catch (ArithmeticException e) {
System.out.println("Caught unchecked exception: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}
Experiment-3
3.Write a Java program to handle checked and unchecked exceptions also demonstrate
the usage of custom exception in real time scenario
// Custom exception class
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// BankAccount class representing a bank account
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Method to withdraw money, handling InsufficientBalanceException
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount);
} else {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
}
// Method to simulate an unchecked exception (ArithmeticException)
public void divideByZero() {
int result = 10 / 0; // This will cause an ArithmeticException
}
}
// Main class to demonstrate exception handling
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Create a bank account with an initial balance
BankAccount account = new BankAccount(1000);
// Handle checked exception (InsufficientBalanceException)
try {
account.withdraw(1500);
} catch (InsufficientBalanceException e) {
System.out.println("Caught checked exception: " + e.getMessage());
}
// Handle unchecked exception (ArithmeticException)
try {
account.divideByZero();
} catch (ArithmeticException e) {
System.out.println("Caught unchecked exception: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}
Output:
1. What are the types of Exceptions in Java?
2. How do you implement user-defined exception handling in Java?
3. What are the dissimilarities between the two types of Java exceptions?
4. What are the different keywords in Exception handling in Java?
5. What is the difference between throws and throw keywords in Java?
6. How to differentiate between the finally, final, and finalize keywords?
Experiment-4
4.Write a Java program on random access file class to perform different read and write
Program:
import java.io.File;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
public static void main(String[] args) {
// Specify the file path
String filePath = "randomAccessFileExample.txt";
// Perform write operations
writeData(filePath, "Hello, World!");
// Perform read operations
readData(filePath);
}
private static void writeData(String filePath, String data) {
try (RandomAccessFile file = new RandomAccessFile(filePath, "rw")) {
// Move the file pointer to the end of the file
file.seek(file.length());
// Write data to the file
file.writeUTF(data);
System.out.println("Data written to file: " + data);
// Move the file pointer to a specific position
file.seek(0);
// Write more data at the beginning of the file
file.writeUTF("New data");
System.out.println("New data written to file.");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readData(String filePath) {
try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
// Read data from the file
String data = file.readUTF();
System.out.println("Read data from file: " + data);
// Move the file pointer to a specific position
file.seek(0);
// Read more data from the beginning of the file
String newData = file.readUTF();
System.out.println("Read new data from file: " + newData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
VIVA QUESTIONS:
1. What is Exception Handling?
2. What is difference between Checked Exception and Unchecked Exception?
3. What is the base class for Error and Exception?
4. What is finally block?
5.Can finally block be used without catch?
6.Is there any case when finally will not be executed?
7.What is exception propagation?
8.What is nested class? 9.What is nested interface?
10.Can an Interface have a class?
Experiment-5
5. write a Java program to demonstrate the working of different collection classes (usage
package structure to store multiple classes
// Create a package named "collectionsdemo"
package collectionsdemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// Class to represent a Product
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product{name='" + name + "', price=" + price + '}';
}
}
// Class to demonstrate different collection classes
public class CollectionsDemo {
public static void main(String[] args) {
// Create a list of products
List<Product> productList = new ArrayList<>();
productList.add(new Product("Laptop", 999.99));
productList.add(new Product("Phone", 499.99));
// Create a map of products with unique IDs
Map<Integer, Product> productMap = new HashMap<>();
productMap.put(1, new Product("Tablet", 299.99));
productMap.put(2, new Product("Headphones", 79.99));
// Display products from the list
Output:
VIVA QUESTIONS:
1. What is multithreading?
2. What is thread?
3. What is the difference between preemptive scheduling and time slicing?
4. What does join() method?
5. Is it possible to start a thread twice?
6. Can we call the run() method instead of start()?
7. What about the daemon threads?
8. What is shutdown hook?
9. When should we interrupt a thread?
Experiment-6
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)
class MovieTicketBooking {
private int availableSeats;
public MovieTicketBooking(int totalSeats) {
this.availableSeats = totalSeats;
}
// Synchronized method to book tickets
public synchronized void bookTickets(String customerName, int numSeats) {
if (numSeats > 0 && numSeats <= availableSeats) {
System.out.println(customerName + " booked " + numSeats + " tickets.");
availableSeats -= numSeats;
System.out.println("Remaining seats: " + availableSeats);
} else {
System.out.println(customerName + " couldn't book tickets. Not enough seats
available.");
}
}
}
class CustomerThread extends Thread {
private MovieTicketBooking booking;
private String customerName;
private int numSeats;
public CustomerThread(MovieTicketBooking booking, String customerName, int numSeats) {
this.booking = booking;
this.customerName = customerName;
this.numSeats = numSeats;
}
@Override
public void run() {
booking.bookTickets(customerName, numSeats);
}
}
public class MovieTicketBookingDemo {
public static void main(String[] args) {
// Create a MovieTicketBooking object with 10 total seats
MovieTicketBooking ticketBooking = new MovieTicketBooking(10);
// Create multiple threads representing customers trying to book tickets
Thread customer1 = new CustomerThread(ticketBooking, "Customer 1", 3);
Thread customer2 = new CustomerThread(ticketBooking, "Customer 2", 5);
Thread customer3 = new CustomerThread(ticketBooking, "Customer 3", 2);
// Start the threads
customer1.start();
customer2.start();
customer3.start();
}
}
VIVA QUESTIONS: 1. What is a Linked list?
2. Can you represent a Linked list graphically?
3.How many pointers are required to implement a simple Linked list?
4. How many types of Linked lists are there?
5. How to delete a node from linked list?
6.How to reverse a singly linked list?
7. Compare Linked lists and Dynamic Arrays
8. What is a Circular Linked list?
Experiment-7
7.write a Java program to demonstrate the working of different collection classes (usage
package structure to store multiple classes
import java.sql.*;
public class StudentCRUD {
// JDBC URL, username, and password of MySQL server
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database_name";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
// JDBC variables for opening, closing, and managing connection
private static Connection connection;
public static void main(String[] args) {
try {
// Open a connection
connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
// Perform CRUD operations
createStudent("John Doe", 20);
readStudents();
updateStudent(1, "Updated Name", 25);
readStudents();
deleteStudent(1);
readStudents();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// Close the connection
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Create operation
private static void createStudent(String name, int age) throws SQLException {
String insertQuery = "INSERT INTO student (name, age) VALUES (?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.executeUpdate();
System.out.println("Student created successfully.");
}
}
// Read operation
private static void readStudents() throws SQLException {
String selectQuery = "SELECT * FROM student";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectQuery)) {
System.out.println("Student Table:");
System.out.println("ID\tName\tAge");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println(id + "\t" + name + "\t" + age);
}
System.out.println();
}
}
// Update operation
private static void updateStudent(int id, String newName, int newAge) throws SQLException {
String updateQuery = "UPDATE student SET name=?, age=? WHERE id=?";
Output:
EXPERIMENT-8
Write a Java Program that works as simple calculator .Use grid layout to arrange buttons for
thedigits and for the +,-,*,% operations .Add text field to display the results, Handle any
AIM : 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.
THEORY: GridLayout is one of the Layout managers.A layout manager automatically arranges your
controls with in a window by using some type of algorithm.Grid Layout lays out component in a two
dimensional grid. When you instantiate a GridLayout,you define the number of rows and columns
Program:
importjavax.swing.*;
importjavax.swing.event.*;
importjava.awt.*;
importjava.awt.event.*;
class A extends JFrame implements ActionListener {
publicJButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16;
publicJTextField tf1;
publicJPanel p;
public String v = "";
public String v1 = "0";
public String op = "";
public A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
p = new JPanel(new FlowLayout());
tf1 = new JTextField(10);
p.add(tf1);
add(p);
setLayout(new GridLayout(0, 3));
b1 = new JButton("1");
b1.addActionListener(this);
add(b1);
b2 = new JButton("2");
b2.addActionListener(this);
add(b2);
b3 = new JButton("3");
b3.addActionListener(this);
add(b3);
b4 = new JButton("4");
b4.addActionListener(this);
add(b4);
b5 = new JButton("5");
b5.addActionListener(this);
add(b5);
b6 = new JButton("6");
b6.addActionListener(this);
add(b6);
b7 = new JButton("7");
b7.addActionListener(this);
add(b7);
b8 = new JButton("8");
b8.addActionListener(this);
add(b8);
b9 = new JButton("9");
b9.addActionListener(this);
add(b9);
b10 = new JButton("0");
b10.addActionListener(this);
add(b10);
b11 = new JButton("+");
b11.addActionListener(this);
add(b11);
b12 = new JButton("-");
b12.addActionListener(this);
add(b12);
b13 = new JButton("*");
b13.addActionListener(this);
add(b13);
b14 = new JButton("/");
b14.addActionListener(this);
add(b14);
b16 = new JButton("%");
b16.addActionListener(this);
add(b16);
b15 = new JButton("=");
b15.addActionListener(this);
add(b15);
setVisible(true);
}
public void actionPerformed(ActionEventae) {
String b = ae.getActionCommand();
switch (b) {
case "1": {
v = v + "1";
tf1.setText(v);
}
break;
case "2": {
v = v + "2";
tf1.setText(v);
}
break;
case "3": {
v = v + "3";
tf1.setText(v);
}
break;
case "4": {
v = v + "4";
tf1.setText(v);
}
break;
case "5": {
v = v + "5";
tf1.setText(v);
}
break;
case "6": {
v = v + "6";
tf1.setText(v);
}
break;
case "7": {
v = v + "7";
tf1.setText(v);
}
break;
case "8": {
v = v + "8";
tf1.setText(v);
}
break;
case "9": {
v = v + "9";
tf1.setText(v);
}
break;
case "0": {
v = v + "0";
tf1.setText(v);
}
break;
case "+": {
op = "+";
v1 = tf1.getText();
v = "";
}
break;
case "-": {
op = "-";
v1 = tf1.getText();
v = "";
}
break;
case "*": {
op = "*";
v1 = tf1.getText();
v = "";
}
break;
case "/": {
op = "/";
v1 = tf1.getText();
v = "";
}
break;
case "%": {
op = "%";
v1 = tf1.getText();
v = "";
}
break;
case "=": {
switch (op) {
case "+": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) + Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "-": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) - Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "*": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) * Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "/": {
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) / Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
case "%": {
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) % Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
}
}
break;
}
}
}
public class Calc {
public static void main(String[] args) {
A a = new A();
}
}
Output:
VIVA QUESTIONS:
Theory:To handle mouse events you must implement the MouseListener and the
MouseMotionListenerinterfaces.These two interfaces contain methods that receive and process the
various types of mouse events.
Program:
importjavax.swing.*;
importjava.awt.*;
importjavax.swing.event.*;
importjava.awt.event.*;
class A extends JFrame implements MouseListener {
JLabel l1;
public A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new GridBagLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m) {
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m) {
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m) {
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m) {
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m) {
l1.setText("Mouse Clicked");
}
}
public class Mevents {
public static void main(String[] args) {
A a = new A();
}
}
Output:
VIVA QUESTIONS
9. An event source is
Program:
public class PrimeExample{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){
break;
}
}
if(flag==0) { System.out.println(n+" is prime number"); }
}
}
}
Output:
3 is prime number
Program:
class FibonacciExample1{
public static void main(String args[]) {
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);
for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}
Output:
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34
Output:
Factorial of 5 is:120
Program:
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;
temp=n;
while(n>0){
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
Output:
Palindrome number
Program:
public class PrintAsciiValueExample1
{
public static void main(String[] args)
{
char ch1 = 'a';
char ch2 = 'b';
int asciivalue1 = ch1;
int asciivalue2 = ch2;
System.out.println("The ASCII value of " + ch1 + " is: " + asciivalue1);
System.out.println("The ASCII value of " + ch2 + " is: " + asciivalue2);
}
}
Output:
Program:
public class RightTrianglePattern
{
public static void main(String args[])
{
int i, j, row=6;
for(i=0; i<row; i++)
{
for(j=0; j<=i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
Program:
{
int i, num = 10, sum = 0;
sum = sum + i;
Output:
Program:
int number=100;
if (i%2==0)
}
}
Output:
Program:
import java.util.Scanner;
import java.lang.Math;
temp=n;
while(temp>0)
{
temp = temp/10;
digits++;
}
temp = n;
while(temp>0)
{
last = temp % 10;
int num;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the limit: ");
num=sc.nextInt();
System.out.println("Armstrong Number up to "+ num + " are: ");
Output:
Enter the limit: 999
Armstrong Number up to 999 are:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407