0% found this document useful (0 votes)
181 views15 pages

Java Programming Lab Exercises

The document describes a Java lab manual with 10 programming examples covering topics like creating classes and objects, sorting arrays, method and constructor overloading, inheritance, abstraction, interfaces, exceptions handling, applets, and layouts. The examples provide code snippets and outputs to demonstrate different Java concepts.
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)
181 views15 pages

Java Programming Lab Exercises

The document describes a Java lab manual with 10 programming examples covering topics like creating classes and objects, sorting arrays, method and constructor overloading, inheritance, abstraction, interfaces, exceptions handling, applets, and layouts. The examples provide code snippets and outputs to demonstrate different Java concepts.
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

JAVA LAB MANUAL

[Link] 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() {
[Link] = false; // Initializing isOn to false when Lamp object is created
}

// Method to turn on the lamp


public void turnOn() {
[Link] = true;
}

// Method to turn off the lamp


public void turnOff() {
[Link] = false;
}

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


public boolean isLampOn() {
return [Link];
}

// Main method for testing


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

// Turning on the lamp


[Link]();

// Checking if the lamp is on


[Link]("Lamp is on: " + [Link]());
// Turning off the lamp
[Link]();

// Checking if the lamp is off


[Link]("Lamp is on: " + [Link]());
}
}

[Link] a java program for sorting a given list of names in ascending order.
Program:
import [Link].*; 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([Link]));

[Link] ("Enter the strings U want to sort----");

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

arr[i]=[Link]();

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{

[Link] ("Sorted list is---");

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

[Link](arr[i]);

} //end of the Test class

class Ascend {

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

Test obj1=new Test(4);

[Link]();

[Link]();

[Link]();

Input and output:


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

import [Link].*;
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[])


{
[Link]("add() with 2 parameters");
[Link](add(4, 6));

[Link]("add() with 3 parameters");


[Link](add(4, 6, 7));
}
}

Output:
Constructor overloading

public class Student {


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

Student(){
[Link]("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();
[Link]("\nDefault Constructor values: \n");
[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]);

[Link]("\nParameterized Constructor values: \n");


Student student = new Student(10, "Kalpana");
[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]);
}
}
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


[Link]("Rate of interest for BankA: " + [Link]() + "%");
[Link]("Rate of interest for BankB: " + [Link]() + "%");
[Link]("Rate of interest for BankC: " + [Link]() + "%");
}
}

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()

[Link](" Trapezoidal has four sides");

class Triangle extends Shape

void numberOfSides()

[Link]("Triangle has three sides");

class Hexagon extends Shape

{ void

numberOfSides()

{
[Link]("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;
[Link]();
s=r;
[Link]();
s=h;
[Link]();
}
}

Output:-

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


Program:
[Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}

[Link] import
pack.A; class B
{
public static void main(String args[])
{
A obj = new A(); [Link]();
}
}
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) {
[Link] = basicSalary;
[Link] = 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


[Link]("Employee Salary: $" + [Link]());
}
}

[Link] 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
[Link]("Array index out of bounds exception occurred!");
} catch (Exception e) {
// Catch block to handle any other exceptions
[Link]("An unexpected exception occurred: " + [Link]());
}
}
}
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 [Link].*;

import [Link];

import [Link].*;

import [Link];

public class Fact extends Applet implements ActionListener

String str;

Button b0;

TextField t1,t2;

Label l1;

publicvoidinit(){

Panel p=new Panel();

[Link](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"));

[Link](this);

public void actionPerformed(ActionEvent e)

int i,n,f=1;

n=[Link]([Link]());

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

[Link]([Link](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 [Link];
import [Link].*;

public class CalculatorApplet extends Applet {


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

public void init() {


setLayout(new BorderLayout());
display = new TextField();
add(display, [Link]);

Panel buttonPanel = new Panel();


[Link](new GridLayout(4, 4));

// Adding buttons for digits


for (int i = 9; i >= 0; i--) {
Button button = new Button([Link](i));
[Link](button);
[Link](e -> {
[Link]([Link]() + [Link]());
});
}

// Adding buttons for arithmetic operations


String[] operations = {"+", "-", "*", "%"};
for (String op : operations) {
Button button = new Button(op);
[Link](button);
[Link](e -> {
operator = op;
num1 = [Link]([Link]());
[Link]("");
});
}

// Adding equals button


Button equalsButton = new Button("=");
[Link](e -> {
num2 = [Link]([Link]());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "%":
result = num1 % num2;
break;
}
[Link]([Link](result));
});
[Link](equalsButton);

// Adding clear button


Button clearButton = new Button("C");
[Link](e -> {
[Link]("");
});
[Link](clearButton);

add(buttonPanel, [Link]);
}
}

Common questions

Powered by AI

In Java, abstract classes and methods are utilized to define a common interface for different subclasses while deferring the implementation to the subclasses themselves. An abstract class cannot be instantiated on its own and must be extended by other classes. An example is a `Shape` class with an abstract method `numberOfSides` . Different shapes such as `Trapezoid`, `Triangle`, and `Hexagon` extend `Shape` and provide concrete implementations of `numberOfSides`. This design allows each shape to specifically define how many sides it has, while maintaining a standardized method structure mandated by the parent abstract class.

Polymorphism in Java can be implemented using method overriding, which allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This functionality is crucial for achieving dynamic method dispatch, which enables Java to execute the correct method at runtime. For example, in a banking application where different banks calculate interest rates differently, each bank class can override the `getRateOfInterest` method of a common superclass (e.g., `Bank`). Bank A might implement a 5% interest rate, Bank B a 6% rate, and so on . This dynamic selection of the correct interest rate method based on the bank object created demonstrates method overriding and polymorphism's ability to operate on the superclass interface but execute subclass methods.

Applets in Java can be used to create graphical user interfaces such as a simple calculator by leveraging AWT components for user input and output. A calculator applet can use `TextField` components for displaying numbers and results, while buttons represent digits and arithmetic operations like addition or subtraction . Actions on buttons can be captured using `ActionListener`, updating the `TextField` dynamically as users input values or perform calculations. Upon pressing an operation button, the applet can internally store users' numbers and chosen operation. When equals is clicked, it performs the calculation and updates the display with results. This interaction between input components (buttons) and output (display `TextField`) demonstrates the dynamic interface capabilities enabled by applet architecture.

Sorting a list of names in ascending order in Java involves several steps. First, a class `Test` is instantiated, which holds the list of names in a `String` array. Next, the array elements are compared in nested loops, swapping elements if they are out of order to achieve sorting . The `compareTo` method of the `String` class is used for comparisons, and potential `ArrayIndexOutOfBoundsException` errors need handling. This is often done using try-catch blocks, ensuring the program runs even when unexpected array index access occurs. However, the provided program does not explicitly demonstrate exception handling for sorting, which can be improved by surrounding sorting logic with try-catch blocks to catch bounds-related errors.

In a Java Applet designed to calculate factorials, the Button's `ActionEvent` handling mechanism works by associating event listeners with UI components, enabling them to respond to user actions. Specifically, a `Button` is created and an `ActionListener` is added, implementing the required `actionPerformed` method . When the button (labeled 'compute') is clicked, the `actionPerformed` method is triggered. Inside this method, the input from a `TextField` is parsed into an integer, the factorial is computed using a loop, and the result is displayed in another `TextField`. This mechanism demonstrates essential GUI programming concepts, where interactive behaviors are executed in response to user inputs.

Implementing interfaces in Java is a way to define a contract that a class can implement, ensuring that the class follows a particular protocol or set of methods. Interfaces provide a form of multiple inheritance since a class can implement multiple interfaces. In the case of salary calculation for employees, the `SalaryCalculator` interface declares a method `calculateSalary` that any implementing class must provide . The `Employee` class can then implement this interface and provide a concrete calculation for the salary based on attributes like basic salary and allowances. This use of interfaces enforces a consistent contract method for salary calculation across different classes.

Constructor overloading in Java allows a class to have more than one constructor with different parameter lists. Each constructor can perform a different task or initialize the object in various ways. For instance, in the `Student` class, there are two constructors: one default constructor, which doesn't take any parameters and might be used for setting default values, and a parameterized constructor that initializes the object with specific values such as an ID and name . This showcases how constructor overloading enables flexibility in object construction, allowing for objects to be initialized in multiple ways to suit different requirements.

Using try-catch blocks in Java program contributes significantly to program reliability by allowing the detection and handling of runtime exceptions, preventing potential crashes. For example, in array indexing, accessing an invalid index can cause an `ArrayIndexOutOfBoundsException` . A try block can enclose the code that might throw such exceptions, while the catch blocks handle specific exceptions, allowing for fallback actions or user notifications. This mechanism ensures that the program can continue executing gracefully even when unforeseen errors occur, thus enhancing the robustness and user experience of the application.

Method overloading in Java allows an application to define multiple methods with the same name but different parameter lists within a class, enhancing functionality by enabling one method name to perform various tasks based on input parameters. For arithmetic operations, method overloading facilitates operations like adding numbers by defining `add` functions with different parameter combinations. For instance, one `add` method could sum two integers, while another sums three integers . This approach not only improves code readability and organization but also allows for a flexible, intuitive way to perform related operations under a single method name while handling different input scenarios.

Arrays and loops form the backbone of many sorting algorithms by providing the data structure and iterative mechanism required to process and reorder elements systematically. In the context of a Java program to sort a list of names in ascending order, an array holds the list of names, while nested loops iterate over these elements to compare and swap them into sorted order using a comparison method like `compareTo` . Each iteration takes two elements, compares them, and swaps them if they are out of order, progressively sorting the entire list. This process highlights how core programming constructs such as arrays and loops are integral to implementing efficient sorting algorithms in Java.

You might also like