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

java problem

The document contains several Java programming exercises, including sorting arrays, calculating averages, converting between arrays and ArrayLists, and implementing object-oriented concepts like classes, inheritance, and interfaces. It also covers advanced topics such as matrix operations, method overriding, and polymorphism. Each exercise includes code examples and explanations for better understanding.

Uploaded by

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

java problem

The document contains several Java programming exercises, including sorting arrays, calculating averages, converting between arrays and ArrayLists, and implementing object-oriented concepts like classes, inheritance, and interfaces. It also covers advanced topics such as matrix operations, method overriding, and polymorphism. Each exercise includes code examples and explanations for better understanding.

Uploaded by

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

CLASS : -SY BSC(IT) SUBJECT : - JAVA

DATE : - 7/11/2023 ENROLMENT : 2202040601109

1. Write a Java program to sort a numeric array and a string array?

import java.util.Arrays;

public class ArraySorting {

public static void main(String[] args) {

// Sorting a numeric array

int[] numericArray = {5, 2, 9, 1, 5};

Arrays.sort(numericArray);

System.out.println("Sorted numeric array: " + Arrays.toString(numericArray));

// Sorting a string array

String[] stringArray = {"apple", "banana", "cherry", "date", "berry"};

Arrays.sort(stringArray);

System.out.println("Sorted string array: " + Arrays.toString(stringArray));

2. Write a Java program to calculate the average value of array elements.

public class ArrayAverage {

public static void main(String[] args) {

double[] values = {12.5, 7.2, 9.8, 3.6, 6.4};


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

double sum = 0.0;

for (double value : values) {

sum += value;

double average = sum / values.length;

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

3. Write a Java program to convert an array to ArrayList.

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class ArrayToArrayList {

public static void main(String[] args) {

// Create an array of integers

Integer[] array = {1, 2, 3, 4, 5};

// Convert the array to an ArrayList

List<Integer> list = Arrays.asList(array);

ArrayList<Integer> arrayList = new ArrayList<>(list);


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

// Print the ArrayList

System.out.println("ArrayList: " + arrayList);

4. Write a Java program to convert an ArrayList to an array.

import java.util.ArrayList;

public class ArrayListToArray {

public static void main(String[] args) {

// Create an ArrayList of integers

ArrayList<Integer> arrayList = new ArrayList<>();

arrayList.add(1);

arrayList.add(2);

arrayList.add(3);

arrayList.add(4);

arrayList.add(5);

// Convert the ArrayList to an array

Integer[] array = arrayList.toArray(new Integer[0]);

// Print the array

for (Integer element : array) {

System.out.print(element + " ");


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

5. Write a program to Accessing elements from an ArrayList

import java.util.ArrayList;

public class AccessArrayList {

public static void main(String[] args) {

// Create an ArrayList of strings

ArrayList<String> arrayList = new ArrayList<>();

arrayList.add("Apple");

arrayList.add("Banana");

arrayList.add("Cherry");

arrayList.add("Date");

// Access elements from the ArrayList

System.out.println("Accessing elements from the ArrayList:");

for (int i = 0; i < arrayList.size(); i++) {

String element = arrayList.get(i);

System.out.println("Element at index " + i + ": " + element);

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

6. Create a class called 'Matrix' containing a constructor that initializes the


number of rows and number of columns of a new Matrix object. The Matrix
class has the following information:
1.number of rows of matrix
2 number of columns of matrix
3 - elements of matrix in the form of 2D array.
The Matrix class has methods for each of the following:
1 - get the number of rows
2 - get the number of columns
3 - set the elements of the matrix at given position (i,j)
4 - adding two matrices. If the matrices are not addable, "Matrices cannot be
added" will be displayed.
5 - multiplying the two matrices

public class Matrix {

private int numRows;

private int numColumns;

private int[][] elements;

public Matrix(int numRows, int numColumns, int[][] elements) {


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

this.numRows = numRows;

this.numColumns = numColumns;

this.elements = elements;

public int getNumRows() {

return numRows;

public int getNumColumns() {

return numColumns;

public void setElement(int i, int j, int value) {

if (i >= 0 && i < numRows && j >= 0 && j < numColumns) {

elements[i][j] = value;

} else {

System.out.println("Invalid position (" + i + ", " + j + ")");

public static Matrix addMatrices(Matrix matrix1, Matrix matrix2) {

if (matrix1.getNumRows() != matrix2.getNumRows() || matrix1.getNumColumns() !=


matrix2.getNumColumns()) {

System.out.println("Matrices cannot be added.");

return null;

int numRows = matrix1.getNumRows();

int numColumns = matrix1.getNumColumns();

int[][] resultElements = new int[numRows][numColumns];


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

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

for (int j = 0; j < numColumns; j++) {

resultElements[i][j] = matrix1.elements[i][j] + matrix2.elements[i][j];

return new Matrix(numRows, numColumns, resultElements);

public static Matrix multiplyMatrices(Matrix matrix1, Matrix matrix2) {

if (matrix1.getNumColumns() != matrix2.getNumRows()) {

System.out.println("Matrices cannot be multiplied.");

return null;

int numRows = matrix1.getNumRows();

int numColumns = matrix2.getNumColumns();

int[][] resultElements = new int[numRows][numColumns];

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

for (int j = 0; j < numColumns; j++) {

int sum = 0;

for (int k = 0; k < matrix1.getNumColumns(); k++) {

sum += matrix1.elements[i][k] * matrix2.elements[k][j];

resultElements[i][j] = sum;

return new Matrix(numRows, numColumns, resultElements);


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

public void displayMatrix() {

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

for (int j = 0; j < numColumns; j++) {

System.out.print(elements[i][j] + " ");

System.out.println();

public static void main(String[] args) {

int numRows = 2;

int numColumns = 2;

int[][] matrix1Elements = {

{1, 2},

{3, 4}

};

int[][] matrix2Elements = {

{5, 6},

{7, 8}

};

Matrix matrix1 = new Matrix(numRows, numColumns, matrix1Elements);

Matrix matrix2 = new Matrix(numRows, numColumns, matrix2Elements);

System.out.println("Matrix 1:");

matrix1.displayMatrix();

System.out.println("\nMatrix 2:");
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

matrix2.displayMatrix();

System.out.println("\nAdding Matrices:");

Matrix sumMatrix = addMatrices(matrix1, matrix2);

if (sumMatrix != null) {

sumMatrix.displayMatrix();

System.out.println("\nMultiplying Matrices:");

int[][] matrix3Elements = {

{1, 2, 3},

{4, 5, 6}

};

int[][] matrix4Elements = {

{7, 8},

{9, 10},

{11, 12}

};

Matrix matrix3 = new Matrix(2, 3, matrix3Elements);

Matrix matrix4 = new Matrix(3, 2, matrix4Elements);

Matrix productMatrix = multiplyMatrices(matrix3, matrix4);

if (productMatrix != null) {

productMatrix.displayMatrix();

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

7. Write a program that has variables to store Car data like; CarModel,
CarName, CarPrice and CarOwner. The program should include functions to
assign user defined values to the above mentioned variable and a display
function to show the values. Write a main that calls these functions.

public class Car {

private String carModel;

private String carName;

private double carPrice;

private String carOwner;

public void setCarModel(String model) {

carModel = model;

public void setCarName(String name) {


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

carName = name;

public void setCarPrice(double price) {

carPrice = price;

public void setCarOwner(String owner) {

carOwner = owner;

public void displayCarInfo() {

System.out.println("Car Model: " + carModel);

System.out.println("Car Name: " + carName);

System.out.println("Car Price: $" + carPrice);

System.out.println("Car Owner: " + carOwner);

public static void main(String[] args) {

Car myCar = new Car();

// Assign values to car data

myCar.setCarModel("Mahindra Thar");

myCar.setCarName("4x4 M210021");

myCar.setCarPrice(2050000);

myCar.setCarOwner("Rohan sahu");

// Display car information

System.out.println("Car Information:");

myCar.displayCarInfo();

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

8. Write a program to give the example for method overriding concepts

class Animal {

void makeSound() {

System.out.println("Animal makes a generic sound.");

class Dog extends Animal {

@Override

void makeSound() {

System.out.println("Dog barks.");

class Cat extends Animal {

@Override

void makeSound() {

System.out.println("Cat meows.");

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

public class MethodOverridingExample {

public static void main(String[] args) {

Animal animal = new Animal();

Animal dog = new Dog();

Animal cat = new Cat();

animal.makeSound(); // Output: Animal makes a generic sound.

dog.makeSound(); // Output: Dog barks.

cat.makeSound(); // Output: Cat meows.

9. Write a program to create a class named shape. In this class we have three
subclasses: circle, triangle and square. Each class has two member functions
named draw () and erase (). Create these using polymorphism concepts.

class Shape {

void draw() {

System.out.println("Drawing a generic shape");

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

void erase() {

System.out.println("Erasing a generic shape");

class Circle extends Shape {

@Override

void draw() {

System.out.println("Drawing a circle");

@Override

void erase() {

System.out.println("Erasing a circle");

class Triangle extends Shape {

@Override

void draw() {

System.out.println("Drawing a triangle");

@Override

void erase() {

System.out.println("Erasing a triangle");

class Square extends Shape {

@Override
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

void draw() {

System.out.println("Drawing a square");

@Override

void erase() {

System.out.println("Erasing a square");

public class ShapeDemo {

public static void main(String[] args) {

Shape circle = new Circle();

Shape triangle = new Triangle();

Shape square = new Square();

// Polymorphism: Calling draw and erase on different shapes

circle.draw();

circle.erase();

triangle.draw();

triangle.erase();

square.draw();

square.erase();

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

10. Write a program to create interface A. In this interface we have two


methods meth1 and meth2. Implements this interface in another class named
MyClass

interface A {

void meth1();

void meth2();

class MyClass implements A {

@Override

public void meth1() {

System.out.println("Inside meth1 method in MyClass");

@Override

public void meth2() {

System.out.println("Inside meth2 method in MyClass");

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

public class Main {

public static void main(String[] args) {

MyClass myClass = new MyClass();

myClass.meth1();

myClass.meth2();

11. Create an outer class with a function display, again create another class
inside the outer class named inner with a function called display and call the
two functions in the main class.

class Outer {

void display() {

System.out.println("This is the display method in the Outer class");

class Inner {
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

void display() {

System.out.println("This is the display method in the Inner class");

public class Main {

public static void main(String[] args) {

Outer outerObj = new Outer();

outerObj.display();

Outer.Inner innerObj = outerObj.new Inner();

innerObj.display();

12. Write a Java program to perform employee payroll processing using


packages. In the java file, Emp.java creates a package employee and creates a
class Emp. Declare the variables name,empid, category, bpay, hra, da, npay, pf,
grosspay, incometax, and allowance. Calculate the values in methods. Create
another java file Emppay.java. Create an object e to call the methods to
perform and print values.

public class Emp {

String name;
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

int empid;

String category;

double bpay;

double hra;

double da;

double npay;

double pf;

double grosspay;

double incometax;

double allowance;

public void calculatePayroll() {

npay = bpay + hra + da;

pf = 0.12 * npay; // Assuming 12% of basic pay for PF

grosspay = npay - pf;

incometax = 0.1 * grosspay; // Assuming 10% income tax

allowance = 0.05 * npay; // Assuming 5% of basic pay as allowance

//ANOTHER FILE FOR EMPFILE

public class Emppay {

public static void main(String[] args) {

Emp e = new Emp();

e.name = "John";

e.empid = 101;

e.category = "Manager";

e.bpay = 50000;

e.hra = 0.2 * e.bpay;


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

e.da = 0.1 * e.bpay;

e.calculatePayroll();

System.out.println("Employee Name: " + e.name);

System.out.println("Employee ID: " + e.empid);

System.out.println("Employee Category: " + e.category);

System.out.println("Basic Pay: " + e.bpay);

System.out.println("HRA: " + e.hra);

System.out.println("DA: " + e.da);

System.out.println("Net Pay: " + e.npay);

System.out.println("PF Deduction: " + e.pf);

System.out.println("Gross Pay: " + e.grosspay);

System.out.println("Income Tax Deduction: " + e.incometax);

System.out.println("Allowance: " + e.allowance);

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

13. Write a program in Java such that it accepts a number and displays the
square of the number 12 using applet. Create an input text field to accept a
number from user. Create a button to confirm the number and calculate its
square. When the button is clicked, display its square in a text field.

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JTextField;

public class SquareCalculator extends JFrame implements ActionListener {

private JTextField numberField, resultField;

private JButton calculateButton;

public SquareCalculator() {

setTitle("Calculate Square");

setLayout(null);

JLabel inputLabel = new JLabel("Enter a number:");

inputLabel.setBounds(20, 20, 120, 20);

add(inputLabel);

numberField = new JTextField();

numberField.setBounds(150, 20, 100, 20);

add(numberField);

calculateButton = new JButton("Calculate Square");

calculateButton.setBounds(20, 60, 230, 30);

calculateButton.addActionListener(this);
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

add(calculateButton);

JLabel resultLabel = new JLabel("Square result:");

resultLabel.setBounds(20, 110, 120, 20);

add(resultLabel);

resultField = new JTextField();

resultField.setBounds(150, 110, 100, 20);

resultField.setEditable(false);

add(resultField);

public void actionPerformed(ActionEvent e) {

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

try {

String inputText = numberField.getText();

double number = Double.parseDouble(inputText);

double square = number * number;

resultField.setText(String.valueOf(square));

} catch (NumberFormatException ex) {

resultField.setText("Invalid Input");

public static void main(String[] args) {

SquareCalculator calculator = new SquareCalculator();

calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

calculator.setSize(280, 180);

calculator.setVisible(true);

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

14. Build and run "simple calculator " using swing.

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SimpleCalculator extends JFrame implements ActionListener {

private JTextField display;

private double num1, num2;

private char operator;

public SimpleCalculator() {

setTitle("Simple Calculator");

setSize(300, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

display = new JTextField();

display.setHorizontalAlignment(JTextField.RIGHT);

display.setEditable(false);

JPanel buttonPanel = new JPanel(new GridLayout(4, 4));

String[] buttonLabels = {

"7", "8", "9", "/",

"4", "5", "6", "*",

"1", "2", "3", "-",

"0", "C", "=", "+"

};

for (String label : buttonLabels) {

JButton button = new JButton(label);

button.addActionListener(this);

buttonPanel.add(button);

add(display, BorderLayout.NORTH);

add(buttonPanel);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if (command.matches("[0-9]")) {

display.setText(display.getText() + command);
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

} else if (command.equals("C")) {

display.setText("");

num1 = 0;

num2 = 0;

operator = ' ';

} else if (command.equals("=")) {

num2 = Double.parseDouble(display.getText());

double result = calculate(num1, num2, operator);

display.setText(String.valueOf(result));

num1 = result;

num2 = 0;

operator = ' ';

} else if (command.matches("[+\\-*/]")) {

num1 = Double.parseDouble(display.getText());

operator = command.charAt(0);

display.setText("");

private double calculate(double num1, double num2, char operator) {

switch (operator) {

case '+':

return num1 + num2;

case '-':

return num1 - num2;

case '*':

return num1 * num2;

case '/':

if (num2 != 0) {

return num1 / num2;

} else {
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

JOptionPane.showMessageDialog(this, "Cannot divide by zero");

return 0;

default:

return num2;

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new SimpleCalculator());

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

15. Build and run “Simple registration page” using Swing


import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SimpleRegistrationPage extends JFrame implements ActionListener {

private JTextField usernameField;

private JPasswordField passwordField;


CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

private JTextField emailField;

private JButton registerButton;

public SimpleRegistrationPage() {

setTitle("Simple Registration Page");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel(new GridLayout(4, 2));

JLabel usernameLabel = new JLabel("Username:");

usernameField = new JTextField();

JLabel passwordLabel = new JLabel("Password:");

passwordField = new JPasswordField();

JLabel emailLabel = new JLabel("Email:");

emailField = new JTextField();

registerButton = new JButton("Register");

registerButton.addActionListener(this);

panel.add(usernameLabel);

panel.add(usernameField);

panel.add(passwordLabel);

panel.add(passwordField);

panel.add(emailLabel);

panel.add(emailField);

panel.add(registerButton);

add(panel);
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

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

String username = usernameField.getText();

String password = new String(passwordField.getPassword());

String email = emailField.getText();

// You can add your registration logic here

// For this example, we will simply display the entered values

JOptionPane.showMessageDialog(this, "Registered with:\nUsername: " + username + "\


nEmail: " + email);

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new SimpleRegistrationPage());

}
CLASS : -SY BSC(IT) SUBJECT : - JAVA
DATE : - 7/11/2023 ENROLMENT : 2202040601109

You might also like