OOPS CODES
OOPS CODES
OOPS CODES
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.
Program:
/* 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:
Enter Any Number : 10
10 is not prime
2. Write a Java program that implements a multi-thread application that has three threads. The first thread
generates a random integer every 1 second and if the value is even, the second thread computes the square
of the number and prints. If the value is odd, the third thread will print the value of the cube of the
number.
Program:
import java.util.*;
public class Multithreading
{
public static void main(String args[])
{
sample s=new sample();
s.start();
}
}
class even extends Thread
{
public int x;
public even(int num)
{ x=num;
}
public void run()
{
System.out.println("New thread "+x+" is even and square of "+x+" is : "+(x*x));
}
}
class odd extends Thread
{
public int x;
public odd(int num)
{x=num;
}
public void run()
{
System.out.println("New thread "+x+" is odd and cube of "+x+" is : "+(x*x*x));
}
}
class sample extends Thread
{
int num=0;
public void run()
{
for(int i=1;i<=6;i++)
{
num=r.nextInt(200);
System.out.println("Mainthreadandgeneratednumberis"+num); try
{
if(num%2==0)
{
even e=new even(num);
e.start();
}
else
{
odd o=new odd(num);
o.start();
}
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(" ");
}
}
}
OUTPUT:
3. write a Java program to create an abstract class named Shape that contains two integers and an empty
method named print Area (). Provide three classes named Rectangle, Triangle, and Circle such that each
one of the classes extends the class Shape. Each one of the classes contains only the method printArea ()
that prints the area of the given shape.
Program:
import java.util.*;
abstract class Shape {
public int x,y;
public abstract void printArea();
}
class Rectangle1 extends Shape {
public void printArea() {
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends Shape {
public void printArea() {
float area;
area= (x * y) / 2.0f;
System.out.println("Area of Triangle is " + area);
}
}
class Circle extends Shape {
public void printArea() {
float area;
area=(22 * x * x) / 7.0f;
System.out.println("Area of Circle is " + area);
}
}
public class AreaOfShapes {
public static void main(String[] args) {
int choice;
Scanner sc=new Scanner(System.in);
System.out.println("Menu \n 1.Area of Rectangle \n 2.Area of Traingle \n 3.Area of Circle ");
System.out.print("Enter your choice : ");
choice=sc.nextInt();
switch(choice) {
case 1: System.out.println("Enter length and breadth for area of rectangle : ");
Rectangle1 r = new Rectangle1();
r.x=sc.nextInt();
r.y=sc.nextInt();
r.printArea();
break;
case 2: System.out.println("Enter bredth and height for area of traingle : ");
Triangle t = new Triangle();
t.x=sc.nextInt();
t.y=sc.nextInt();
t.printArea();
break;
case 3: System.out.println("Enter radius for area of circle : ");
Circle c = new Circle();
c.x = sc.nextInt();
c.printArea();
break;
default:System.out.println("Enter correct choice");
}
}
}
OUTPUT:
4. Write a Java program that correctly implements the producer – consumer problem using the concept of
inter thread communication.
PROGRAM:
public class ProducerConsumerTest {
public static void main(String[] args) {
SharedResource s = new SharedResource();
Producer p1 = new Producer(s, 1);
Consumer c1 = new Consumer(s, 1);
p1.start();
c1.start();
}
}
class SharedResource {
private int contents;
private boolean available = false;
JTextField resultTxt;
JButton btn_digits[] = new JButton[10];
JButton btn_plus, btn_minus, btn_mul, btn_div, btn_equal, btn_dot, btn_clear;
char eventFrom;
SimpleCalculator() {
Font txtFont = new Font("SansSerif", Font.BOLD, 20);
Font titleFont = new Font("SansSerif", Font.BOLD, 30);
Font expressionFont = new Font("SansSerif", Font.BOLD, 15);
resultPanel.add(appTitle);
resultPanel.add(resultTxt);
resultPanel.add(expression);
for(int i = 0; i < 10; i++) {
buttonPanel.add(btn_digits[i]);
}
buttonPanel.add(btn_plus);
buttonPanel.add(btn_minus);
buttonPanel.add(btn_mul);
buttonPanel.add(btn_div);
buttonPanel.add(btn_dot);
buttonPanel.add(btn_equal);
infoPanel.add(btn_clear);
infoPanel.add(siteTitle);
actualWindow.add(resultPanel);
actualWindow.add(buttonPanel);
actualWindow.add(infoPanel);
actualWindow.setSize(300, 500);
actualWindow.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
eventFrom = e.getActionCommand().charAt(0);
String buildNumber;
if(Character.isDigit(eventFrom)) {
buildNumber = resultTxt.getText() + eventFrom;
resultTxt.setText(buildNumber);
} else if(e.getActionCommand() == ".") {
buildNumber = resultTxt.getText() + eventFrom;
resultTxt.setText(buildNumber);
}
else if(eventFrom != '='){
oparand_1 = Double.parseDouble(resultTxt.getText());
operator = e.getActionCommand();
expression.setText(oparand_1 + " " + operator);
resultTxt.setText("");
} else if(e.getActionCommand() == "Clear") {
resultTxt.setText("");
}
else {
operand_2 = Double.parseDouble(resultTxt.getText());
(OR)
PROGRAM:
tf1=new TextField();
tf1.setBounds(160,100,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);
setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);
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));
}
}
B) Develop an applet in Java that receives an integer in one textfield, and computes its factorial Value and
returns it in an other textfield, when the button named “Compute” is clicked.
PROGRAM:
/** Develop applet to find factorial of the given number */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="FactorialApplet" width=500 height=250>
</applet>*/
public class FactorialApplet extends Applet implements ActionListener {
Label L1,L2;
TextField T1,T2;
Button B1;
public void init() {
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n) {
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}
OUTPUT:
7. Write a Java program that creates a user interface to perform integer divisions. The user enters two
numbers in the text fields, Num1and Num2. The division of Num1 and Num2 is displayed in the Result
field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw
a Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception.
Display the exception in a message dialog box.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
IntegerDivisions() {
actualWindow = new JFrame("Experiment 4");
container = new JPanel();
container.setLayout(new FlowLayout());
txt_num1 = new JTextField(20);
txt_num2 = new JTextField(20);
txt_result = new JTextField(20);
container.add(txt_num1);
container.add(txt_num2);
container.add(btn_div);
container.add(txt_result);
actualWindow.add(container);
actualWindow.setSize(300, 300);
actualWindow.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
int num1, num2;
try {
num1 = Integer.parseInt(txt_num1.getText());
num2 = Integer.parseInt(txt_num2.getText());
txt_result.setText(num1/num2+"");
}
catch(NumberFormatException nfe) {
JOptionPane.showMessageDialog(actualWindow,"Please do enter only integers");
}
catch(ArithmeticException ae) {
JOptionPane.showMessageDialog(actualWindow,"Divisor can not be ZERO");
}
}
}
public class Week_7 {
}
OUTPUT:
8. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and
the remaining lines correspond to rows in the table. The elements are separated by commas. Write a java
program to display the table using Labels in Grid Layout.
PROGRAM:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Text_To_Table extends JFrame
{
public void convertTexttotable()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fis = new FileInputStream("./Table.txt");
Scanner sc = new Scanner(fis);
String[] arrayList;
String str;
while (sc.hasNextLine())
{
str = sc.nextLine();
arrayList = str.split(",");
for (String i : arrayList)
{
add(new Label(i));
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
setVisible(true);
setTitle("Display Data in Table");
}
}
public class TableText
{
public static void main(String[] args)
{
Text_To_Table tt = new Text_To_Table();
tt.convertTexttotable();
}
}
INPUT FORMAT:
NAME,NUMBER,MARKS,RESULT
NAVEEN,501,544,PASS
RAMESH,503,344,PASS
DURGA,521,344,PASS
ASHOK,532,344,PASS
MADHU,543,344,PASS
OUTPUT:
9. Write a Java program that simulates a traffic light. The program lets the user select one of three lights:
red, yellow, or green with radio buttons. On selecting a button, an appropriate message with “Stop” or
“Ready” or “Go” should appear above the buttons in the selected color. Initially, there is no message
shown.
PROGRAM:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class TrafficLightSimulator extends JFrame implements ItemListener {
JLabel lbl1, lbl2;
JPanel nPanel, cPanel;
CheckboxGroup cbg;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(600,400);
setLayout(new GridLayout(2, 1));
nPanel = new JPanel(new FlowLayout());
cPanel = new JPanel(new FlowLayout());
lbl1 = new JLabel();
Font font = new Font("Verdana", Font.BOLD, 70);
lbl1.setFont(font);
nPanel.add(lbl1);
add(nPanel);
Font fontR = new Font("Verdana", Font.BOLD, 20);
lbl2 = new JLabel("Select Lights");
lbl2.setFont(fontR);
cPanel.add(lbl2);
cbg = new CheckboxGroup();
Checkbox rbn1 = new Checkbox("Red Light", cbg, false);
rbn1.setBackground(Color.RED);
rbn1.setFont(fontR);
cPanel.add(rbn1);
rbn1.addItemListener(this);
Checkbox rbn2 = new Checkbox("Orange Light", cbg, false);
rbn2.setBackground(Color.ORANGE);
rbn2.setFont(fontR);
cPanel.add(rbn2);
rbn2.addItemListener(this);
Checkbox rbn3 = new Checkbox("Green Light", cbg, false);
rbn3.setBackground(Color.GREEN);
rbn3.setFont(fontR);
cPanel.add(rbn3);
rbn3.addItemListener(this);
add(cPanel);
setVisible(true);
// to close the main window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// To read selected item
public void itemStateChanged(ItemEvent i) {
Checkbox chk = cbg.getSelectedCheckbox();
String str=chk.getLabel();
char choice=str.charAt(0);
switch (choice) {
case 'R':lbl1.setText("STOP");
lbl1.setForeground(Color.RED);
break;
case 'O':lbl1.setText("READY");
lbl1.setForeground(Color.ORANGE);
break;
case 'G':lbl1.setText("GO");
lbl1.setForeground(Color.GREEN);
break;
}
}
// main method
public static void main(String[] args) {
new TrafficLightSimulator();
}
}
OUTPUT:
10. Write a Java program that loads names and phone numbers from a text file where the data is organized
as one line per record and each field in a record are separated by a tab (\t). It takes a name or phone
number as input and prints the corresponding other value from the hash table (hint: use hash tables).
PROGRAM:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
if (output != null) {
System.out.println("Data found in HashTable: " + output);
} else {
System.out.println("Data not found in HashTable");
}
}
if (filesList != null) {
for (File file : filesList) {
if (file.isFile())
System.out.println("- " + file.getName());
else
System.out.println("> " + file.getName());
}
} else {
System.out.println("The directory is empty or cannot be accessed.");
}
}