0% found this document useful (0 votes)
21 views32 pages

java manual r22

The document outlines a Java Programming Lab course for B.Tech. II Year II Sem, focusing on OOP principles, exception handling, Java collections, multithreading, and GUI programming with swing controls. It includes a list of experiments with specific programming tasks to demonstrate these concepts, such as creating a test project, handling exceptions, using random access files, and performing CRUD operations with JDBC. Reference books for further reading are also provided.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views32 pages

java manual r22

The document outlines a Java Programming Lab course for B.Tech. II Year II Sem, focusing on OOP principles, exception handling, Java collections, multithreading, and GUI programming with swing controls. It includes a list of experiments with specific programming tasks to demonstrate these concepts, such as creating a test project, handling exceptions, using random access files, and performing CRUD operations with JDBC. Reference books for further reading are also provided.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 32

JAVA PROGRAMMING LAB

B.Tech. II Year II Sem. LT PC

0021
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.
EXPERIMENT-01

Aim:

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:
EXPERIMENT-2

Aim:

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:
EXPERIMENT-3

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:
EXPERIMENT-4

Aim:

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:

EXPERIMENT-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

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:
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.]

public class Safe {

public static void main(String[] args) {


// Tell that one berth is needed
Reservation obj = new Reservation(1);
// Attach first thread to the object
Thread t1 = new Thread(obj);
// Attach second thread to the same object
Thread t2 = new Thread(obj);

// take the thread names as persons names


t1.setName("First Person");
t2.setName("Second Person");

// Send the request for berths


t1.start();
t2.start();
}

}
public class Safe {
public static void main(String[] args) {
// Tell that one berth is needed
Reservation obj = new Reservation(1);

// Attach first thread to the object


Thread t1 = new Thread(obj);
// Attach second thread to the same object
Thread t2 = new Thread(obj);

// take the thread names as persons names


t1.setName("First Person");
t2.setName("Second Person");
// Send the request for berths
t1.start();
t2.start();
}

}
EXPERIMENT-7

Aim:

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:
EXPERIMENT-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 */

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:

EXPERIMENT-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

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

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