0% found this document useful (0 votes)
29 views23 pages

Basic Arithmetic Operations

Uploaded by

Khushi Nagapure
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)
29 views23 pages

Basic Arithmetic Operations

Uploaded by

Khushi Nagapure
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/ 23

1.

Maximum and Minimum of Three Integers

import java.util.Scanner;

public class MaxMin {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter three integers:");

int num1 = scanner.nextInt();

int num2 = scanner.nextInt();

int num3 = scanner.nextInt();

int max = Math.max(num1, Math.max(num2, num3));

int min = Math.min(num1, Math.min(num2, num3));

System.out.println("Maximum: " + max);

System.out.println("Minimum: " + min);

2. Multiplication Table

public class MultiplicationTable {

public static void main(String[] args) {

int number = Integer.parseInt(args[0]);

System.out.println("Multiplication Table for " + number);

for (int i = 1; i <= 10; i++) {

System.out.println(number + " x " + i + " = " + (number * i));

3. Basic Arithmetic Operations

public class ArithmeticOperations {

public static void main(String[] args) {


int num1 = Integer.parseInt(args[0]);

int num2 = Integer.parseInt(args[1]);

System.out.println("Addition: " + (num1 + num2));

System.out.println("Subtraction: " + (num1 - num2));

System.out.println("Multiplication: " + (num1 * num2));

System.out.println("Division: " + (num1 / (double) num2));

4. Prime Number Check

import java.util.Scanner;

public class PrimeCheck {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter a number:");

int number = scanner.nextInt();

boolean isPrime = true;

if (number <= 1) {

isPrime = false;

} else {

for (int i = 2; i <= Math.sqrt(number); i++) {

if (number % i == 0) {

isPrime = false;

break;

System.out.println(number + " is " + (isPrime ? "a Prime number." : "not a Prime number."));

}
}

5. Perfect Numbers Between 1 and n

import java.util.Scanner;

public class PerfectNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter a number n:");

int n = scanner.nextInt();

System.out.println("Perfect numbers between 1 and " + n + ":");

for (int i = 1; i <= n; i++) {

if (isPerfect(i)) {

System.out.println(i);

static boolean isPerfect(int num) {

int sum = 0;

for (int i = 1; i < num; i++) {

if (num % i == 0) {

sum += i;

return sum == num;

6. Sum of Digits of a Number

import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter a number:");

int number = scanner.nextInt();

int sum = 0;

while (number != 0) {

sum += number % 10;

number /= 10;

System.out.println("Sum of digits: " + sum);

7. Area Calculation with Method Overloading

class AreaCalculator {

public double area(double radius) {

return Math.PI * radius * radius; // Area of Circle

public double area(double base, double height) {

return 0.5 * base * height; // Area of Triangle

public double area(double length, double width) {

return length * width; // Area of Rectangle

public static void main(String[] args) {

AreaCalculator calculator = new AreaCalculator();

System.out.println("Area of Circle: " + calculator.area(5));

System.out.println("Area of Triangle: " + calculator.area(5, 10));


System.out.println("Area of Rectangle: " + calculator.area(5, 10));

8. Person Class with Constructors

class Person {

int pid;

String pname;

int age;

String gender;

// Default constructor

public Person() {

this.pid = 0;

this.pname = "";

this.age = 0;

this.gender = "";

// Parameterized constructor

public Person(int pid, String pname, int age, String gender) {

this.pid = pid;

this.pname = pname;

this.age = age;

this.gender = gender;

public void display() {

System.out.println("ID: " + pid + ", Name: " + pname + ", Age: " + age + ", Gender: " + gender);

public static void main(String[] args) {

Person[] persons = new Person[5];

for (int i = 0; i < 5; i++) {


persons[i] = new Person(i + 1, "Person" + (i + 1), 20 + i, i % 2 == 0 ? "Male" : "Female");

persons[i].display();

9. Product Class with Array of Objects

import java.util.Scanner;

class Product {

int pid;

String pname;

double price;

public void accept() {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter Product ID:");

pid = scanner.nextInt();

System.out.println("Enter Product Name:");

pname = scanner.next();

System.out.println("Enter Product Price:");

price = scanner.nextDouble();

public void display() {

System.out.println("ID: " + pid + ", Name: " + pname + ", Price: " + price);

public double calculateTotal(int quantity) {

return quantity * price;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

Product[] products = new Product[3];

for (int i = 0; i < products.length; i++) {

products[i] = new Product();

products[i].accept();

for (Product product : products) {

product.display();

System.out.println("Enter quantity to calculate total:");

int quantity = scanner.nextInt();

System.out.println("Total Amount: " + product.calculateTotal(quantity));

10. Sort Employee Names

import java.util.Scanner;

class Employee {

String name;

public Employee(String name) {

this.name = name;

public String getName() {

return name;

public class SortEmployees {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter number of employees:");

int n = scanner.nextInt();

Employee[] employees = new Employee[n];

for (int i = 0; i < n; i++) {

System.out.println("Enter employee name:");

String name = scanner.next();

employees[i] = new Employee(name);

// Sorting

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - 1 - i; j++) {

if (employees[j].getName().compareTo(employees[j + 1].getName()) > 0) {

// Swap

Employee temp = employees[j];

employees[j] = employees[j + 1];

employees[j + 1] = temp;

// Displaying sorted names

System.out.println("Sorted Employee Names:");

for (Employee emp : employees) {

System.out.println(emp.getName());

11. Cricket Players and Average Calculation

import java.util.Scanner;
class CricketPlayer {

int pid;

String pname;

int totalRuns, inningsPlayed;

CricketPlayer(int pid, String pname, int totalRuns, int inningsPlayed) {

this.pid = pid;

this.pname = pname;

this.totalRuns = totalRuns;

this.inningsPlayed = inningsPlayed;

double average() {

return inningsPlayed == 0 ? 0 : (double) totalRuns / inningsPlayed;

void display() {

System.out.println(pname + " (Average: " + average() + ")");

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter number of players: ");

int n = scanner.nextInt();

CricketPlayer[] players = new CricketPlayer[n];

for (int i = 0; i < n; i++) {

System.out.print("Enter pid, pname, totalRuns, inningsPlayed: ");

players[i] = new CricketPlayer(scanner.nextInt(), scanner.next(), scanner.nextInt(), scanner.nextInt());

CricketPlayer maxAvgPlayer = players[0];

for (CricketPlayer player : players) {

if (player.average() > maxAvgPlayer.average()) {


maxAvgPlayer = player;

System.out.println("Player with maximum average:");

maxAvgPlayer.display();

12. Student Class with this Keyword

import java.util.Scanner;

class Stud {

int sid;

String sname, sclass;

Stud(int sid, String sname, String sclass) {

this.sid = sid;

this.sname = sname;

this.sclass = sclass;

void display() {

System.out.println("ID: " + sid + ", Name: " + sname + ", Class: " + sclass);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter number of students: ");

int n = scanner.nextInt();

Stud[] students = new Stud[n];

for (int i = 0; i < n; i++) {


System.out.print("Enter sid, sname, sclass: ");

students[i] = new Stud(scanner.nextInt(), scanner.next(), scanner.next());

for (Stud student : students) student.display();

13. Shape Class with Area Calculation

abstract class Shape {

abstract double area();

class Rectangle extends Shape {

double length, width;

Rectangle(double length, double width) {

this.length = length;

this.width = width;

double area() {

return length * width;

class Triangle extends Shape {

double base, height;

Triangle(double base, double height) {

this.base = base;

this.height = height;

double area() {

return 0.5 * base * height;

}
}

public class ShapeArea {

public static void main(String[] args) {

Shape rectangle = new Rectangle(5, 10);

Shape triangle = new Triangle(5, 10);

System.out.println("Area of Rectangle: " + rectangle.area());

System.out.println("Area of Triangle: " + triangle.area());

14. Mathematics Package for Maximum and Power

1. Maximum Class:

package Mathematics;

public class Maximum {

public static int max(int a, int b) {

return Math.max(a, b);

2. Power Class:
package Mathematics;

public class Power {


public static double calculatePower(double base, double exponent) {
return Math.pow(base, exponent);
}
}
3. Main Program:
import Mathematics.Maximum;
import Mathematics.Power;
import java.util.Scanner;

public class MathOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int num1 = scanner.nextInt(), num2 = scanner.nextInt();
System.out.println("Maximum: " + Maximum.max(num1, num2));
System.out.print("Enter base and exponent: ");
double base = scanner.nextDouble(), exponent = scanner.nextDouble();
System.out.println("Power: " + Power.calculatePower(base, exponent));
}
}

15. Area Calculation of Cylinder and Circle Using Super Keyword

class Circle {
double radius;
Circle(double radius) {
this.radius = radius;
}
double area() {
return Math.PI * radius * radius;
}
}

class Cylinder extends Circle {


double height;
Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
double volume() {
return area() * height;
}
}

public class AreaCalc {


public static void main(String[] args) {
Circle circle = new Circle(5);
Cylinder cylinder = new Cylinder(5, 10);
System.out.println("Area of Circle: " + circle.area());
System.out.println("Volume of Cylinder: " + cylinder.volume());
}
}

16. Interface Shape with area() method for Circle and Sphere:

interface Shape {
double area();
}

final class Circle implements Shape {


private final double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}
final class Sphere implements Shape {
private final double radius;

public Sphere(double radius) {


this.radius = radius;
}

@Override
public double area() {
return 4 * Math.PI * radius * radius;
}
}

public class Main {


public static void main(String[] args) {
Circle circle = new Circle(5);
Sphere sphere = new Sphere(5);
System.out.println("Area of Circle: " + circle.area());
System.out.println("Area of Sphere: " + sphere.area());
}
}

17. Interface Integer to check if a number is positive or negative:

interface IntegerCheck {
void check(int num);
}

public class NumberCheck implements IntegerCheck {


@Override
public void check(int num) {
if (num >= 0) {
System.out.println("The number is Positive.");
} else {
System.out.println("The number is Negative.");
}
}

public static void main(String[] args) {


NumberCheck obj = new NumberCheck();
obj.check(-5);
}
}

18. Abstract class Shape with calc_area() & calc_volume() for Sphere and Cone:

abstract class Shape {


abstract double calc_area();
abstract double calc_volume();
}

class Sphere extends Shape {


private final double radius;

public Sphere(double radius) {


this.radius = radius;
}

@Override
double calc_area() {
return 4 * Math.PI * radius * radius;
}

@Override
double calc_volume() {
return (4.0 / 3) * Math.PI * radius * radius * radius;
}
}

class Cone extends Shape {


private final double radius;
private final double height;

public Cone(double radius, double height) {


this.radius = radius;
this.height = height;
}

@Override
double calc_area() {
return Math.PI * radius * (radius + Math.sqrt(height * height + radius * radius));
}

@Override
double calc_volume() {
return (1.0 / 3) * Math.PI * radius * radius * height;
}
}

public class Main {


public static void main(String[] args) {
Sphere sphere = new Sphere(5);
Cone cone = new Cone(3, 7);

System.out.println("Sphere Area: " + sphere.calc_area());


System.out.println("Sphere Volume: " + sphere.calc_volume());

System.out.println("Cone Area: " + cone.calc_area());


System.out.println("Cone Volume: " + cone.calc_volume());
}
}

19. Package game with classes Indoor & Outdoor:


package game;

class Indoor {

private String[] players;

public Indoor() {

this.players = new String[]{"Player1", "Player2"};

public Indoor(String[] players) {

this.players = players;

public void display() {

System.out.println("Indoor Players: ");

for (String player : players) {

System.out.println(player);

class Outdoor {

private String[] players;

public Outdoor() {

this.players = new String[]{"PlayerA", "PlayerB"};

public Outdoor(String[] players) {

this.players = players;

public void display() {

System.out.println("Outdoor Players: ");


for (String player : players) {

System.out.println(player);

public class Main {

public static void main(String[] args) {

Indoor indoor = new Indoor();

indoor.display();

Outdoor outdoor = new Outdoor(new String[]{"PlayerX", "PlayerY"});

outdoor.display();

20. Check voting eligibility

import java.util.Scanner;

class VotingAgeException extends Exception {

VotingAgeException(String msg) { super(msg); }

public class VotingEligibility {

public static void main(String[] args) {

try {

System.out.print("Enter age: ");

int age = new Scanner(System.in).nextInt();

if (age < 18) throw new VotingAgeException("Not eligible to vote");

System.out.println("Eligible to vote");

} catch (VotingAgeException e) {

System.out.println(e.getMessage());

}
21. Check palindrome and handle exceptions

import java.util.Scanner;

class ZeroException extends Exception {

ZeroException(String msg) { super(msg); }

public class PalindromeCheck {

public static void main(String[] args) {

try {

System.out.print("Enter number: ");

String input = new Scanner(System.in).next();

int num = Integer.parseInt(input);

if (num == 0) throw new ZeroException("Number is zero");

String reversed = new StringBuilder(input).reverse().toString();

System.out.println(input.equals(reversed) ? "Palindrome" : "Not Palindrome");

} catch (NumberFormatException e) {

System.out.println("Invalid number");

} catch (ZeroException e) {

System.out.println(e.getMessage());

22. Sum digits with custom exception

class OutOfRangeException extends Exception {

OutOfRangeException(String msg) { super(msg); }

public class SumOfDigits {

public static void main(String[] args) {

try {

int num = 101; // replace with user input if needed

if (num > 100) throw new OutOfRangeException("Number out of range");

int sum = 0;
for (char digit : String.valueOf(num).toCharArray()) sum += digit - '0';

System.out.println("Sum of digits: " + sum);

} catch (OutOfRangeException e) {

System.out.println(e.getMessage());

23. File copy with case change and digit replacement

import java.io.*;

public class FileCopy {

public static void main(String[] args) throws IOException {

BufferedReader reader = new BufferedReader(new FileReader("source.txt"));

BufferedWriter writer = new BufferedWriter(new FileWriter("target.txt"));

int ch;

while ((ch = reader.read()) != -1) {

char c = (char) ch;

writer.write(Character.isDigit(c) ? '*' :

Character.isUpperCase(c) ? Character.toLowerCase(c) :

Character.toUpperCase(c));

reader.close(); writer.close();

24. Delete .txt files and show remaining info

import java.io.File;

public class DeleteTxtFiles {

public static void main(String[] args) {

for (String name : args) {

File file = new File(name);

if (file.exists() && name.endsWith(".txt")) {

file.delete();

System.out.println("Deleted: " + name);


} else {

System.out.println(file.getName() + " | " + file.getAbsolutePath() + " | " + file.length() + " bytes");

25. Applet drawing a centered circle with name

import java.applet.Applet;

import java.awt.Graphics;

public class CircleApplet extends Applet {

public void paint(Graphics g) {

int w = 500, h = 300, r = 100;

setSize(w, h);

g.drawOval(w/2 - r, h/2 - r, 2 * r, 2 * r);

g.drawString("Ashish", w / 2 - 20, h / 2);

26. Frame handling mouse events

import java.awt.*;

import java.awt.event.*;

public class MouseEventFrame extends Frame implements MouseListener {

public MouseEventFrame() { setSize(400, 300); addMouseListener(this); }

public void mouseEntered(MouseEvent e) { setVisible(true); }

public void mouseExited(MouseEvent e) { setVisible(false); }

public void mouseClicked(MouseEvent e) { System.out.println("Mouse Clicked"); }

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public static void main(String[] args) { new MouseEventFrame().setVisible(false); }

27. Frame with pink background and string display


import java.awt.*;

public class PinkFrame extends Frame {

public PinkFrame() { setSize(400, 300); setBackground(Color.PINK); setVisible(true); }

public void paint(Graphics g) { g.drawString("Hello, World!", 150, 150); }

public static void main(String[] args) { new PinkFrame(); }

28. Arithmetic calculator with basic validation

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

double num1 = sc.nextDouble(), num2 = sc.nextDouble();

char op = sc.next().charAt(0);

System.out.println(op == '+' ? num1 + num2 :

op == '-' ? num1 - num2 :

op == '*' ? num1 * num2 :

op == '/' && num2 != 0 ? num1 / num2 : "Invalid operation");

sc.close();

29. Applet drawing a simple temple

import java.applet.Applet;

import java.awt.Graphics;

public class TempleApplet extends Applet {

public void paint(Graphics g) {

g.drawLine(100, 150, 200, 50); g.drawLine(200, 50, 300, 150); // Roof

g.drawRect(150, 150, 100, 150); // Base

g.drawRect(190, 220, 20, 80); // Door

}
}

30. Write a java program to display following screen

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class InterestCalculatorCompact extends JFrame implements ActionListener {

JTextField txtPrinciple = new JTextField(), txtInterestRate = new JTextField(),

txtYears = new JTextField(), txtTotalAmount = new JTextField(),

txtInterestAmount = new JTextField();

JButton btnCalculate = new JButton("Calculate"), btnClear = new JButton("Clear"), btnClose = new


JButton("Close");

public InterestCalculatorCompact() {

setTitle("Interest Calculator");

setLayout(new GridLayout(6, 2, 10, 10));

add(new JLabel("Principle Amount")); add(txtPrinciple);

add(new JLabel("Interest Rate")); add(txtInterestRate);

add(new JLabel("No. of Years")); add(txtYears);

add(new JLabel("Total Amount")); add(txtTotalAmount); txtTotalAmount.setEditable(false);

add(new JLabel("Interest Amount")); add(txtInterestAmount); txtInterestAmount.setEditable(false);

add(btnCalculate); add(btnClear); add(btnClose);

btnCalculate.addActionListener(this); btnClear.addActionListener(this); btnClose.addActionListener(this);

setSize(350, 250); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent e) {

if (e.getSource() == btnCalculate) {

try {

double p = Double.parseDouble(txtPrinciple.getText()), r = Double.parseDouble(txtInterestRate.getText());

int y = Integer.parseInt(txtYears.getText());

double interest = (p * r * y) / 100, total = p + interest;


txtInterestAmount.setText(String.valueOf(interest));

txtTotalAmount.setText(String.valueOf(total));

} catch (Exception ex) {

JOptionPane.showMessageDialog(this, "Invalid input!");

} else if (e.getSource() == btnClear) {

txtPrinciple.setText(""); txtInterestRate.setText(""); txtYears.setText("");

txtTotalAmount.setText(""); txtInterestAmount.setText("");

} else if (e.getSource() == btnClose) dispose();

public static void main(String[] args) {

new InterestCalculatorCompact();

You might also like