[go: up one dir, main page]

0% found this document useful (0 votes)
1 views34 pages

Java R23 Merged

The document outlines a series of Java lab exercises, each with specific aims, algorithms, and programs. Exercises include converting Celsius to Fahrenheit, finding the largest number, implementing command line arguments, calculating marks, sorting names, using constructors, method overloading, inheritance, and interfaces. Each exercise is structured with a clear aim, step-by-step algorithm, and corresponding Java code, demonstrating fundamental programming concepts.

Uploaded by

lyricglimplse
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)
1 views34 pages

Java R23 Merged

The document outlines a series of Java lab exercises, each with specific aims, algorithms, and programs. Exercises include converting Celsius to Fahrenheit, finding the largest number, implementing command line arguments, calculating marks, sorting names, using constructors, method overloading, inheritance, and interfaces. Each exercise is structured with a clear aim, step-by-step algorithm, and corresponding Java code, demonstrating fundamental programming concepts.

Uploaded by

lyricglimplse
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/ 34

JAVA LAB EXERCISE PROGRAM

PART A

EX.NO:1 CELSIUS TO FAHRENHEIT CONVERSION

Aim: To write a program to read the temperature in celsius and


convert into Fahrenheit.

Algorithm:

1. Open Netbeans IDE.


2. Select File -> New project and rename the project as
‘CelsiusToFahrenheit’ and click ‘Finish’.
3. Import the package java.io.*.
4. Read the value of Celsius.
5. Convert it into Fahrenheit using the formula
‘Fahrenheit=(1.8*Celsius)+32;’
6. Print the Fahrenheit.
7. Save the program by clicking Ctrl+S.
8. Run the project by clicking Run->Run Project.

Program:

import java.util.Scanner;

public class CelsiusToFahrenheit {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter temperature in Celsius: ");

double celsius = input.nextDouble();

double fahrenheit = (1.8 * celsius) + 32;

System.out.println("Temperature in Fahrenheit: " + fahrenheit);

}
}

Output:

Result:

Thus, the program to convert Celsius to Fahrenheit is executed


successfully.
Ex. No: 2 FIND THE LARGEST NUMBER

Aim: To write a program to read 2 integers and find the largest number using
conditional operator.

Algorithm:

1. Open Netbeans IDE.


2. Select File->New project and rename the project as
‘LargestNumber’ and click ‘Finish’.
3. Import the package java.util.*.
4. Read the value of first and second number.
5. Compute the largest of two number using conditional operator “?:”.
6. Print the largest number.
7. Save the program by clicking Ctrl+S.
8. Run the project by clicking Run->RunProject.

Program:

import java.util.Scanner;

public class LargestNumber {

public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);

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

int num1 = scanner.nextInt();

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

int num2 = scanner.nextInt();

int largest = (num1 > num2) ? num1 : num2;

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


}

Output:

Result:

Thus, the program to calculate the largest number is executed successfully.


Ex. No: 3 COMMAND LINE ARGUMENTS

Aim: To write a program to implement command line arguments.

Algorithm:
1. Open Netbeans IDE.
2. Select File -> New project and rename the project as
‘CommandLineArguments’ and click ‘Finish’.
3. Read the value of radius of circle from command line.
4. Compute the area of the circle using the formula 3.14*radius*radius.
5. Print the area of the circle.
6. Right click the project folder and click ‘Properties’. Select ‘Run’ under
‘Categories’ and enter area of the circle in ‘Arguments’ and click ‘Ok’.
7. Save the program by clicking Ctrl+S.
8. Run the project by clicking Run->Run Project.

Program:

public class CommandLineArgument

public static void main(String args[])

double radius;

double area;

radius=Double.parseDouble(args[0]);

area=3.14*radius*radius;

System.out.println("Area of the circle is: "+ area);

}
Output:
Result:

Thus, the program to implement command line argument is executed


successfully.
Ex. No: 4 SUM AND AVERAGE OF TENTH STANDARD MARKS

Aim: To write a program to find the sum and average of tenth standard marks.

Algorithm:
1. Open Netbeans IDE.
2. Select File -> New project and rename the project as ‘MarksCalculator’ and
click ‘Finish’.
3. Read the number of subjects.
4. Read the marks of all subjects using ‘for’ loop.
5. Calculate the total mark by summing up the marks of all the subject.
6. Calculate the average by dividing the total marks by the number of subjects.
7. Print the total marks and the average.
8. Save the program by clicking Ctrl+S.
9. Run the project by clicking Run->Run Project.

Program:

import java.util.Scanner;

public class MarksCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int numberOfSubjects = scanner.nextInt();

int sum = 0;

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

System.out.print("Enter the marks for subject " + i + ": ");

int marks = scanner.nextInt();

sum += marks;

double average = (double) sum / numberOfSubjects;


System.out.println("\nTotal Marks: " + sum);

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

Output:
Result:

Thus, the program to find the sum and average of tenth standard marks is
executed successfully.
Ex. No: 5 BUBBLE SORT

Aim: To write a Java Program to sort 10 student names in alphabetical order


using bubble sort.

Algorithm:
1. Open Netbeans IDE.
2. Select File -> New project and rename the project as ‘BubbleSort’ and
click ‘Finish’.
3. Initialization:
• Start with the first element in the array.
• Assume the array has n elements.
4. Pass-Through the List:
• For each element in the array (from the first to the second
last):
• Compare the current element with the next element.
• If the current element is greater than the next element,
swap them.
5. Repeat Passes:
• Repeat the above step for all elements in the array.
• After each pass, the largest unsorted element will have
“bubbled up” to its correct position at the end of the array.
• Decrease the range of comparison by one each time (since
the last elements are already sorted).
6. Stop When Sorted:
• Continue repeating the passes until no more swaps are
needed (i.e., the array is sorted).
7. Save the program by clicking Ctrl+S.
8. Run the project by clicking Run->Run Project.

Program:

import java.util.Scanner;

public class BubbleSort {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String[] names = new String[10];


System.out.println("Enter 10 student names:");

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

System.out.print("Name " + (i + 1) + ": ");

names[i] = scanner.nextLine();

for (int i = 0; i < names.length - 1; i++) {

for (int j = 0; j < names.length - 1 - i; j++) {

if (names[j].compareToIgnoreCase(names[j + 1]) > 0) {

String temp = names[j];

names[j] = names[j + 1];

names[j + 1] = temp;

System.out.println("\nStudent names in alphabetical order:");

for (String name : names) {

System.out.println(name);

}
Output:

Result:

Thus, the program to sort 10 student names in alphabetical order using


bubble sort is executed successfully and the output is verified.
Ex. No: 6 STUDENT DETAILS USING CONSTRUCTOR

Aim: To write a Java program to collect student details using constructor.

Algorithm:
1. Open Netbeans IDE.
2. Select File -> New project and rename the project as ‘StudentDetails’
and click ‘Finish’.
3. Define the Student class with student details such as name, rollnumber,
grade and marks etc.
4. Define the Constructor to initialize the student details.
5. Define the method to display the student details.
6. Define the Main class StudentDetails and read the student details.
7. Create the student object using the constructor.
8. Display the student details using the display() method.
9. Save the program by clicking Ctrl+S.
10. Run the project by clicking Run->Run Project.

Program:

import java.util.Scanner;

class Student {

private String name;


private int rollNumber;
private String grade;
private double marks;

public Student(String name, int rollNumber, String grade, double marks) {


this.name = name;
this.rollNumber = rollNumber;
this.grade = grade;
this.marks = marks;
}

public void displayDetails() {


System.out.println("\nStudent Details:");
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Grade: " + grade);
System.out.println("Marks: " + marks);
}
}

public class StudentDetails {

public static void main(String[] args) {


// TODO code application logic here
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Student Name: ");
String name = scanner.nextLine();
System.out.print("Enter Roll Number: ");
int rollNumber = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Grade: ");
String grade = scanner.nextLine();
System.out.print("Enter Marks: ");
double marks = scanner.nextDouble();
Student student = new Student(name, rollNumber, grade, marks);
student.displayDetails();

}
Output:

Result:

Thus, the program to collect student details using constructor is executed


successfully.
Ex. No: 7 METHOD OVERLOADING

Aim: To write a Java program to calculate area of rectangle, triangle and square
using method overloading.

Algorithm:
1. Open Netbeans IDE.
2. Select File -> New project and rename the project as
‘MethodOverloadingExample’ and click ‘Finish’.
3. Define the class AreaCalculator.
4. Define the method calculateArea() to calculate area of the rectangle
using the formula length * breadth.
5. Define the method calculateArea() to calculate area of the triangle using
the formula 0.5 * base * height.
6. Define the method calculateArea() to calculate area of the square using
the formula side * side.
7. In the main method of ‘MethodOverloadingExample’ class, create an
object for ‘AreaCalculator’ class using new operator.
8. Call the calculateArea() method using dot operator to calculate area of
the rectangle and print the ‘rectangleArea’.
9. Call the calculateArea() method using dot operator to calculate area of
the triangle and print the ‘triangleArea’.
10. Call the calculateArea() method using dot operator to calculate area of
the square and print the ‘squareArea’.
11. Save the program by clicking Ctrl+S.
12. Run the project by clicking Run->Run Project.

Program:

class AreaCalculator {

public double calculateArea(double length, double breadth) {


return length * breadth;
}

public double calculateArea(double base, double height, boolean isTriangle) {


return 0.5 * base * height;
}

public double calculateArea(double side) {


return side * side;
}
}

public class MethodOverloadingExample {

public static void main(String[] args) {


AreaCalculator calculator = new AreaCalculator();
double rectangleArea = calculator.calculateArea(10.5, 7.0);
System.out.println("Area of Rectangle: " + rectangleArea);
double triangleArea = calculator.calculateArea(8.0, 5.0, true);
System.out.println("Area of Triangle: " + triangleArea);
double squareArea = calculator.calculateArea(4.5);
System.out.println("Area of Square: " + squareArea);

}
Output:

Result:

Thus, the program to calculate area of rectangle, triangle and square


using method overloading is executed successfully.
Ex. No: 8 INHERITANCE

Aim: To Write a Java program to create a class called Shape with methods
called getPerimeter() and getArea(). Create a subclass called Circle that
overrides the getPerimeter() and getArea() methods to calculate the area and
perimeter of a circle.

Algorithm:
1. Open Netbeans IDE.
2. Select File -> New project and rename the project as ‘ShapeDemo’ and
click ‘Finish’.
3. Define the Base class ‘Shape’ and define the methods baseMethod(),
getPerimeter() and getArea().
4. Define the Subclass ‘Circle’ and extend it from ‘Shape’ class using
‘extends’ keyword.
5. Define the constructor for the subclass ‘Circle’ to initialize the radius.
6. Define the getPerimeter() method to calculate perimeter of the circle
using the formula 2* Math.PI * radius.
7. Define the getArea() method to calculate area of the circle using the
formula Math.PI * radius * radius.
8. Define the Main class ‘ShapeDemo’ and create the object for the ‘Circle’
by passing radius.
9. Print the radius of the Circle.
10. Print the perimeter of the circle by calling the circle.getPerimeter()
method using ‘dot’ operator .
11. Print the area of the circle by using call circle.getArea() method using
‘dot’ operator.
12. Save the program by clicking Ctrl+S.
13. Run the project by clicking Run->Run Project.

Program:

package shapedemo;

class Shape {

public void baseMethod(){

System.out.println("Base Method is called");

}
public double getPerimeter() {

return 0.0;

public double getArea() {

return 0.0;

class Circle extends Shape {

private double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double getPerimeter() {

return 2 * Math.PI * radius;

@Override

public double getArea() {

return Math.PI * radius * radius;

public class ShapeDemo {

public static void main(String[] args) {

// TODO code application logic here


Circle circle = new Circle(5.0);

System.out.println("Circle Radius: " + 5);

circle.baseMethod();

System.out.println("Circle Perimeter: " + circle.getPerimeter());

System.out.println("Circle Area: " + circle.getArea());

}
Output:
Result:

Thus, the program to create a subclass called Circle that overrides the
getPerimeter() and getArea() methods to calculate the area and perimeter of a
circle is executed successfully.
Ex.No:9 JAVA INTERFACE

Aim: To write a Java Program to create an interface shape with getArea()


method. Create three classes Rectangle, Circle and Triangle that implement the
Shape interface. Implement the getArea() method for each of the three classes.

Algorithm:
1. Open Netbeans IDE.
2. Select File->New project and rename the project as
‘ShapeInterfaceDemo’and click ‘Finish’.
3. Define the Interface ‘Shape’ and define the Abstract method
‘getArea()’.
4. Define the Rectangle class and implement the Shape interface, define
the Constructor to initialize length and breadth and Implement the
‘getArea()’ method to calculate area of the rectangle.
5. Define the Circle class and implement the Shape interface, define the
constructor to initialize radius and Implement the ‘getArea()’ method
to calculate area of the circle.
6. Define the Triangle class and implement the Shape interface, define
the constructor to initialize base and height and Implement the
‘getArea()’ method to calculate area of the triangle.
7. Define the Main class ‘ShapeInterfaceDemo’ and create object for
Rectangle, Circle and Triangle classes.
8. Print the Area of Rectangle by calling the ‘rectangle.getArea()’
method.
9. Print the Area of Circle by calling the ‘circle.getArea()’ method.
10. Print the Area of Triangle by calling the ‘triangle.getArea()’ method.
11. Save the program by clicking Ctrl+S.
12. Run the project by clicking Run->Run Project.

Program:

package shapeinterfacedemo;

interface Shape {

double getArea();

class Rectangle implements Shape {

private final double length;

private final double breadth;


public Rectangle(double length, double breadth) {

this.length = length;

this.breadth = breadth;

@Override

public double getArea() {

return length * breadth;

class Circle implements Shape {

private final double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double getArea() {

return Math.PI * radius * radius;

class Triangle implements Shape {

private final double base;

private final double height;

public Triangle(double base, double height) {

this.base = base;
this.height = height;

@Override

public double getArea() {

return 0.5 * base * height;

public class ShapeInterfaceDemo {

public static void main(String[] args) {

// TODO code application logic here

Shape rectangle = new Rectangle(10.0, 5.0);

Shape circle = new Circle(7.0);

Shape triangle = new Triangle(8.0, 4.0);

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

System.out.println("Area of Circle: " + circle.getArea());

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

}
Output:
Result:

Thus, the program to create an interface shape with ‘getArea()’ method,


Create three classes Rectangle, Circle and Triangle that implement the Shape
interface and Implement the ‘getArea()’ method for each of the three classes is
executed successfully.
Ex. No: 10 JAVA SWING

Aim: To write a Java program to create a panel with three buttons, labeled
Red, Blue and Yellow, so that clicking each button results in the background
color changing to the appropriate color.

Algorithm:
1. Open Netbeans IDE.
2. Select File -> New project and rename the project as ‘ColorChangePanel’
and click ‘Finish’.
3. Import Swing and AWT packeges
4. Create a class ColorChangerPanel which extends JFrame class.
5. Define the constructor to set up GUI.
6. Create a panel to hold the buttons and create the buttons Red, Blue and
Yellow.
7. Add action listeners to the buttons.
8. Add buttons to the panel.
9. Add the panel to the frame and make the frame visible.
10. Create an instance of the ColorChangerPanel class.
11. Save the program by clicking Ctrl+S.
12. Run the project by clicking Run->Run Project.

Program:
package colorchangerpanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ColorChangerPanel extends JFrame {

public ColorChangerPanel() {
setTitle("Color Changer Panel");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel;
panel = new JPanel();
panel.setLayout(new FlowLayout());
JButton redButton = new JButton("Red");
JButton blueButton = new JButton("Blue");
JButton yellowButton = new JButton("Yellow");
redButton.addActionListener((ActionEvent e) -> {
panel.setBackground(Color.RED);
});
blueButton.addActionListener((ActionEvent e) -> {
panel.setBackground(Color.BLUE);
});
yellowButton.addActionListener((ActionEvent e) -> {
panel.setBackground(Color.YELLOW);
});
panel.add(redButton);
panel.add(blueButton);
panel.add(yellowButton);
add(panel);
setVisible(true);
}

public static void main(String[] args) {


new ColorChangerPanel();
}

Output:
Result:

Thus, the program to create a panel with three buttons, labeled Red,
Blue and Yellow, so that clicking each button results in the background color
changing to the appropriate color is executed successfully and the output is
verified.

You might also like