R-22 JNTUH SYLLABUS
OBJECT ORIENTED
PROGRAMMING
THROUGH JAVA
[Link]
II YEAR I SEM & II YEAR II SEM
NEW EDITION
2024
CONTACT :PRASAD SIR 98-49-18-19
[Link] 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 [Link];
import [Link];
class Sample_Program
{
public static void main(String args[])
{
int i,count=0,n;
Scanner sc=new Scanner([Link]);
[Link]("Enter Any Number : ");
n=[Link]();
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2)
[Link](n+" is prime");
else
[Link](n+" is not prime");
}
}
Output:
[Link] a java program to demonstrate the oop principles.[ie
Encapsulation , inheritance , polymorphism and abstraction]
import [Link].*;
class parent
{
void add(int a, int b)
{
[Link](a+b);
}
void add(int a)
{
[Link](a+a);
}
}
class child extends parent
{
void add(int a)
{
[Link](a+a+a);
}
public static void main(String args[])
{
parent o=new parent();
[Link](6,4);
}
}
Output:
[Link] a Java program to handle checked and unchecked
exceptions. Also, demonstrate the usage of custom exceptions
in real time scenario.
[Link]
import [Link];
import [Link];
import [Link];
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
{
[Link]("Registration successful for user: " + name);
}
}
public static void main(String[] args)
{
try {
File file = new File("[Link]");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{
[Link]("File not found: " + [Link]());
}
try {
int[] arr = {1, 2, 3};
[Link](arr[6]);
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Array index out of bounds: " + [Link]());
}
finally
{
[Link]("Cleanup operations can be performed here.");
}
[Link]("Demonstrating Custom Exception:");
try {
register("madhu", 17);
}
catch (InvalidAgeException e)
{
[Link]("Custom Exception Caught: " + [Link]());
}
}
}
Output:
[Link] a Java program on Random Access File class to
perform different read and write operations.
[Link]
import [Link].*;
public class RandomAccessFileExample
{
public static void main(String[] args)
{
try{
RandomAccessFile file = new RandomAccessFile("[Link]", "rw");
String data1 = "Hello";
String data2 = "World";
[Link](data1);
[Link](data2);
[Link](0);
String readData1 = [Link]();
String readData2 = [Link]();
[Link]("Data read from file:");
[Link](readData1);
[Link](readData2);
[Link]([Link]());
String newData = "Java!";
[Link](newData);
[Link](0);
readData1 = [Link]();
readData2 = [Link]();
String readData3 = [Link]();
[Link]("Data read from file after appending:");
[Link](readData1);
[Link](readData2);
[Link](readData3);
[Link]();
}
catch (IOException e)
{
[Link]("An error occurred: " + [Link]());
[Link]();
}
}
}
Output:
[Link] a Java program to demonstrate the working of different
collection classes. [Use package structure to store multiple classes].
[Link]
package collections;
import [Link];
public class ListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
// to display
[Link]("List Example:");
for (String fruit : list) {
[Link](fruit);
}
}
}
[Link]
package collections;
import [Link];
public class SetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Apple"); // This won't be added since sets don't allow dup
licates
// To display
[Link]("Set Example:");
for (String fruit : set) {
[Link](fruit);
}
}
}
[Link]
package collections;
import [Link];
public class MapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "Apple");
[Link](2, "Banana");
[Link](3, "Orange");
// To display
[Link]("Map Example:");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + ": " + [Link]());
}
}
}
[Link]
package collections;
public class CollectionsDemo {
public static void main(String[] args) {
[Link](args);
[Link](args);
[Link](args);
}
}
Output:
[Link] 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)
{
[Link]([Link]().getName() + " - Booking " + seats
" seats");
totalSeatsAvailable = totalSeatsAvailable - seats;
[Link]([Link]().getName() + " - Seat
s left: " + totalSeatsAvailable);
}
else
{
[Link]([Link]().getName() + " -
Not enough seats available to book " + seats + " seats.");
}
}
}
public class TicketBookingThread implements Runnable {
BusReservation br;
int seatsNeeded;
public TicketBookingThread(BusReservation br, int seats) {
[Link] = br;
[Link] = seats;
}
public void run() {
[Link](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");
[Link]();
[Link]();
[Link]();
}
}
Output:
[Link] a program to perform CRUD operations on the student
table in a database using JDBC.
[Link]
import [Link].*;
import [Link];
public class InsertData {
public static void main(String[] args) {
try {
// to create connection with database
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://lo
calhost/mydb", "root", "");
Statement s = [Link]();
// To read insert data into student table
Scanner sc = new Scanner([Link]);
[Link]("Inserting Data into student table : ");
[Link]("________________________________________");
[Link]("Enter student id : ");
int sid = [Link]();
[Link]("Enter student name : ");
String sname = [Link]();
[Link]("Enter student address : ");
String saddr = [Link]();
// to execute insert query
[Link]("insert into student values("+sid+",'"+sname+"','"+sa
ddr+"')");
[Link]("Data inserted successfully into student tabl
e");
[Link]();
[Link]();
} catch (SQLException err) {
[Link]("ERROR: " + err);
} catch (Exception err) {
[Link]("ERROR: " + err);
}
}
}
[Link]
import [Link].*;
import [Link];
public class UpdateData {
public static void main(String[] args) {
try {
// to create connection with database
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://lo
calhost/mydb", "root", "");
Statement s = [Link]();
// To read insert data into student table
Scanner sc = new Scanner([Link]);
[Link]("Update Data in student table : ");
[Link]("________________________________________");
[Link]("Enter student id : ");
int sid = [Link]();
[Link]("Enter student name : ");
String sname = [Link]();
[Link]("Enter student address : ");
String saddr = [Link]();
// to execute update query
[Link]("update student set s_name='"+sname+"',s_address =
'"+saddr+"' where s_id = "+sid);
[Link]("Data updated successfully");
[Link]();
[Link]();
} catch (SQLException err) {
[Link]("ERROR: " + err);
} catch (Exception err) {
[Link]("ERROR: " + err);
}
}
}
[Link]
import [Link].*;
import [Link];
public class DeleteData {
public static void main(String[] args) {
try {
// to create connection with database
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://lo
calhost/mydb", "root", "");
Statement s = [Link]();
// To read insert data into student table
Scanner sc = new Scanner([Link]);
[Link]("Delete Data from student table : ");
[Link]("________________________________________");
[Link]("Enter student id : ");
int sid = [Link]();
// to execute delete query
[Link]("delete from student where s_id = "+sid);
[Link]("Data deleted successfully");
[Link]();
[Link]();
} catch (SQLException err) {
[Link]("ERROR: " + err);
} catch (Exception err) {
[Link]("ERROR: " + err);
}
}
}
[Link]
import [Link].*;
import [Link];
public class DisplayData {
public static void main(String[] args) {
try {
// to create connection with database
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://lo
calhost/mydb", "root", "");
Statement s = [Link]();
// To display the data from the student table
ResultSet rs = [Link]("select * from student");
if (rs != null) {
[Link]("SID \t STU_NAME \t ADDRESS");
[Link]("________________________________________");
while ([Link]())
{
[Link]([Link](1) +" \t "+ [Link](2)+ " \t
"+[Link](3));
[Link]("________________________________________");
}
[Link]();
[Link]();
}
} catch (SQLException err) {
[Link]("ERROR: " + err);
} catch (Exception err) {
[Link]("ERROR: " + err);
}
}
}
Output:
[Link] 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.
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void addcomp(Component cc,int r,int c,int w,int h)
{
[Link]=c;
[Link]=r;
[Link]=w;
[Link]=h;
[Link]=[Link];
add(cc,gc);
}
// performing action on simple calculator
public void actionPerformed(ActionEvent ae)
{ // comparing input value in simple calculator
if([Link]()==b)
{
[Link]("");
}
if([Link]()==one)
{
if(temp==1)
func();
[Link]([Link]()+"1");
}
if([Link]()==two)
{
if(temp==1)
func();
[Link]([Link]()+"2");
}
if([Link]()==three)
{
if(temp==1)
func();
[Link]([Link]()+"3");
}
if([Link]()==four)
{
if(temp==1)
func();
[Link]([Link]()+"4");
}
if([Link]()==five)
{
if(temp==1)
func();
[Link]([Link]()+"5");
}
if([Link]()==six)
{
if(temp==1)
func();
[Link]([Link]()+"6");
}
if([Link]()==seven)
{
if(temp==1)
func();
[Link]([Link]()+"7");
}
if([Link]()==eight)
{
if(temp==1)
func();
[Link]([Link]()+"8");
}
if([Link]()==nine)
{
[Link]([Link]()+"9");
if(temp==1)
func();
}
if([Link]()==zero)
{
[Link]([Link]()+"0");
if(temp==1)
func();
}
if([Link]()==add||[Link]()==sub||[Link]()==mul||
[Link]()==div||[Link]()==mod||[Link]()==sqrt|
|
[Link]()==cbrt||[Link]()==sine)
{
String s;
s=[Link]();
float num1=0,num2=0,num3=0;
float n=[Link](s);
push(n);
if([Link]()==add)
a='+';
if([Link]()==sub)
a='-';
if([Link]()==mul)
a='*';
if([Link]()==div)
a='/';
if([Link]()==mod)
a='%';
[Link]("");
if([Link]()==sqrt)
{
double num=pop();
[Link]([Link]([Link](num)));
}
if([Link]()==cbrt)
{
double num=pop();
[Link]([Link]([Link](num)));
}
if([Link]()==sine)
{
double num=pop();
[Link]([Link]([Link](num)));
}
}
if([Link]()==eq)
{
float num1=0,num2=0,num3=0,temp1;
String s=[Link]();
float n=[Link](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)
{
[Link]([Link](num3));
i=0;
}
else
[Link]([Link]((int)num3));
temp=1;
}
if([Link]()==dot)
{
i=1;
[Link]([Link]()+".");
}
}
public void push(float a)
{
top++;
stk[top]=a;
}
public float pop()
{
float num=stk[top];
top--;
return(num);
}
public void func()
{
[Link]("");
temp=0;
}
public static void main(String rr[])throws Exception
{
new calculator();
}
}
Output:
[Link] 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 [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout([Link]));
l1 = new JLabel();
Font f = new Font("Verdana", [Link], 20);
[Link](f);
[Link]([Link]);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
[Link]("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
[Link]("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
[Link]("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
[Link]("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
[Link]("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}
Output: