0% found this document useful (0 votes)
7 views

JAVA PROGRAMMING LAB MANUAL (AIML)

The document is a Java Programming Lab Manual for the II B.Tech II Semester in Artificial Intelligence and Machine Learning for the academic year 2024-2025. It includes various lab exercises focusing on Java programming concepts such as OOP principles, exception handling, file operations, collections, thread synchronization, and CRUD operations using JDBC. Each exercise provides source code examples and aims to help students practice and understand the respective Java programming topics.

Uploaded by

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

JAVA PROGRAMMING LAB MANUAL (AIML)

The document is a Java Programming Lab Manual for the II B.Tech II Semester in Artificial Intelligence and Machine Learning for the academic year 2024-2025. It includes various lab exercises focusing on Java programming concepts such as OOP principles, exception handling, file operations, collections, thread synchronization, and CRUD operations using JDBC. Each exercise provides source code examples and aims to help students practice and understand the respective Java programming topics.

Uploaded by

geeth407762
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING.

II B.TECH II SEM AIML(R22)

JAVA PROGRAMMING LAB MANUAL

ACADEMIC YEAR 2024-2025


Java Programming [ Lab Programs
]

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

/* 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(String args[]) {
int i,count=0,n;
// creating scanner object
Scanner sc=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");
}

Output:

Related Content :

Java Programming Lab Programs


2) Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation,
Inheritance, Polymorphism and Abstraction] View Solution
3) Write a Java program to handle checked and unchecked exceptions. Also,
demonstrate the usage of custom exceptions in real time scenario.

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);
}
}

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();
}
}

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

import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;

// Custom Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(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
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " +
e.getMessage());
}
//Handling Unchecked Exception
try {
int[] arr = {1, 2, 3};
// 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:
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);
}
}

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
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " +
e.getMessage());
}
//Handling Unchecked Exception
try {
int[] arr = {1, 2, 3};
// 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:
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;

public class CollectionsDemo {


public static void main(String[] args) {
ListExample.main(args);
SetExample.main(args);
MapExample.main(args);
}
}
Output:

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;

synchronized void bookTicket(String passengerName, int seatsRequested) {


System.out.println(passengerName + " is trying to book " + seatsRequested
+ " seat(s).");

if (seatsRequested <= availableSeats) {


System.out.println("Booking confirmed for " + passengerName);
availableSeats -= seatsRequested;
} else {
System.out.println("Sorry, not enough seats available for " +
passengerName);
}

System.out.println("Remaining seats: " + availableSeats);


}
}

class Passenger extends Thread {


TicketBooking bookingSystem;
String name;
int seats;

Passenger(TicketBooking bookingSystem, String name, int seats) {


this.bookingSystem = bookingSystem;
this.name = name;
this.seats = seats;
}

public void run() {


bookingSystem.bookTicket(name, seats);
}
}

public class RailwayReservation {


public static void main(String[] args) {
TicketBooking system = new TicketBooking();

Passenger p1 = new Passenger(system, "Alice", 1);


Passenger p2 = new Passenger(system, "Bob", 1);
Passenger p3 = new Passenger(system, "Charlie", 1);

p1.start();
p2.start();
p3.start();
}
}
Output:

Alice is trying to book 1 seat(s).


Booking confirmed for Alice
Remaining seats: 1
Bob is trying to book 1 seat(s).
Booking confirmed for Bob
Remaining seats: 0
Charlie is trying to book 1 seat(s).
Sorry, not enough seats available for Charlie
Remaining seats: 0
Aim:7
Write a program to perform CRUD operations on the student table in a
database using JDBC.

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();

// To read insert data into student table


Scanner sc = new Scanner(System.in);
System.out.println("Inserting Data into student
table : ");

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();

// To read insert data into student table


Scanner sc = new Scanner(System.in);
System.out.println("Update Data in student table :
");

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();

// To read insert data into student table


Scanner sc = new Scanner(System.in);
System.out.println("Delete Data from student table
: ");

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();

// To display the data from the student table


ResultSet rs = 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:
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

/* Program to create a Simple Calculator */


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements
ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;

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:

You might also like