0% found this document useful (0 votes)
4 views14 pages

r22 Java Prgmmg Lab Manual

The document outlines various Java programming lab exercises, including using IDEs, demonstrating OOP principles, handling exceptions, and performing CRUD operations with JDBC. It provides source code examples for each task, showcasing key concepts such as encapsulation, inheritance, polymorphism, and file handling. Additionally, it covers creating a simple calculator and managing collections in Java.

Uploaded by

manjulacsepetw
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views14 pages

r22 Java Prgmmg Lab Manual

The document outlines various Java programming lab exercises, including using IDEs, demonstrating OOP principles, handling exceptions, and performing CRUD operations with JDBC. It provides source code examples for each task, showcasing key concepts such as encapsulation, inheritance, polymorphism, and file handling. Additionally, it covers creating a simple calculator and managing collections in Java.

Uploaded by

manjulacsepetw
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

Java Programming Lab Programs

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.

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]
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 packagesimport
java.lang.System;import java.util.Scanner;// Creating Classclass 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:

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:

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

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

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:

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.
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:
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.*;
public class MyCalculator extends Frame implements ActionListener {
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator() {
lbl1=new Label("Number 1: ");
lbl1.setBounds(50,100,100,30);

tf1=new TextField();
tf1.setBounds(160,100,100,30);

lbl2=new Label("Number 2: ");


lbl2.setBounds(50,170,100,30);

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

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

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

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

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

lbl3=new Label("Result : ");


lbl3.setBounds(50,320,100,30);

tf3=new TextField();
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);

public void actionPerformed(ActionEvent ae) {

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));
}
if(ae.getSource() == btn3)
{
result = num1 * num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn4)
{
result = num1 / num2;
tf3.setText(String.valueOf(result));
}
}

public static void main(String args[]) {


MyCalculator calc=new MyCalculator();
}}
Output:
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.*;
Importjava.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");
}
public void mousePressed(MouseEvent m)
{
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