JAVA PROGRAMMING LAB MANUAL (AIML)
JAVA PROGRAMMING LAB MANUAL (AIML)
Aim:1
Use eclipse or Netbean 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
Output:
Related Content :
Aim:2
Write a Java program to demonstrate the OOP principles. [i.e.,
Encapsulation, Inheritance, Polymorphism and Abstraction]
Source Code:
OopPrinciplesDemo.java
/* Encapsulation:
The fields of the class are private and accessed through
getter and setter methods.*/
class Person
{
// private fields
private String name;
private int 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.*/
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);
}
}
Output:
Aim:3
Source Code:
ExceptionsDemo.java
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
// Custom Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
Output:
Aim:
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
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
// Custom Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
Output:
Aim: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);
file // Move the file pointer to the beginning of the
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);
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:
Aim:5
Write a Java program to demonstrate the working of different collection
classes. [Use package structure to store multiple classes].
Source Code:
ListExample.java
package collections;
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
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
package collections;
import java.util.HashSet;
public class SetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
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
package collections;
import java.util.HashMap;
public class MapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
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
package collections;
Aim: 10
Write a Java program to synchronize the threads acting on the same object. Consider the example
of a railway reservation system where multiple users try to book tickets simultaneously.
Source Code
RailwayReservation.java
import java.util.*;
class TicketBooking {
private int availableSeats = 2;
p1.start();
p2.start();
p3.start();
}
}
Output:
Source Code:
InsertData.java
import java.sql.*;
import java.util.Scanner;
public class InsertData {
public static void main(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();
System.out.println(" ")
;
System.out.print("Enter student id : ");
int sid = sc.nextInt();
System.out.print("Enter student name : ");
String sname = sc.next();
System.out.print("Enter student address : ");
String saddr = 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);
}
}
}
UpdateData.java
import java.sql.*;
import java.util.Scanner;
public class UpdateData {
public static void main(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();
System.out.println(" ")
;
System.out.print("Enter student id : ");
int sid = sc.nextInt();
System.out.print("Enter student name : ");
String sname = sc.next();
System.out.print("Enter student address : ");
String saddr = 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);
}
}
}
DeleteData.java
import java.sql.*;
import java.util.Scanner;
public class DeleteData {
public static void main(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();
System.out.println(" ")
;
System.out.print("Enter student id : ");
int sid = 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
import java.sql.*;
import java.util.Scanner;
public class DisplayData {
public static void main(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();
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:
Aim: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.
Source Code:
MyCalculator.java
JOptionPane.showMessageDialog(this,"Divided by zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}
Output:
Aim: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]
Source Code:
MouseEventPerformer.java
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MouseEventPerformer extends JFrame implements
MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout(FlowLayout.CENTER));
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
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");
}
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}
Output: