You are on page 1of 19

1.

Write a program with a method named getTotal that accepts two integers as an
argument and return its sum. Call this method from main( ) and print the results.

public class SumCalculator {

public static int getTotal(int num1, int num2) {

return num1 + num2;

public static void main(String[] args) {

int num1 = 10;

int num2 = 20;

int sum = getTotal(num1, num2);

System.out.println("The sum is: " + sum);

The sum is: 30

2. Write a method named isEven that accepts an int argument. The method should
return true if the argument is even, or false otherwise. Also write a program to test
your method

public class EvenNumberChecker {

public static boolean isEven(int number) {

return number % 2 == 0;

public static void main(String[] args) {

int number1 = 10;

int number2 = 7;

boolean isNumber1Even = isEven(number1);

System.out.println(number1 + " is even: " + isNumber1Even);


boolean isNumber2Even = isEven(number2);

System.out.println(number2 + " is even: " + isNumber2Even);

10 is even: true

7 is even: false

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

public class ArrayAverageCalculator {

public static double calculateAverage(int[] array) {

int sum = 0;

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

sum += array[i];

return (double) sum / array.length;

public static void main(String[] args) {

int[] numbers = {5, 10, 15, 20, 25};

double average = calculateAverage(numbers);

System.out.println("The average value is: " + average);

The average value is: 15.0


4. In tabular form, differentiate between Object-Oriented Programming and Structural
Programming

Object-Oriented Programming
Feature (OOP) Structural Programming

Approach Based on objects and classes Based on procedures and functions

Fundamental Unit Object Function

Separated into data structures and


Data and Behavior Encapsulated together in objects functions

Organized around objects and their Organized around functions and


Code Organization interactions control structures

Achieved through classes and Achieved through functions and


Modularity objects subroutines

Supports inheritance and code


Inheritance reuse Does not support inheritance

Supports polymorphism and


Polymorphism dynamic method dispatch Does not support polymorphism
Object-Oriented Programming
Feature (OOP) Structural Programming

Encourages encapsulation and


Data Hiding information hiding No specific support for data hiding

Promotes code reusability through Code reuse may be limited to


Code Reusability class inheritance function libraries

Complexity Handles complexity through Handles complexity through


Management abstraction and modularity procedural decomposition

Examples Java, C++, Python, C# C, Pascal, Fortran, Assembly

5. Write a Java program to sum values (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) of an array.

public class ArraySum {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int sum = 0;

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

sum += numbers[i];

System.out.println("The sum of the array elements is: " + sum);


}

The sum of the array elements is: 55

6. Write a Java program to sort a numeric array and a string array. The output should
print out: Original numeric array : [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254,
1472, 2365, 1456, 2165, 1457, 2456] Sorted numeric array : [1254, 1456, 1456, 1457,
1458, 1472, 1789, 1899, 2013, 2035, 2165, 2365, 2456, 2458] Original string array :
[Java, Python, PHP, C#, C Programming, C++] Sorted string array : [C Programming,
C#, C++, Java, PHP, Python]

import java.util.Arrays;

public class ArraySorting {

public static void main(String[] args) {

int[] numericArray = {1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365, 1456, 2165,
1457, 2456};

String[] stringArray = {"Java", "Python", "PHP", "C#", "C Programming", "C++"};

// Sort numeric array

Arrays.sort(numericArray);

// Sort string array

Arrays.sort(stringArray);

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

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

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

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

}
Original numeric array: [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365, 1456, 2165,
1457, 2456]

Sorted numeric array: [1254, 1456, 1456, 1457, 1458, 1472, 1789, 1899, 2013, 2035, 2165, 2365,
2456, 2458]

Original string array: [Java, Python, PHP, C#, C Programming, C++]

Sorted string array: [C Programming, C#, C++, Java, PHP, Python]

7. Write JAVA code that creates a new JFrame object and sets its size. The code should
then create a new JButton and JLabel object, and adds them to the frame using the
add method. The layout manager of the frame should be set to FlowLayout, which
arranges the components in a horizontal row. Finally, the default close operation of
the frame is set to EXIT_ON_CLOSE, and the frame is made visible using the setVisible
method

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import java.awt.FlowLayout;

public class JFrameExample {

public static void main(String[] args) {

JFrame frame = new JFrame("JFrame Example");

frame.setSize(300, 200);

JButton button = new JButton("Click Me!");

JLabel label = new JLabel("Hello, JFrame!");

frame.setLayout(new FlowLayout());

frame.add(button);

frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

8. Revenue can be calculated as the selling price of the product times the quantity sold,
i.e., revenue = price × quantity. Write a program that asks the user to enter product
price and quantity and then calculate the revenue. If the revenue is more than 5000 a
discount is 10% offered. Program should display the discount and net revenue.

import java.util.Scanner;

public class RevenueCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the product price: ");

double price = scanner.nextDouble();

System.out.print("Enter the quantity sold: ");

int quantity = scanner.nextInt();

double revenue = price * quantity;

double discount = 0.0;

double netRevenue = revenue;

if (revenue > 5000) {

discount = 0.1 * revenue;

netRevenue = revenue - discount;

}
System.out.println("Revenue: $" + revenue);

System.out.println("Discount: $" + discount);

System.out.println("Net Revenue: $" + netRevenue);

scanner.close();

Enter the product price: 10.50

Enter the quantity sold: 600

Revenue: $6300.0

Discount: $630.0

Net Revenue: $5670.0

9. Write a JAVA code that create a JFrame object called frame with the title "Add Two
Numbers". It also creates a JLabel object called resultLabel to display the result of the
addition operation, and two JTextField objects called num1Field and num2Field to
input the two numbers.

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JTextField;

import java.awt.FlowLayout;

public class AddTwoNumbers {

public static void main(String[] args) {

JFrame frame = new JFrame("Add Two Numbers");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new FlowLayout());

JLabel resultLabel = new JLabel("Result: ");


JTextField num1Field = new JTextField(10);

JTextField num2Field = new JTextField(10);

frame.add(num1Field);

frame.add(num2Field);

frame.add(resultLabel);

frame.pack();

frame.setVisible(true);

10. The code then creates a JButton object called addButton with the label "Add" and
add an ActionListener to it by passing this (the current object, which implements the
ActionListener interface) to its addActionListener method. When the button is clicked,
the actionPerformed method is called, which gets the values from the text fields, adds
them, and displays the result in the resultLabel.

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JTextField;

import javax.swing.JButton;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class AddTwoNumbers implements ActionListener {

private JFrame frame;

private JTextField num1Field;

private JTextField num2Field;

private JLabel resultLabel;


public AddTwoNumbers() {

frame = new JFrame("Add Two Numbers");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new FlowLayout());

num1Field = new JTextField(10);

num2Field = new JTextField(10);

resultLabel = new JLabel("Result: ");

JButton addButton = new JButton("Add");

addButton.addActionListener(this);

frame.add(num1Field);

frame.add(num2Field);

frame.add(addButton);

frame.add(resultLabel);

frame.pack();

frame.setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

try {

double num1 = Double.parseDouble(num1Field.getText());

double num2 = Double.parseDouble(num2Field.getText());

double sum = num1 + num2;

resultLabel.setText("Result: " + sum);

} catch (NumberFormatException ex) {

resultLabel.setText("Error: Invalid Input");


}

public static void main(String[] args) {

new AddTwoNumbers();

11. create a JPanel object called panel to hold the components, set its layout to
GridLayout, and add the components to it. Add the panel to the frame using the add
method.

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JTextField;

import javax.swing.JButton;

import javax.swing.JPanel;

import java.awt.FlowLayout;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class AddTwoNumbers implements ActionListener {

private JFrame frame;

private JTextField num1Field;

private JTextField num2Field;

private JLabel resultLabel;

public AddTwoNumbers() {

frame = new JFrame("Add Two Numbers");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new FlowLayout());

num1Field = new JTextField(10);

num2Field = new JTextField(10);

resultLabel = new JLabel("Result: ");

JButton addButton = new JButton("Add");

addButton.addActionListener(this);

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 1));

panel.add(num1Field);

panel.add(num2Field);

panel.add(addButton);

panel.add(resultLabel);

frame.add(panel);

frame.pack();

frame.setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

try {

double num1 = Double.parseDouble(num1Field.getText());

double num2 = Double.parseDouble(num2Field.getText());

double sum = num1 + num2;

resultLabel.setText("Result: " + sum);

} catch (NumberFormatException ex) {


resultLabel.setText("Error: Invalid Input");

public static void main(String[] args) {

new AddTwoNumbers();

12. Set the default close operation of the frame to JFrame.EXIT_ON_CLOSE, set its size to
300x200 pixels, and make it visible using the setVisible method. Finally, create a new
AddTwoNumbersGUI object in the main method to start the GUI.

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JTextField;

import javax.swing.JButton;

import javax.swing.JPanel;

import java.awt.FlowLayout;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class AddTwoNumbersGUI implements ActionListener {

private JFrame frame;

private JTextField num1Field;

private JTextField num2Field;

private JLabel resultLabel;


public AddTwoNumbersGUI() {

frame = new JFrame("Add Two Numbers");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new FlowLayout());

frame.setSize(300, 200);

num1Field = new JTextField(10);

num2Field = new JTextField(10);

resultLabel = new JLabel("Result: ");

JButton addButton = new JButton("Add");

addButton.addActionListener(this);

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 1));

panel.add(num1Field);

panel.add(num2Field);

panel.add(addButton);

panel.add(resultLabel);

frame.add(panel);

frame.setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

try {

double num1 = Double.parseDouble(num1Field.getText());

double num2 = Double.parseDouble(num2Field.getText());


double sum = num1 + num2;

resultLabel.setText("Result: " + sum);

} catch (NumberFormatException ex) {

resultLabel.setText("Error: Invalid Input");

public static void main(String[] args) {

AddTwoNumbersGUI calculator = new AddTwoNumbersGUI();

13. Write JAVA codes to create chat frame

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class ChatFrame extends JFrame implements ActionListener {

private JTextArea chatArea;

private JTextField messageField;

public ChatFrame() {

setTitle("Chat Frame");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

// Create the chat area


chatArea = new JTextArea();

chatArea.setEditable(false);

JScrollPane scrollPane = new JScrollPane(chatArea);

add(scrollPane, BorderLayout.CENTER);

// Create the message input field

messageField = new JTextField();

messageField.addActionListener(this);

add(messageField, BorderLayout.SOUTH);

// Create the send button

JButton sendButton = new JButton("Send");

sendButton.addActionListener(this);

add(sendButton, BorderLayout.EAST);

pack();

setLocationRelativeTo(null);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

String message = messageField.getText();

if (!message.isEmpty()) {

chatArea.append("You: " + message + "\n");

messageField.setText("");

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
@Override

public void run() {

new ChatFrame();

});

14. Write a program that asks for a temperature in Celsius and prints out the
temperature in Fahrenheit. Use InputBox for input and OutputBox for output. The
formula to convert Celsius to the equivalent Fahrenheit is: fahrenheit = 1.8 x celsius +
32

import javax.swing.JOptionPane;

public class TemperatureConverter {

public static void main(String[] args) {

// Ask for input using InputBox

String celsiusString = JOptionPane.showInputDialog(null, "Enter temperature in Celsius:",


"Temperature Converter", JOptionPane.QUESTION_MESSAGE);

// Convert input to double

double celsius = Double.parseDouble(celsiusString);

// Calculate Fahrenheit

double fahrenheit = 1.8 * celsius + 32;

// Prepare the output message

String outputMessage = String.format("%.2f Celsius = %.2f Fahrenheit", celsius, fahrenheit);

// Display output using OutputBox


JOptionPane.showMessageDialog(null, outputMessage, "Temperature Converter",
JOptionPane.INFORMATION_MESSAGE);

15. If a triangle has side lengths a,b,c, then the formula for the area of the triangle is area
= √s(s − a)(s − b)(s − c), where = (a + b + c)/2. Write a program that asks the user to
enter three sides of triangle. The progr s am should compute and display the area of
triangle.

import java.util.Scanner;

public class TriangleAreaCalculator {

public static void main(String[] args) {

// Create a Scanner object for user input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the side lengths

System.out.print("Enter the length of side a: ");

double a = scanner.nextDouble();

System.out.print("Enter the length of side b: ");

double b = scanner.nextDouble();

System.out.print("Enter the length of side c: ");

double c = scanner.nextDouble();

// Calculate the semi-perimeter (s)

double s = (a + b + c) / 2;
// Calculate the area using the formula

double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));

// Display the area of the triangle

System.out.println("The area of the triangle is: " + area);

// Close the Scanner

scanner.close();

You might also like