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

Java Manual R-22

Uploaded by

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

Java Manual R-22

Uploaded by

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

R-22 JNTUH SYLLABUS

OBJECT ORIENTED
PROGRAMMING
THROUGH JAVA
B.TECH
II YEAR I SEM & II YEAR II SEM

NEW EDITION
2024

CONTACT :PRASAD SIR 98-49-18-19


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

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

public class ExceptionsDemo


{
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)
{
try {
File file = new File("myfile.txt");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{
System.out.println("File not found: " + e.getMessage());
}
try {
int[] arr = {1, 2, 3};
System.out.println(arr[6]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds: " + e.getMessage());
}
finally
{
System.out.println("Cleanup operations can be performed here.");
}
System.out.println("Demonstrating Custom Exception:");
try {
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.

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;

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

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

public class TicketBookingThread implements Runnable {


BusReservation br;
int seatsNeeded;

public TicketBookingThread(BusReservation br, int seats) {


this.br = br;
this.seatsNeeded = seats;
}

public void run() {


br.bookSeat(seatsNeeded);
}

public static void main(String[] args)


{
BusReservation br = new BusReservation();
Thread t1 = new Thread(new TicketBookingThread(br, 2), "Agent1");

Thread t2 = new Thread(new TicketBookingThread(br, 5), "Agent2");


Thread t3 = new Thread(new TicketBookingThread(br, 4), "Agent3");

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

// 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+"','"+sa
ddr+"')");
System.out.println("Data inserted successfully into student tabl
e");

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

// 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://lo
calhost/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://lo
calhost/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.

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:

You might also like