Java Lab Manual 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

JAVA LAB MANUAL

1.Create a class called lamp it contains a variable is on and two methods turn on () and turn off
() with an associated object.
Program:
public class Lamp {
private boolean isOn;

// Constructor
public Lamp() {
this.isOn = false; // Initializing isOn to false when Lamp object is created
}

// Method to turn on the lamp


public void turnOn() {
this.isOn = true;
}

// Method to turn off the lamp


public void turnOff() {
this.isOn = false;
}

// Getter method to check if lamp is on or off


public boolean isLampOn() {
return this.isOn;
}

// Main method for testing


public static void main(String[] args) {
// Creating an instance of Lamp
Lamp myLamp = new Lamp();

// Turning on the lamp


myLamp.turnOn();

// Checking if the lamp is on


System.out.println("Lamp is on: " + myLamp.isLampOn());
// Turning off the lamp
myLamp.turnOff();

// Checking if the lamp is off


System.out.println("Lamp is on: " + myLamp.isLampOn());
}
}

2.Write a java program for sorting a given list of names in ascending order.
Program:
import java.io.*; class Test

int len,i,j;

String arr[ ];

Test(int n) {

len=n;

arr=new String[n];

String[ ] getArray()throws IOException {

BufferedReader br=new BufferedReader (new InputStreamReader(System.in));

System.out.println ("Enter the strings U want to sort----");

for (int i=0;i<len;i++)

arr[i]=br.readLine();

return arr;

String[ ] check()throws ArrayIndexOutOfBoundsException {

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

for(int j=i+1;j<len;j++) {
if ((arr[i].compareTo(arr[j]))>0) {

String s1=arr[i];

arr[i]=arr[j];

arr[j]=s1;

return arr;

void display()throws ArrayIndexOutOfBoundsException{

System.out.println ("Sorted list is---");

for (i=0;i<len;i++)

System.out.println(arr[i]);

} //end of the Test class

class Ascend {

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

Test obj1=new Test(4);

obj1.getArray();

obj1.check();

obj1.display();

Input and output:


3. Write a java program for Method overloading and Constructor overloading.
Program:
Method overloading:

import java.io.*;
class MethodOverloadingEx {

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

public static void main(String args[])


{
System.out.println("add() with 2 parameters");
System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");


System.out.println(add(4, 6, 7));
}
}

Output:
Constructor overloading

public class Student {


//instance variables of the class
int id;
String name;

Student(){
System.out.println("this a default constructor");
}
Student(int i,
String n){
id = i;
name = n;
}

public static void main(String[] args) {


//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");


Student student = new Student(10, "Kalpana");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}
Three test outputs:
Create a class called Bank and calculate the rate of interest for different banks using
4.
method overriding and inheritance.
Program:
// Parent class Bank
class Bank {
// Method to calculate rate of interest
double getRateOfInterest() {
return 0.0;
}
}

// Child class extending Bank - BankA


class BankA extends Bank {
// Method overriding to calculate rate of interest for BankA
@Override
double getRateOfInterest() {
return 5.0;
}
}

// Child class extending Bank - BankB


class BankB extends Bank {
// Method overriding to calculate rate of interest for BankB
@Override
double getRateOfInterest() {
return 6.0;
}
}

// Child class extending Bank - BankC


class BankC extends Bank {
// Method overriding to calculate rate of interest for BankC
@Override
double getRateOfInterest() {
return 7.0;
}
}

// Main class to test the program


public class Main {
public static void main(String[] args) {
BankA bankA = new BankA();
BankB bankB = new BankB();
BankC bankC = new BankC();

// Printing rate of interest for each bank


System.out.println("Rate of interest for BankA: " + bankA.getRateOfInterest() + "%");
System.out.println("Rate of interest for BankB: " + bankB.getRateOfInterest() + "%");
System.out.println("Rate of interest for BankC: " + bankC.getRateOfInterest() + "%");
}
}

5. Write a java program to create an abstract class named Shape that contains two
integers and an empty method named print Area (). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class Shape.
Each one of the classes contain only the method print Area() that prints the area of the
given shape.
Program:
abstract class Shape

abstract void numberOfSides();

class Trapezoid extends Shape

{ void

numberOfSides()

System.out.println(" Trapezoidal has four sides");

class Triangle extends Shape

void numberOfSides()

System.out.println("Triangle has three sides");

class Hexagon extends Shape

{ void

numberOfSides()

{
System.out.println("Hexagon has six sides");
}
}
class ShapeDemo
{
public static void main(String args[ ])
{
Trapezoid t=new Trapezoid();
Triangle r=new Triangle();
Hexagon h=new
Hexagon(); Shape s; s=t;
s.numberOfSides();
s=r;
s.numberOfSides();
s=h;
s.numberOfSides();
}
}

Output:-

6. Write a java program to create user defined package.


Program:
A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

B.java import
pack.A; class B
{
public static void main(String args[])
{
A obj = new A(); obj.msg();
}
}
Three Test Outputs:

7. Write a java program to calculate the salary of employee using interface.


Program:
// Interface for SalaryCalculator
interface SalaryCalculator {
double calculateSalary();
}

// Implementation class for SalaryCalculator


class Employee implements SalaryCalculator {
private double basicSalary;
private double allowances;

// Constructor
public Employee(double basicSalary, double allowances) {
this.basicSalary = basicSalary;
this.allowances = allowances;
}

// Method to calculate salary


@Override
public double calculateSalary() {
return basicSalary + allowances;
}
}

// Main class to test the program


public class Main {
public static void main(String[] args) {
double basicSalary = 50000; // Example basic salary
double allowances = 10000; // Example allowances

// Creating an Employee object


Employee emp = new Employee(basicSalary, allowances);

// Calculating and printing the salary


System.out.println("Employee Salary: $" + emp.calculateSalary());
}
}

8.Write a Java program to handle exception using try and multiple catch block.
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Code that may throw exceptions
int[] numbers = {1, 2, 3};
int result = numbers[4]; // Trying to access an index that doesn't exist
} catch (ArrayIndexOutOfBoundsException e) {
// Catch block to handle ArrayIndexOutOfBoundsException
System.out.println("Array index out of bounds exception occurred!");
} catch (Exception e) {
// Catch block to handle any other exceptions
System.out.println("An unexpected exception occurred: " + e.getMessage());
}
}
}
9. Develop an Applet that receives an integer in one text field & compute its factorial
value & returns it in another text field when the button “compute” is clicked.
import java.awt.*;

import java.lang.String;

import java.awt.event.*;

import java.applet.Applet;

public class Fact extends Applet implements ActionListener

String str;

Button b0;

TextField t1,t2;

Label l1;

publicvoidinit(){

Panel p=new Panel();

p.setLayout(new GridLayout());

add(new Label("Enter any Integer value"));

add(t1=new TextField(20));

add(new Label("Factorial value is: "));

add(t2=new TextField(20));

add(b0=new Button("compute"));

b0.addActionListener(this);

public void actionPerformed(ActionEvent e)

int i,n,f=1;

n=Integer.parseInt(t1.getText());

for(i=1;i<=n;i++)
f=f*i;

t2.setText(String.valueOf(f));

repaint();

Output:-

10. Create a layout using applets to arrange buttons for digits and for the +, -, *, %
operations. Add text field to display the result.
Program:
import java.applet.Applet;
import java.awt.*;

public class CalculatorApplet extends Applet {


TextField display;
String operator;
double num1, num2, result;

public void init() {


setLayout(new BorderLayout());
display = new TextField();
add(display, BorderLayout.NORTH);

Panel buttonPanel = new Panel();


buttonPanel.setLayout(new GridLayout(4, 4));

// Adding buttons for digits


for (int i = 9; i >= 0; i--) {
Button button = new Button(String.valueOf(i));
buttonPanel.add(button);
button.addActionListener(e -> {
display.setText(display.getText() + button.getLabel());
});
}

// Adding buttons for arithmetic operations


String[] operations = {"+", "-", "*", "%"};
for (String op : operations) {
Button button = new Button(op);
buttonPanel.add(button);
button.addActionListener(e -> {
operator = op;
num1 = Double.parseDouble(display.getText());
display.setText("");
});
}

// Adding equals button


Button equalsButton = new Button("=");
equalsButton.addActionListener(e -> {
num2 = Double.parseDouble(display.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "%":
result = num1 % num2;
break;
}
display.setText(String.valueOf(result));
});
buttonPanel.add(equalsButton);

// Adding clear button


Button clearButton = new Button("C");
clearButton.addActionListener(e -> {
display.setText("");
});
buttonPanel.add(clearButton);

add(buttonPanel, BorderLayout.CENTER);
}
}

You might also like