Java Manual R-22
Java Manual R-22
OBJECT ORIENTED
PROGRAMMING
THROUGH JAVA
B.TECH
II YEAR I SEM & II YEAR II SEM
NEW EDITION
2024
import java.lang.System;
import java.util.Scanner;
class Sample_Program
{
public static void main(String args[])
{
int i,count=0,n;
Scanner sc=new Scanner(System.in);
System.out.print("Enter Any Number : ");
n=sc.nextInt();
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.[ie
Encapsulation , inheritance , polymorphism and abstraction]
import java.lang.*;
class parent
{
void add(int a, int b)
{
System.out.println(a+b);
}
void add(int a)
{
System.out.println(a+a);
}
}
class child extends parent
{
void add(int a)
{
System.out.println(a+a+a);
}
public static void main(String args[])
{
parent o=new parent();
o.add(6,4);
}
}
Output:
3.Write a Java program to handle checked and unchecked
exceptions. Also, demonstrate the usage of custom exceptions
in real time scenario.
ExceptionsDemo.java
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
class InvalidAgeException extends Exception
{
public InvalidAgeException(String message)
{
super(message);
}
}
Output:
4.Write a Java program on Random Access File class to
perform different read and write operations.
RandomAccessFileExample.java
import java.io.*;
public class RandomAccessFileExample
{
public static void main(String[] args)
{
try{
RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
String data1 = "Hello";
String data2 = "World";
file.writeUTF(data1);
file.writeUTF(data2);
file.seek(0);
String readData1 = file.readUTF();
String readData2 = file.readUTF();
System.out.println("Data read from file:");
System.out.println(readData1);
System.out.println(readData2);
file.seek(file.length());
String newData = "Java!";
file.writeUTF(newData);
file.seek(0);
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);
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].
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 dup
licates
// 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;
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.]
class BusReservation
{
private int totalSeatsAvailable = 10;
public synchronized void bookSeat(int seats)
{
if (totalSeatsAvailable >= seats)
{
System.out.println(Thread.currentThread().getName() + " - Booking " + seats
" seats");
totalSeatsAvailable = totalSeatsAvailable - seats;
System.out.println(Thread.currentThread().getName() + " - Seat
s left: " + totalSeatsAvailable);
}
else
{
System.out.println(Thread.currentThread().getName() + " -
Not enough seats available to book " + seats + " seats.");
}
}
}
t1.start();
t2.start();
t3.start();
}
}
Output:
7.Write a program to perform CRUD operations on the student
table in a database using JDBC.
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://lo
calhost/mydb", "root", "");
Statement s = con.createStatement();
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://lo
calhost/mydb", "root", "");
Statement s = con.createStatement();
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://lo
calhost/mydb", "root", "");
Statement s = con.createStatement();
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://lo
calhost/mydb", "root", "");
Statement s = con.createStatement();
}
}
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.
Calculator.java
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class calculator extends Frame implements ActionListener
{
int i=0,temp=0;
char a;
float stk[];
int top;
TextField t;
Button dot,mod,b,one,two,three,four,five,six,seven,eight,nine,zero,add
,sub,mul,div,eq,sine,sqrt,cbrt;
GridBagConstraints gc;
calculator()
{
super("My Calculator");
stk=new float[20];
top=-1;
gc=new GridBagConstraints(); //creating gridlayout
//creating textfield and button on simple calculator
t=new TextField("");
b=new Button("Reset");
one=new Button(" 1 ");
two=new Button(" 2 ");
three=new Button(" 3 ");
four=new Button(" 4 ");
five=new Button(" 5 ");
six=new Button(" 6 ");
seven=new Button(" 7 ");
eight=new Button(" 8 ");
nine=new Button(" 9 ");
zero=new Button(" 0 ");
add=new Button(" + ");
sub=new Button(" - ");
mul=new Button(" * ");
div=new Button(" / ");
eq=new Button(" = ");
dot=new Button("...");
mod=new Button(" % ");
sine=new Button(" sin ");
sqrt=new Button(" sqrt ");
cbrt=new Button(" cbrt ");
setSize(250,250);
setLocation(500,200);
setLayout(new GridBagLayout());
addcomp(one,1,1,1,1);
addcomp(two,1,2,1,1);
addcomp(three,1,3,1,1);
addcomp(four,1,4,1,1);
addcomp(five,2,1,1,1);
addcomp(six,2,2,1,1);
addcomp(seven,2,3,1,1);
addcomp(eight,2,4,1,1);
addcomp(nine,3,1,1,1);
addcomp(zero,3,2,1,1);
addcomp(mul,3,3,1,1);
addcomp(div,3,4,1,1);
addcomp(add,4,1,1,1);
addcomp(sub,4,2,1,1);
addcomp(eq,4,3,1,1);
addcomp(mod,4,4,1,1);
addcomp(dot,5,1,1,1);
addcomp(sine,5,2,1,1);
addcomp(sqrt,5,3,1,1);
addcomp(cbrt,5,4,1,1);
addcomp(new Label(""),7,1,4,1);
addcomp(t,8,1,4,1);
addcomp(new Label(""),9,1,4,1);
addcomp(b,10,2,2,1);
setVisible(true);
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
four.addActionListener(this);
five.addActionListener(this);
six.addActionListener(this);
seven.addActionListener(this);
eight.addActionListener(this);
nine.addActionListener(this);
zero.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
eq.addActionListener(this);
mod.addActionListener(this);
dot.addActionListener(this);
sine.addActionListener(this);
sqrt.addActionListener(this);
cbrt.addActionListener(this);
b.addActionListener(this);
}
public void addcomp(Component cc,int r,int c,int w,int h)
{
gc.gridx=c;
gc.gridy=r;
gc.gridwidth=w;
gc.gridheight=h;
gc.fill=gc.BOTH;
add(cc,gc);
}
// performing action on simple calculator
public void actionPerformed(ActionEvent ae)
{ // comparing input value in simple calculator
if(ae.getSource()==b)
{
t.setText("");
}
if(ae.getSource()==one)
{
if(temp==1)
func();
t.setText(t.getText()+"1");
}
if(ae.getSource()==two)
{
if(temp==1)
func();
t.setText(t.getText()+"2");
}
if(ae.getSource()==three)
{
if(temp==1)
func();
t.setText(t.getText()+"3");
}
if(ae.getSource()==four)
{
if(temp==1)
func();
t.setText(t.getText()+"4");
}
if(ae.getSource()==five)
{
if(temp==1)
func();
t.setText(t.getText()+"5");
}
if(ae.getSource()==six)
{
if(temp==1)
func();
t.setText(t.getText()+"6");
}
if(ae.getSource()==seven)
{
if(temp==1)
func();
t.setText(t.getText()+"7");
}
if(ae.getSource()==eight)
{
if(temp==1)
func();
t.setText(t.getText()+"8");
}
if(ae.getSource()==nine)
{
t.setText(t.getText()+"9");
if(temp==1)
func();
}
if(ae.getSource()==zero)
{
t.setText(t.getText()+"0");
if(temp==1)
func();
}
if(ae.getSource()==add||ae.getSource()==sub||ae.getSource()==mul||
ae.getSource()==div||ae.getSource()==mod||ae.getSource()==sqrt|
|
ae.getSource()==cbrt||ae.getSource()==sine)
{
String s;
s=t.getText();
float num1=0,num2=0,num3=0;
float n=Float.parseFloat(s);
push(n);
if(ae.getSource()==add)
a='+';
if(ae.getSource()==sub)
a='-';
if(ae.getSource()==mul)
a='*';
if(ae.getSource()==div)
a='/';
if(ae.getSource()==mod)
a='%';
t.setText("");
if(ae.getSource()==sqrt)
{
double num=pop();
t.setText(Double.toString(Math.sqrt(num)));
}
if(ae.getSource()==cbrt)
{
double num=pop();
t.setText(Double.toString(Math.cbrt(num)));
}
if(ae.getSource()==sine)
{
double num=pop();
t.setText(Double.toString(Math.sin(num)));
}
}
if(ae.getSource()==eq)
{
float num1=0,num2=0,num3=0,temp1;
String s=t.getText();
float n=Float.parseFloat(s);
push(n);
num1=pop();
num2=pop();
switch(a)
{
case '+' : num3=num1+num2;push(num3);break;
case '-' : num3=num2-num1;push(num3);break;
case '*' : num3=num1*num2;push(num3);break;
case '/' : num3=num2/num1;push(num3);break;
case '%' : num3=num2%num1;push(num3);break
;
}
if(i==1)
{
t.setText(Float.toString(num3));
i=0;
}
else
t.setText(Integer.toString((int)num3));
temp=1;
}
if(ae.getSource()==dot)
{
i=1;
t.setText(t.getText()+".");
}
}
public void push(float a)
{
top++;
stk[top]=a;
}
public float pop()
{
float num=stk[top];
top--;
return(num);
}
public void func()
{
t.setText("");
temp=0;
}
public static void main(String rr[])throws Exception
{
new calculator();
}
}
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]
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: