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

Oops Java Lab

practical file

Uploaded by

anjalimaurya2801
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Oops Java Lab

practical file

Uploaded by

anjalimaurya2801
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

DR.

APJ ABDUL KALAM TECHNICAL


UNIVERSITY LUCKNOW

RAM CHAMELI CHADHA VISHWAS GIRLS COLLEGE

SESSION 2023-24
PROJECT FILE
OBJECT ORIENTED PROGRAMMING LAB

SUBMITTED BY: SUBMITTED TO:


ANJALI MAURYA GUNJAN MAM
MCA 1ST YR
ROLL NO: 2301170140003
INDEX

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.

3. Write a program to print addition of 2 matrices in


JAVA.

4. Write a program in Java to implement the following


types of inheritance.
• Single Inheritance
• Multilevel Inheritance

5. Write a Java program to implement user define


exception handling for negative amount enter.

6. Create a package named ‘Mathematics’ and add a


class ‘Matrix’ with methods to add and subtract
matrices (2X2). WAP in Java importing the
mathematics package and use the classes definition
in it.

7. Develop a calculator application in Java.


8. Develop a Client Server Application
9. Develop GUI applications using Swing component.
10. Create Java programs using inheritance and
polymorphism.

11. File handling and establishment of database


connection.
1. WAP that takes input through command line argument and
then prints whether a number is prime or not.
public class PrimeChecker {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a number as a command-line
argument.");
return;
}

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

// Function to check if a number is prime


public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
}

OUTPUT:
Please provide a number as a command-line argument.

2. WAP to check whether a number is palindrome or not.


class Main {
public static void main(String[] args) {
int num = 3553, reversedNum = 0, remainder;
int originalNum = num;
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
if (originalNum == reversedNum) {
System.out.println(originalNum + " is Palindrome.");
}
else {
System.out.println(originalNum + " is not Palindrome.");
}
}
}
OUTPUT:
3553 is Palindrome

3. Write a program to print addition of 2 matrices in JAVA.


public class MatrixAdditionExample{
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];
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
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

5. Write a Java program to implement user define exception


handling for negative amount enter.
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the amount: ");


try {
double amount = scanner.nextDouble();

// Check if amount is negative


if (amount < 0) {
throw new NegativeAmountException();
}

// If amount is positive or zero, proceed with normal execution


System.out.println("Amount entered: " + amount);

} 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:

6. Create a package named ‘Mathematics’ and add a class


‘Matrix’ with methods to add and subtract matrices (2X2).
WAP in Java importing the mathematics package and use the
classes definition in it.

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

7. Develop a calculator application in Java.

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

8. Develop a Client Server Application.

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

9. Develop GUI applications using Swing component.

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.

11. File handling and establishment of database connection.


File Handling-
import java.io.File;
class file Property {
public static void main(String[] args)
{
String fname = args[0];
File f= new File(fname);
System.out.println("File name:" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:"+f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :"+f.exists());
if (f.exists()) {
System.out.println("Is writable:" + f.canWrite());
System.out.println("Is readable" + f.canRead());
System.out.println("Is a directory:" + f.isDirectory());
System.out.println("File Size in bytes "+f.length());

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

You might also like