Oops Java Lab
Oops Java Lab
SESSION 2023-24
PROJECT FILE
OBJECT ORIENTED PROGRAMMING LAB
S.NO. TOPIC T.
SIGNATURE
1. WAP that takes input through command line
argument and then prints whether a number is
prime or not
2. WAP to check whether a number is palindrome or
not.
try {
// Parse the first command-line argument as an integer
int number = Integer.parseInt(args[0]);
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please provide a valid integer
number.");
}
}
OUTPUT:
Please provide a number as a command-line argument.
OUTPUT:
268
486
469
4. Write a program in Java to implement the following types of
inheritance.
➔ Single Inheritance
➔ Multilevel Inheritance
Single inheritance:
class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}
Output:
Total salary credited: 414408.0
Bonus of six months: 18000.0
Multiple inheritance:
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}
OUTPUT:
registration number= 0987
marks= 78.0
score= 68.7
} catch (NegativeAmountException e) {
// Handle custom exception
System.out.println(e.getMessage());
// Additional handling logic if required
} catch (Exception e) {
// Handle other exceptions (e.g., input mismatch)
System.out.println("Error: Invalid input.");
} finally {
scanner.close(); // Close scanner to prevent resource leak
}
}
}
OUTPUT:
Enter the amount:
import package.Mathematics.*;
public class MatrixAddition{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//adding and printing addition of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
OUTPUT:
268
486
469
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the first number:”);
int firstNumber = sc.nextint();
System.out.print(“Enter the second number);
int secondNumber = sc.nextint();
System.out.print(“Enter the type of operation you want to perform (+,-
,*,/,%):”);
String operation = sc.next();
int result = performOperation(firstNumber, secondNumber, operation);
System.out.println(“Your answer is: + result”);
}
public static int performOperation(int firstNumber, int secondNumber,
string operation)
{
int result = 0;
switch (operation) {
case “+”:
result = firstNumber + secondNumber;
break;
case “-”:
result = firstNumber – secondNumber;
case “*”:
result = firstNumber * secondNumber;
case “%”:
result = firstNumber % secondNumber;
case “/”:
result = firstNumber / secondNumber;
break;
default:
System.out.println(“Invalid operation”);
break;
}
return result;
}
}
OUTPUT:
Enter the first number: 3
Enter the second number: 7
Enter the type of operation you want to perform(+,-,*,/,%):+
Your answer is: 10
Myserver.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main (String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println(“message= ”+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
MyClient.java
import java.io.*;
import java.net*;
public class MyClient {
public static void main (String[] args) {
try{
Socket s=new Socket(“localhost”’6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF(“Hello Server”);
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT:
Hello Server
import java.awt.*;
import java.awt.event.*;
public class MyCalculator extends Frame
{
public Boolean setClear=true;
double number, memValue;
char op;
String digitButtonText[] = {“7”, “8”, “9”, “4”, “5”, “6”, “1”, “2”, “3”,“0”, “+/-
”, “.”};
String operatorButtonText[] = {“/”, “sqrt”, “*”, “%”, “-”, “1/X”, “+”, “=” };
String memoryButtonText[] = {“MC”, “MR”, “MS”, “M+” };
String specialButtonText[] = {“Backspc”, “C”, “CE” };
MyDigitButton digitButton[]=new MyDigitButton[digitButtonText.length];
MyOperatorButton operatorButton[]=new MyOperatorButton[operator
ButtonText.length];
MyMemoryButton memoryButton[]=new MyMemoryButton[memory
Buttontext.length];
MySpecialButton specialButton[]=new MySpecialButton[specialButton
Text.length];
Label displayLabel=new Label(“0”,Label.RIGHT);
Label memLabel=new Label(“ ”,Label.RIGHT);
final int FRAME_WIDTH=30,FRAME_HEIGHT=325;
final int HEIGHT=30, WIDTH=30,H_SPACE=10,V_SPACE=10;
final int TOPX=30, TOPY=50;
MyCalculator(String frameText)
{
Super(frameText);
Int tempX=TOPX, y=TOPY;
displayLabel.setBounds(tempX,y,240,HEIGHT);
displayLabel.setBackground(Color.BLUE);
displayLabel.setForeground(Color.WHITE);
add(displayLabel);
memLabel.setBounds(TOPX, TOPY+HEIGHT+V_SPACE,WIDTH,HEIGHT);
add(memLabel);
tempX=TOPX;
y=TOPY+2*(HEIGHT+V_SPACE);
for(int i=0;i<memoryButton.length;i++)
{
memoryButton[i]=new MyMemoryButton(tempX,y,WIDTH,
HEIGHT,memoryButt on Text[i], this);
memoryButton[i].setForeground(Color.RED);
y+=HEIGHT+V_SPACE;
}
tempX=TOPX+1*(WIDTH+H_SPACE); y=TOPY+1*(HEIGHT+V_SPACE);
for(int i=0;i<specialButton.length;i++)
{
specialButton[i]=new MySpecialButton(tempX,y,WIDTH
*2,HEIGHT,specialButto nText[i], this);
specialButton[i].setForeground (Color.RED);
tempX=tempX+2*WIDTH+H_SPACE;
}
int digitX=TOPX+WIDTH+H_SPACE;
int digitY=TOPY+2*(HEIGHT+V_SPACE);
tempX-digitX; y=digitY;
for(int i=0;i<digitButton.length;i++)
}
digitButton[i]=new MyDigitButton(tempX,y,WIDTH,
HEIGHT,digitButtonText[i], this);
digitButton[i].setForeground (Color.BLUE);
tempX+=WIDTH+H_SPACE;
if((i+1)%3==0){tempX-digitX; y+=HEIGHT+V_SPACE;}
}
int opsX-digitX+2*(WIDTH+H_SPACE)+H_SPACE;
int opsY=digitY;
tempX=opsX; y=opsy;
for(int i=0;i<operatorButton.length;i++)
{
tempX+=WIDTH+H_SPACE;
operatorButton[i]=new MyOperatorButton(tempX,y,WIDTH,HEIGHT,
operatorButtonText[i], this);
operatorButton[i].setForeground (Color.RED);
if((i+1)%2==0){tempX=opsX; y+=HEIGHT+V_SPACE;}
}
addWindowListener(new WindowAdapter()
{
public void window Closing(WindowEvent ev)
{System.exit(0);}
});
setLayout(null);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setVisible(true);
}
static String getFormattedText(double temp)
{
String resText=""+temp;
if(resText.lastIndexOf(".0")>0)
resText=resText.substring(0,resText.length()-2);
return resText;
}
public static void main(String [] args)
{
new MyCalculator("Calculator - JavaTpoint");
}
}
class MyDigitButton extends Button implements ActionListener
{
MyCalculator cl;
MyDigitButton(int x, int y, int width, int height,String cap, MyCalculator
clc)
{
super(cap);
setBounds(x,y,width, height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
static boolean isInString(String s, char ch)
{
for(int i=0; i<s.length();i++) if(s.charAt(i) ==ch) return true;
return false;
}
public void action Performed (ActionEvent ev)
{
String tempText=((MyDigitButton)ev.getSource()).getLabel();
if(tempText.equals("."))
{
if(cl.setClear)
{cl.displayLabel.setText("0.");cl.setClear=false;}
else if(!isInString(cl.displayLabel.getText(),'.'))
cl.displayLabel.setText(cl.displayLabel.getText()+".");
return;
}
int index=0;
try{
index=Integer.parseInt(tempText);
}catch(NumberFormatException e){return;}
if (index==0 && cl.displayLabel.getText().equals("0")) return;
if(cl.setClear)
{
cl.displayLabel.setText(""+index); cl.setClear=false;
}
else
}
cl.displayLabel.setText(cl.displayLabel.getText()+index);
}
}
class MyOperatorButton extends Button implements ActionListener
{
MyCalculator cl;
MyOperatorButton(int x, int y, int width, int height,String cap,
MyCalculator clc)
{
super(cap);
setBounds(x,y,width, height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
public void action Performed (ActionEvent ev)
{
String opText=((MyOperatorButton)ev.getSource()).getLabel();
cl.setClear=true;
double temp Double.parseDouble(cl.displayLabel.getText());
if(opText.equals("1/x"))
{
try
{double tempd=1/(double)temp;
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch (ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(opText.equals("sqrt"))
{
try
{double tempd=Math.sqrt(temp);
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(!opText.equals("="))
{
cl.number=temp;
cl.op=opText.charAt(0);
return;
}
switch(cl.op)
{
case '+':
temp+=cl.number;break;
case '-':
temp=cl.number-temp; break;
case ‘*’:
temp*=cl.number; break;
case '%':
try{temp=cl.number%temp;}
catch (ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
case '/':
try{temp=cl.number/temp;}
catch (ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
}
cl.displayLabel.setText(MyCalculator.getFormattedText(temp));
}
}
class MyMemoryButton extends Button implements ActionListener
{
MyCalculator cl;
MyMemoryButton(int x, int y, int width, int height,String cap,
MyCalculator clc)
{
super(cap);
setBounds(x,y,width, height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
public void action Performed (ActionEvent ev)
{
char memop=((MyMemoryButton)ev.getSource()).getLabel().charAt(1);
cl.setClear=true;
double temp Double.parseDouble(cl.displayLabel.getText());
switch(memop)
{
case 'C':
cl.memLabel.setText(" ");cl.mem Value=0.0; break;
case 'R':
cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValue));
break;
case 'S':
cl.mem Value=0.0;
case '+':
cl.memValue+ Double.parseDouble(cl.displayLabel.getText());
if(cl.displayLabel.getText().equals("0")||cl.displayLabel.getText().equals("
0.0") )
cl.memLabel.setText(" ");
else
cl.memLabel.setText("M");
break;
}
}
}
class MySpecialButton extends Button implements ActionListener
{
MyCalculator cl;
MySpecialButton(int x, int y, int width, int height, String cap,
MyCalculator clc)
}
super(cap);
setBounds(x,y,width, height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
static String backSpace(String s)
{
String Res="";
for(int i=0; i<s.length()-1; i++) Res+=s.charAt(i);
return Res;
}
public void action Performed (ActionEvent ev)
{
String opText=((MySpecialButton)ev.getSource()).getLabel();
if(opText.equals("Backspc"))
{
String tempText-backSpace (cl.displayLabel.getText());
if(tempText.equals(""))
cl.displayLabel.setText("0");
else
cl.displayLabel.setText(tempText);
return;
}
if(opText.equals("C"))
{
cl.number=0.0; cl.op=' '; cl.mem Value=0.0;
cl.memLabel.setText(" ");
}
cl.displayLabel.setText("0"); cl.setClear=true;
}
}
OUTPUT:
10. Create Java programs using inheritance and
polymorphism.
Inheritance:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
Polymorphism:
class Bike{
void run()
{
System.out.println("Running");
}
}
class Splendor extends Bike{
void run()
{
System.out.println("Running safely with 60km");
}
public static void main(String args[]){
Bike b= new Splendor();
b.run();
}
}
Output:
Running safely with 60km.
Output:
File name :file.txt
Path: file.txt
Absolute path:C:\Users\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20