KEMBAR78
Java-All Practicals 1-11 | PDF | Control Flow | Java (Programming Language)
0% found this document useful (0 votes)
102 views47 pages

Java-All Practicals 1-11

Uploaded by

rohanshedge2006
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)
102 views47 pages

Java-All Practicals 1-11

Uploaded by

rohanshedge2006
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/ 47

Experiment 1

Aim: Installation of Java (JDK) and execution of Hello Word program

Prerequisite: JDK 12 or above

Theory:

1. Introduction to Java and JDK

Java is a popular, high-level, object-oriented programming language developed by Sun Microsystems (now owned by
Oracle). It is widely used for building platform-independent applications. The Java Development Kit (JDK) is a
software development environment used for developing Java applications. It includes tools for compiling,
debugging, and running Java programs.

2. Installing the JDK

Step 1: Download the JDK

1. Visit the Oracle Website:

- Go to the [Oracle JDK download page](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html)


(or the appropriate version).

2. Choose the JDK Version:

- Select the version you wish to download. It's often recommended to use the latest stable version.

3. Select the Appropriate Installer:

- Choose the installer suitable for your operating system (Windows, macOS, or Linux).

Step 2: Install the JDK

1. Run the Installer:

- Open the downloaded file and follow the installation instructions.

2. Set Environment Variables (Windows):

- After installation, you may need to set environment variables.

- Right-click on "This PC" or "My Computer" and select "Properties".

- Click on "Advanced system settings" > "Environment Variables".

- Under "System variables", click "New" and add:

- Variable name: `JAVA_HOME`

- Variable value: Path to the JDK installation (e.g., `C:\Program Files\Java\jdk-11.x.x`).


- Find the "Path" variable in the "System variables" section, click "Edit", and add a new entry:

- `%JAVA_HOME%\bin`.

3. Verify the Installation:

- Open Command Prompt (Windows) or Terminal (macOS/Linux).

- Type the following command:

java -version

- If installed correctly, you should see the version of Java.

3. Writing and Executing a "Hello World" Program

Step 1: Create the Program

1. Open a Text Editor:

- Use any text editor (Notepad, VSCode, Sublime Text, etc.).

2. Write the Java Code:

3. Save the File:

- Save the file as `Helloworld.java`. Ensure that the filename matches the class name exactly (case-sensitive).

Step 2: Compile the Program

1. Open Command Prompt or Terminal:

- Navigate to the directory where you saved `Helloworld.java`.

2. Compile the Java Program:

- Run the following command:

javac Helloworld.java

- This will create a file named `Helloworld.class`, which contains the bytecode.

Step 3: Run the Program

Program:

class Helloworld {

public static void main (String[] args) {

System.out.println("Hello World!");

}
//Name: Dipak || Tushar

//roll no : 2578 || 2581

output:-

4. Conclusion

You have successfully installed the JDK, written a simple Java program, compiled it, and executed it. This "Hello World"
program serves as a basic introduction to Java programming and showcases the fundamental steps involved in
creating and running a Java application.

5. Troubleshooting Tips

- Check the Case Sensitivity: Ensure the file name and class name match exactly, including case.

- Path Issues: If you receive errors about Java not being found, double-check that the `JAVA_HOME` variable and
`Path` settings are correctly configured.

- Permissions: Ensure you have permission to execute commands in the terminal or command prompt.
Experiment 2
Aim: WAP to demonstrate Control Statements and Iteration Statements

Prerequisite: JDK 12 or above

Theory:

Control Statements

Control statements determine the flow of control in a program. They dictate how a program behaves based on certain
conditions. There are several types of control statements in Java:

1. Conditional Statements

Conditional statements allow a program to execute certain sections of code based on whether a condition evaluates
to true or false. The main types include:

- if Statement: Executes a block of code if a specified condition is true.

if (condition) {

// code to be executed if condition is true

- if-else Statement: Executes one block of code if the condition is true and another block if it is false.

if (condition) {

// code if condition is true

} else {

// code if condition is false

- else if Statement: Used to check multiple conditions.

if (condition1) {

// code if condition1 is true

} else if (condition2) {

// code if condition2 is true

} else {
// code if both conditions are false

- switch Statement: Allows a variable to be tested for equality against a list of values (cases).

switch (variable) {

case value1:

// code for value1

break;

case value2:

// code for value2

break;

default:

// code if none of the cases match

2. Jump Statements

Jump statements allow you to move the control flow to a different part of the program. Common jump
statements include:

- break: Exits a loop or switch statement.

- continue: Skips the current iteration of a loop and continues with the next iteration.

- return: Exits from the current method and optionally returns a value.

Iteration Statements

Iteration statements, also known as loops, allow a block of code to be executed repeatedly as long as a specified
condition is true. The main types of iteration statements in Java include:

1. for Loop: The `for` loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and increment/decrement.

for (initialization; condition; increment/decrement) {

// code to be executed }

Example

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

System.out.println(i); }
2. while Loop: The `while` loop continues to execute as long as a specified condition is true. It is generally used when
the number of iterations is not known beforehand.

while (condition) {

// code to be executed

Example:

int i = 0;

while (i < 5) {

System.out.println(i);

i++;

3. do-while Loop: The `do-while` loop is similar to the `while` loop, but it guarantees that the block of code is
executed at least once, even if the condition is false initially.

do {

// code to be executed

} while (condition);

Example:

int i = 0;

do {

System.out.println(i);

i++;

} while (i < 5);

Program Code:

public class ConditionalAndIterationStatements {

public static void main(String[] args) {

System.out.println(“Dipak shedge &

TusharShinde”);

// Conditional Statements (if-else)

int x = 10;

if (x > 5) {
System.out.println("x is greater than 5");

} else {

System.out.println("x is less than or equal to 5");

// Nested if-else statements

int y = 20;

if (y > 10) {

if (y > 15) {

System.out.println("y is greater than 15");

} else {

System.out.println("y is between 10 and 15");

} else {

System.out.println("y is less than or equal to 10");

// Switch statement

char grade = 'A';

switch (grade) {

case 'A':

System.out.println("Excellent");

break;

case 'B':

System.out.println("Good");

break;

case 'C':

System.out.println("Fair");

break;

default:

System.out.println("Invalid grade");
}

// Iteration Statements (for, while, do-while)

// For loop

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

System.out.println("For loop iteration: " + i);

// While loop

int j = 0;

while (j < 5) {

System.out.println("While loop iteration: " + j);

j++;

// Do-while loop

int k = 0;

do {

System.out.println("Do-while loop iteration: " + k);

k++;

} while (k < 5);

// Break and continue statements

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

if (i == 5) {

break; // exit the loop

System.out.println("Break example: " + i);

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

if (i == 5) {

continue; // skip the current iteration


}

System.out.println("Continue example: " + i);

Output:-

Conclusion: Control Statements: Allow conditional execution of code blocks, enabling decision-making within the
program.Iteration Statements: Enable repeated execution of code blocks, facilitating tasks such as looping
through collections, performing calculations, or processing user input.Understanding these concepts is crucial
for developing efficient algorithms and controlling the logic in Java programs. They form the backbone of flow
control, making it possible to build complex applications with branching and looping behaviors.
Experiment 3
Aim: Implement a java program to calculate gross salary & net salary using the following data. Input: empno,
empname, basic salary.

Prerequisite: JDK 12 or above

Theory

1. Understanding Salaries

- Basic Salary: The core part of the salary.

- Dearness Allowance (DA): A cost of living adjustment paid to employees to counteract inflation (often a percentage
of the basic salary).

- House Rent Allowance (HRA): A portion of the salary paid to employees to cover housing costs (again typically a
percentage of the basic salary).

- City Compensatory Allowance (CCA): A fixed allowance to compensate for higher costs in urban areas.

- Provident Fund (PF): A mandatory savings scheme where a portion of the salary is deducted for retirement savings.

- Professional Tax (PT): A tax levied by the state on professions.

2. Salary Calculation

The gross salary can be calculated as:

\[ {Gross Salary} = {Basic Salary} + {DA} + {HRA} \]

The net salary can be computed as:

\[ {Net Salary} = {Gross Salary} - ({PF} + {PT} + {CCA}) \]

Steps:

1. Imports:

- The program imports `java.util` for using the `Scanner` class to read user input.

2. Scanner Setup:

- A `Scanner` object is created to read input from the console. The locale is set to `US` to ensure that the decimal
separator is recognized correctly.

3. Input Collection:

- The program collects the employee number, name, and basic salary from the user.

4. Salary Calculations:

- It calculates DA, HRA, CCA, PF, and PT based on predefined formulas and constants.
- It computes the gross salary and then the net salary.

Program Code:

import java.util.*;

public class salary {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("enter employee number :");

int empNo = scan.nextInt();

System.out.println("enter employee name :");

String empName = scan.next();

System.out.println("enter basic salary :");

double basic = scan.nextDouble();

double DA = 0.70*basic;

double HRA = 0.30*basic;

double CCA = 240;

double PF = 0.10*basic;

double PT = 100;

double grossSalary = basic + DA + HRA ;

double netSalary = grossSalary - PF - PT - CCA ;

System.out.println("\n Employee Details:");

System.out.println("Employee Number :" + empNo);

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

System.out.println("Basic salary :" + basic);

System.out.println("Dearness Allowance (DA) :" + DA);

System.out.println("House Rent Allowance (HRA):"+ HRA);

System.out.println("City Compensatory Allowance (CCA) :" + CCA);

System.out.println("Provident Fund (PF) :" + PF);

System.out.println("Professional Tax :" + PT);


System.out.println("Gross Salary :" +grossSalary);

System.out.println("Net Salary :" +netSalary);

scan.close();

//Name: Dipak || Tushar

roll no 2578 & 2581

output:-

Conclusion: By utilizing control statements for input and mathematical calculations for salary components, this
program encapsulates the fundamental concepts of Java programming. This not only enhances understanding
of how salary calculations work in practice but also illustrates how to handle user input and perform calculations
programmatically.
Experiment 4
Aim: Write a Menu driven program in java to implement simple banking application. Application should read the
customer’s name, account number, initial balance, rate of interest, contact number and address field etc.
Application should have following methods. 1. createAccount() 2. deposit() 3. withdraw () 4.
computeInterest() 5. displayBalance()

Prerequisite:-

1. Basic Java Programming: Understanding of Java syntax, data


types, operators, control structures (if-else, loops), and
exception handling.
2. Object-Oriented Programming (OOP) Concepts: Knowledge of
classes, objects, inheritance, encapsulation, and polymorphism.
3. Java Collections Framework: Familiarity with collections like
Array List for storing objects.
4. Basic I/O Operations: Reading input from the user using
Scanner and displaying output
Theory: -

The menu-driven approach is a user interface design pattern commonly used in console applications to guide users
through various functionalities. In this lab work, we focus on implementing a simple banking application using
Java, utilizing a menu-driven system to provide a structured and interactive way for users to access different
banking operations. This method is particularly effective in ensuring ease of use and clarity, especially in
applications where multiple functionalities are available.

Menu-Driven System Overview

A menu-driven system displays a list of options or commands to the user, each associated with a specific action or
function. The user navigates through the options by selecting an appropriate command, typically by entering a
number corresponding to the desired option. This design pattern helps users understand and interact with the
program's capabilities without needing to remember specific commands or syntax.

In the context of our banking application, the menu-driven system serves as the primary interface through which
users interact with the program. The main menu presents several options, including:

1. Create Account

2. Deposit Funds

3. Withdraw Funds

4. Check Balance

5. Exit
Each of these options corresponds to a particular operation within the banking application. The user selects an option
by entering the corresponding number, which then triggers the execution of the relevant code block.

Implementation Details

1. Creating the Menu Interface: The menu interface is typically implemented using a loop, such as a while loop, which
repeatedly displays the menu until the user chooses to exit the program. Inside the loop, a switch-case
statement or a series of if-else conditions are used to execute the appropriate actions based on the user's input.

2. Handling User Input: User input is managed using the Scanner class in Java, which reads the user's selection from
the console. This input determines the path the program takes, directing it to the appropriate section of the
code to handle the requested operation. For example, if the user chooses to create an account, the program
prompts for additional details such as the account number, the account holder's name, and the initial deposit
amount.

3. Performing Banking Operations: Create Account: When this option is selected, the program collects the necessary
details from the user to set up a new account. The information is then used to create a new instance of the Bank
Account class, which is stored in a collection, such as an ArrayList, for easy management and retrieval.

4. Deposit Funds: To deposit funds into an account, the program first asks for the account number. It then verifies
the existence of the account and prompts for the deposit amount. After validating the amount, the program
updates the account balance accordingly.

5. Withdraw Funds: Like depositing, withdrawing funds requires the user to enter the account number and the desired
withdrawal amount. The program checks that the account exists and that the withdrawal amount does not
exceed the current balance before proceeding with the transaction.

6. Check Balance: This option allows the user to view the current balance of a specific account. The program asks for
the account number and retrieves the balance for display.

7. Exiting the Program: The exit option terminates the loop and subsequently ends the program. This provides a clean
and controlled exit from the application, ensuring that any necessary cleanup or final operations can be
performed before the program shuts down.

Advantages of the Menu-Driven Approach

The menu-driven approach offers several advantages:

◼ User-Friendly: It provides a simple and intuitive way for users to navigate the application. Users do not need to
remember specific commands or syntax, as the options are clearly listed.
◼ Structured Navigation: It organizes the program's functionality into discrete, accessible options, making it easy
for users to find and use the features they need.
◼ Error Reduction: By guiding users through a set of predefined options, the menu-driven approach minimizes the
chances of user error, such as entering invalid commands.
◼ Ease of Expansion: The menu system can be easily expanded to include new functionalities by adding new options
to the menu and implementing the corresponding operations.
Program:

import java.util.Scanner;

class BankAccount {

private String customerName;

private String accountNumber;

private double balance;

private double rateOfInterest;

private String contactNumber;

private String address;

public void createAccount() {

Scanner sc = new Scanner(System.in);

System.out.print("Enter customer name: ");

customerName = sc.nextLine();

System.out.print("Enter account number: ");

accountNumber = sc.nextLine();

System.out.print("Enter initial balance: ");

balance = sc.nextDouble();

System.out.print("Enter rate of interest: ");

rateOfInterest = sc.nextDouble();

sc.nextLine();

System.out.print("Enter contact number: ");

contactNumber = sc.nextLine();

System.out.print("Enter address: ");


address = sc.nextLine();

System.out.println("Account created successfully!\n");

public void deposit() {

Scanner sc = new Scanner(System.in);

System.out.print("Enter amount to deposit: ");

double amount = sc.nextDouble();

if(amount > 0) {

balance += amount;

System.out.println("Account deposited successfully!\n");

}else{

System.out.println("Invalid amount. Please enter a positive number.");

public void withdraw() {

Scanner sc = new Scanner(System.in);

System.out.print("Enter amount to withdraw: ");

double amount = sc.nextDouble();

if(amount > 0 && amount <= balance) {

balance -= amount;

System.out.println("Account withdrawn successfully!\n");

}else{

System.out.println("Invalid amount or insufficient balance");

}
public void computeInterest() {

double interest = balance * (rateOfInterest / 100);

balance += interest;

System.out.println("Interest computed and added to balance successfully!");

public void displayBalance() {

System.out.println("Account Holder: " +customerName);

System.out.println("Account Number: " +accountNumber);

System.out.println("Balance: " +balance);

System.out.println("Rate of Interest: " +rateOfInterest + "%");

System.out.println("Contact Number: " +contactNumber);

System.out.println("Address: "+address);

public class Bankingapplication {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

BankAccount account = new BankAccount();

int choice;

while(true) {

System.out.println("\n--- Banking Application Menu ---");

System.out.println("1.Create Account");

System.out.println("2.Deposit");

System.out.println("3.Withdraw");
System.out.println("4.Compute Interest");

System.out.println("5.Display Balance");

System.out.println("6.Exit");

System.out.print("Enter your choice: ");

choice = sc.nextInt();

switch(choice) {

case 1:

account.createAccount();

break;

case 2:

account.deposit();

break;

case 3:

account.withdraw();

break;

case 4:

account.computeInterest();

break;

case 5:

account.displayBalance();

break;

case 6:

System.out.println("Thank you for using the banking application!");

break;

default:

System.out.println("Invalid choice. Please try again.");

}
}

output:-
Conclusion: - This lab work on creating a menu-driven bank application illustrates fundamental OOP concepts
subclasses, objects, encapsulation, and collections. By implementing a structured user interface and handling
basic banking operations, students can gain hands-on experience in developing user-friendly and maintainable
software.
Experiment 5
Aim: Create a Java based application to perform various ways of Method overloading and constructor
overloading

Prerequisites:

1. Basic knowledge of Java programming

2. OOP (Object-Oriented Programming) concepts


3. Java IDE or compiler

Theory:

Method Overloading

Method overloading is a feature in Java that allows a class to have multiple methods with the same name but
different parameter lists. This means that the methods must differ in the number of parameters, the type of
parameters, or both. Method overloading is a key aspect of polymorphism in object-oriented programming, where
a single method name can be associated with multiple behaviors depending on the context in which it is called.

One of the primary benefits of method overloading is improved code readability and usability. By using the same
method name for similar actions that operate on different types of input, developers can create a more intuitive
interface. For example, if you have a method that calculates the area, you might overload it to handle both square
and rectangular shapes without needing different method names. This can make it easier for other developers to
understand how to use your class without having to remember multiple method names.

Another advantage of method overloading is that it can reduce the complexity of code. Instead of having to create
unique method names for every variation of a task, overloaded methods can simplify the interface and allow for
more straightforward method calls. This is particularly useful in situations where similar operations need to be
performed on different data types.

In summary, both method overloading and constructor overloading are essential features of Java that enhance the
language's flexibility and usability. They contribute to cleaner code, better organization, and increased readability,
making it easier for developers to work with and maintain Java applications. These concepts exemplify the
principles of polymorphism and encapsulation, which are fundamental to object-oriented programming.

Program:

CONSTRUCTOR OVERLOADING:

class Calculator {

private int a;

private int b;
// Default constructor

public Calculator() {

this.a = 0;

this.b = 0;

// Constructor with one parameter

public Calculator(int a) {

this.a = a;

this.b = 0;

// Constructor with two parameters

public Calculator(int a, int b) {

this.a = a;

this.b = b;

// Method to add two integers

public int add(int a, int b) {

return a + b;

// Method to add two doubles

public double add(double a, double b) {

return a + b;

// Method to add three integers

public int add(int a, int b, int c) {

return a + b + c;

}
}

public class OverloadingDemo1 {

public static void main(String[] args) {

// Creating objects using constructor overloading

Calculator cal1 = new Calculator();

Calculator cal2 = new Calculator(10);

Calculator cal3 = new Calculator(10, 20);

// Demonstrating method overloading

System.out.println("Sum (int, int): " + cal1.add(10, 20));

System.out.println("Sum (double, double): " + cal1.add(10.5, 20.5));

System.out.println("Sum (int, int, int): " + cal1.add(10, 20, 30));

//name: Dipak&Tushar

// roll no: 2578 & 2581

Output:-

Method overloading:

class Display {

// Method to display an integer


public void show(int a) {

System.out.println("Integer: " + a);

// Method to display a double

public void show(double b) {

System.out.println("Double: " + b);

// Method to display a string

public void show(String c) {

System.out.println("String: " + c);

// Method to display two integers

public void show(int a, int b) {

System.out.println("Sum of integers: " + (a + b));

public class MethodOverloadingExample {

public static void main(String[] args) {

Display display = new Display();

// Calling overloaded methods

display.show(5);

display.show(3.14);

display.show("Hello, World!");

display.show(10, 20);

}
}

//name:Dipak&Tushar

roll no: 2578 & 2581

output:

Conclusion: Thus, we studied to perform various ways of Method overloading and constructor overloading.
Experiment 6
Aim - To create a class 'Student’ and print the name, age and address of using an array of objects 10 students

Theory - Introduction to Arrays:

An array is a core data structure in Java that allows you to store multiple elements of the same type in a single,
contiguous block of memory. Arrays are widely used in programming because they provide an efficient way to
store and access sequences of data. Each element in an array is stored at a specific index, allowing for fast
retrieval and modification. Arrays are particularly useful when you need to manage a collection of items, such as a
list of numbers, strings, or objects, where Each item is of the same data type.

Array Declaration and Initialization: In Java, arrays are objects that must be declared and initialized before They
can be used. The declaration of an array involves specifying the type of elements it will store and the syntax for
creating an array. The Initiative of an array involves allocating memory for the elements and optionally assigning
values to them

Declaration:

An array must be declared with a specific type, indicating the kind of elements it will hold.

Initialization:

After declaring an array, you must initialize it by allocating memory for its elements. This is done using the new
keyword, followed by the data type and the size of the array.

Accessing and Modifying: Each element in an array is accessed using its index, which starts from 0 and goes up to
1, where length is the number of elements in the array.

Arrays of Objects: In Java, you can create arrays to store objects of a particular class. When you declare an array
of objects, each element in the array holds a reference to an object, not the object itself. This means that the
array stores memory addresses pointing to the actual objects. Accessing and modifying objects in an array is like
working with primitive data types

Iterating Over Arrays:

Arrays are often used in combination with loops to process multiple elements. Java provides two main types of
loops for iterating over arrays: the traditional for loop and the enhanced for-each loop.

Traditional for Loop:

The traditional for loop allows you to iterate over the array using an index, providing full control over the iteration
process. This loop is useful when you need to know the index of the current element or when you need to modify
elements during iteration.

Enhanced for-each Loop: The enhanced for-each loop simplifies iteration by automatically handling the loop
counter and directly accessing each element. This loop is particularly convenient for reading elements when you
don't need to modify them or access their indices.
Advantages and Disadvantages of Arrays

Arrays are simple and efficient data structures but have limitations. They provide constant-time access to
elements and are efficient in terms of memory. However, their size is fixed once they are created, meaning you
cannot resize them without creating a new array. Additionally, arrays are homogeneous, meaning all elements
must be of the same type.

Program:

class Student {

String name;

int age;

String course;

// Default constructor

public Student() {

this("Unknown", 0); // Calls the constructor with 2 parameters

System.out.println("Default constructor called");

public Student(String name, int age) {

this(name, age, "Undeclared"); // Calls the constructor with 3 parameters

System.out.println("Constructor with 2 parameters called");

public Student(String name, int age, String course) {

this.name = name;

this.age = age;

this.course = course;

System.out.println("Constructor with 3 parameters called");

// Method to display student details

public void displayInfo() {

System.out.println("Name: " + name + ", Age: " + age + ", Course: " + course);

}
public static void main(String[] args) {

Student student1 = new Student(); // Calls the default constructor

student1.displayInfo();

Student student2 = new Student("Dipak&Tushar", 20); // Calls the constructor with 2 parameters

student2.displayInfo();

Student student3 = new Student("sakshi", 22, "IT"); // Calls the constructor with 3 parameters

student3.displayInfo();

//name:Dipak&Tushar

Output:

Conclusion

By completing this experiment, we learned how to define a class in Java, create an array of objects, and iterate
over that array to print the details of each object. This exercise reinforces key object-oriented programming
concepts, particularly working with arrays of objects, which is a common scenario in software development.
Experiment 7
Aim: To Demonstrate Constructor Chaining.

Prerequisite:

1. Constructors: These are special methods used to initialize objects. They are called when an object
is created, ensuring it is properly set up.
2. Constructor Overloading: This occurs when a class has more than one constructor with different
parameter lists, providing flexibility in how objects are initialized.

Theory:

1. What is a Constructor? A constructor is a block of code that initializes an object when it is created.
It sets up initial values for object attributes and prepares resources that the object might need
during its lifecycle. Constructors share the same name as their class and cannot return any type.
Constructors are essential for assigning values to the fields of an object and ensuring it is ready to
be used.
2. Constructor Chaining: Constructor chaining occurs when one constructor calls another constructor
to avoid duplicating code. This practice ensures that common initialization code is centralized,
promoting efficiency and reducing redundancy.
3. Types of Constructor Chaining:
1. Within the Same Class: When constructors within the same class call each other, this is done
using the this() keyword. For instance, you might have a constructor that takes no arguments
call another constructor that requires arguments, ensuring all fields are properly initialized.
This helps when you have multiple constructors with different parameters but want to
ensure that some initialization code is always executed.
2. Between Parent and Child Classes: When constructor chaining happens between a parent
and child class, it is done using the super() keyword. This is critical for object-oriented
programming, where a child class might rely on the parent class's constructor to set up
inherited fields. The super() call ensures that parent class attributes are initialized before the
child class adds its own logic.
4. Key Points:
o Order of Calls:
▪ In the case of constructor chaining within the same class, the this() call must be the first line in
the constructor to ensure proper execution flow.
▪ For chaining between parent and child classes, super() must be the first line in the constructor to
ensure that the parent class's attributes are initialized before any child-specific logic is executed.
o Purpose: Constructor chaining centralizes common initialization logic, which minimizes code
duplication. This not only improves maintainability but also reduces the chance of errors in
object creation.
o Access Control: The visibility of constructors affects constructor chaining. For example, a
child class cannot call a private constructor in the parent class using super(). Access must be
public or protected.
5. Characteristics of a Constructor:
o Same Name as the Class: This rule ensures that constructors are easily identifiable as special
methods for object initialization.
o No Return Type: Constructors cannot return any values. They are only meant to initialize
objects, and returning values would conflict with that purpose.
o Initialization Code: Constructors are typically used to set up initial values for object fields,
open connections, or perform other setup activities that are essential before the object can
be used.

Program:

class Animal {

String name;

Animal() {

System.out.println("Animal constructor called");

Animal(String name) {

this(); // calls the no-arg constructor

this.name = name;

System.out.println("Animal constructor with name called");

class Dog extends Animal {

int age;

Dog() {

super(); // calls the no-arg constructor of Animal

System.out.println("Dog constructor called");

Dog(String name, int age) {

super(name); // calls the constructor of Animal with name

this.age = age;

System.out.println("Dog constructor with name and age called");

}
class Bulldog extends Dog {

String breed;

Bulldog() {

super(); // calls the no-arg constructor of Dog

System.out.println("Bulldog constructor called");

Bulldog(String name, int age, String breed) {

super(name, age); // calls the constructor of Dog with name and age

this.breed = breed;

System.out.println("Bulldog constructor with name, age, and breed called");

public class ConstructorChainingExample {

public static void main(String[] args) {

Bulldog bulldog = new Bulldog("Fido", 3, "English Bulldog");

OUTPUT:-

Conclusion:

Constructor chaining and overloading offer a powerful way to manage object initialization efficiently. Constructor
chaining allows multiple constructors to share common setup logic, which reduces redundancy and errors. This is
especially useful in classes with complex initializations or when dealing with inheritance in object-oriented design.
Experiment 8
Aim: Write a Java program to add n strings in a vector array.

Prerequisite: JDK 17

Theory: Vector is part of the Java Collections Framework and is similar to an array, but with two key

differences: it can dynamically grow or shrink in size, and it is synchronized.

Before you start to use vectors, import it from the java.util.package as follow:

import java.util.Vector ;

Creating a Vector:

You can create a Vector using one of its constructors.

For example:

import java.util.Vector;

public class VectorExample {

public static void main(String[] args) {

// Creating a Vector of Strings

Vector<String> vector = new Vector<>();

// Creating a Vector with initial capacity

Vector<Integer> vectorWithCapacity = new Vector<>(10);

// Creating a Vector with initial capacity and capacity increment

Vector<Double> vectorWithCapacityAndIncrement = new Vector<>(10, 5);

About Vectors:

• A vector in java is a dynamic data structure that can be accessed using an integer index.

• Though similar to ArrayList, it is synchronized, containing some legacy methods not available in the
collection framework.

• Insertion order is maintained.

• It is rarely used in a non-thread environment.


• Due to synchronization, vectors have a poor performance in searching, adding, updating, and deleting
elements.

• Iterators of vector class fail fast and throw the ConcurrentModificationException in case of concurrent
modification.

• A stack is its directly known subclass.

Constructors:

1. Vector(int initialCapacity, int Increment):

This creates a vector in java with an initial capacity as specified, and the increment is

also specified. With increment, the number of elements allocated each time the vector is resized

upward is specified.

Syntax:

Vector<V> e = new Vector<V>(int initialCapacity, int Increment);

2. Vector(int initialCapacity):

It creates a vector in java with an initial capacity equal to size as specified.

Syntax:

Vector<V> e = new Vector<V>(int initialCapacity);

3. Vector():

It creates a vector in java with an initial default capacity of 10.

Syntax:

Vector<V> e = new Vector<V>();

4. Vector(Collection c):

It creates a vector in java whose elements are those of collection c.

Syntax:

Vector<V> e = new Vector<V>(Collection c);

Methods:

Here are some frequently used methods of vector in java:

1. Add Elements

Boolean add(Object o)- An element is appended at the end of the vector Void add( int index V element)- The
given element is added to the specified index in the vector
2. Remove Elements

Boolean Remove (object o) – used to remove the element at the specified index in the vector. When the element
is removed, all the elements are shifted left to fill the spaces; the indices are

then updated.

3. Change Elements

The set () method can be used to change the element after adding the elements. The elements

index can be referenced as a vector is indexed. This method takes the index and the updated

element.

4. Iterate the Vector

There are several ways to loop through a vector. One of them is the get() method.

Advantages of Vector in Java:

The dynamic size of vectors avoids memory wastage, and the size of our data structure can be

changed any time in the middle of the program.

Both vectors and Array Lists are dynamic. However, vectors are more advantageous as:

• Vectors are synchronized.

• It has some legacy functions that cannot be implemented on Array Lists.

Program Code:

import java.util.Scanner;

import java.util.Vector;

public class StringVector {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

Vector<String> stringVector = new Vector<>();

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

int n = scanner.nextInt();

scanner.nextLine(); // Consume newline


System.out.println("Enter the strings:");

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

stringVector.add(scanner.nextLine());

while (true) {

System.out.print("Enter a new string (or 'exit' to quit): ");

String newString = scanner.nextLine();

if (newString.equalsIgnoreCase("exit")) {

break;

stringVector.add(newString); // Add new string to the vector

// Display all strings before exiting

System.out.println("Strings in the vector:");

for (String str : stringVector) {

System.out.println(str);

scanner.close(); // Close the scanner to avoid resource leak

Output:
Conclusion: In this experiment we studied that, a vector in java is a dynamic array with no size

limit that is part of the Java Collection Framework. We also studied the various constructors and

popularly used methods of vectors.


Experiment 9
Aim: Write a program to study concepts of inheritance.

Requirements: JDK 1.7/8

Theory:

Inheritance is one of the three foundation principles of object-oriented programming because it

allows the creation of hierarchical classifications.

Inheritance Basics: Java supports inheritance by allowing one class to incorporate another class into its
declaration. This is done by using the extended keyword. Thus, the subclass adds to (extends) the superclass.
When a class inherits from another class, the child class automatically inherits all the characteristics (member
variables) and behavior (methods) from the parent class. Inheritance is always additive; there is no way to inherit
from a class and get less than what the parent class has. Inheritance in Java is handled through the keyword
extends. When one class inherits from Another class, the child’s class extends the parent class.

For example,

public class DogClass extends MammalClass { ... }

The items that men and dogs have in common could be said to be common to all mammals: therefore, you
can create a MammalClass to handle these similarities.

Access modifiers:

It’s important to understand when members (both variables and methods) in the class are accessible.

Why Do We Need Java Inheritance?

• Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.

• Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by
which Java achieves Run Time Polymorphism.

• Abstraction: The concept of abstract where we do not have to provide all details, is achieved through
inheritance. Abstraction only shows the functionality to the user.

Important Terminologies Used in Java Inheritance

• Class: Class is a set of objects which shares common characteristics/ behavior and common properties/
attributes. Class is not a real-world entity. It is just a template or Blueprints or prototype from which
objects are created.

• Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base class
or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.

• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and methods of the existing class.

Types of Inheritance:

1. Single Inheritance

2. Multilevel Inheritance

3. Hierarchical Inheritance

4. Multiple Inheritance

5. Hybrid Inheritance

ALGORITHM: 1. Declare super class

2. Add data member and methods

3. Declare sub class extends super class

4. Add data member and methods

Program:

// Abstract class Vehicle


abstract class Vehicle {
private String model;
private int year;
// Constructor to initialize Vehicle
public Vehicle(String model, int year) {
this.model = model;
this.year = year;
}
// Abstract method to be implemented by subclasses
public abstract void startEngine();
// Method to display common Vehicle details
public void displayVehicleDetails() {
System.out.println("Vehicle Model: " + model);
System.out.println("Manufacture Year: " + year);
}
}
// Subclass Car extending Vehicle
class Car extends Vehicle {
private int numberOfDoors;
// Constructor for Car
public Car(String model, int year, int numberOfDoors) {
super(model, year); // Call the Vehicle constructor
this.numberOfDoors = numberOfDoors;
}
// Implementing the abstract method
@Override
public void startEngine() {
System.out.println("Car engine started with key ignition.");
}
// Display Car-specific details
public void displayCarDetails() {
displayVehicleDetails();
System.out.println("Number of Doors: " + numberOfDoors);
}
}
// Subclass Bike extending Vehicle
class Bike extends Vehicle {
private boolean hasCarrier;
// Constructor for Bike
public Bike(String model, int year, boolean hasCarrier) {
super(model, year); // Call the Vehicle constructor
this.hasCarrier = hasCarrier;
}
// Implementing the abstract method
@Override
public void startEngine() {
System.out.println("Bike engine started with kick-start.");
}
// Display Bike-specific details
public void displayBikeDetails() {
displayVehicleDetails();
System.out.println("Has Carrier: " + (hasCarrier ? "Yes" : "No"));
}
}
// Main class to test polymorphism
public class VehicleDemo {
public static void main(String[] args) {
// Creating instances of Car and Bike
Vehicle myCar = new Car("Toyota Corolla", 2020, 4);
Vehicle myBike = new Bike("Yamaha FZ", 2018, true);
// Polymorphism: Treating both Car and Bike as Vehicle
System.out.println("Car Details:");
myCar.displayVehicleDetails();
myCar.startEngine();
System.out.println("\nBike Details:");
myBike.displayVehicleDetails();
myBike.startEngine();
}
}

Output:

Conclusion:

Thus, we have studied the concept of inheritance, types of inheritance and access specifiers.
Experiment 10
Aim: An employee works in a particular department of an organization. Every employee has an employee
number, name and draws a particular salary. Every department has a name and a head of department. The head
of department is an employee. Every year a new head of department takes over. Also, every year an employee is
given an annual salary enhancement. Identify and design the classes for the above description with suitable
instance variables and methods. The classes should be such that they implement information hiding. You must
give logic in support of your design. Also create two objects for each class.

Prerequisite:

1. Classes and Objects: Creating and using classes and objects to represent real-world entities.

2. Encapsulation: The concept of information hiding where data is kept private within a class,
accessible only through methods.

3. Inheritance: How one class can inherit properties and methods from another class.

4. Constructors: Using constructors to initialize objects.

5. Methods: Defining functions within classes that perform actions on instance variables.

Theory:

The problem revolves around modeling an organization where employees work in departments, with each
department having a head. The classes need to represent both employees and departments with proper
information hiding, meaning the sensitive attributes (e.g., salary) should only be accessible through public
methods.

• Encapsulation is important here. Data like salary, employee name, and employee number should
be made private, and public methods should be used to access or modify these fields.

• Class Design:

1. Employee Class:

▪ Attributes: employeeNumber, name, salary

▪ Methods: getSalary(), setSalary(), annualSalaryEnhancement()

2. Department Class:

▪ Attributes: departmentName, headOfDepartment (which is an Employee object)

▪ Methods: changeHeadOfDepartment(), getDepartmentDetails()

Each department can have a head of department that changes every year. The annual salary enhancement can be
implemented as a method in the Employee class.
Program:

public class Employee {

private int employeeNumber;

private String name;

private double salary;

// Constructor

public Employee(int employeeNumber, String name, double salary) {

this.employeeNumber = employeeNumber;

this.name = name;

this.salary = salary;

// Getter methods

public int getEmployeeNumber() {

return employeeNumber;

public String getName() {

return name;

public double getSalary() {

return salary;

// Setter methods

public void setName(String name) {

this.name = name;

public void setSalary(double salary) {

this.salary = salary;

}
// Method to apply salary enhancement

public void applySalaryEnhancement(double percentage) {

if (percentage > 0) {

this.salary += this.salary * (percentage / 100);

Output:-

Conclusion:

This program demonstrates how to model real-world entities using Object-Oriented Programming concepts such
as encapsulation and relationships between objects (Employee and Department). It focuses on data protection
and logical class design that reflects hierarchical relationships within an organization.
Experiment 11
Aim: Create an interface vehicle and classes like bicycle, car, bike etc., having common functionalities and put all
the common functionalities in the interface. Classes like Bicycle, Bike, car etc. implement all these functionalities
in their own class in their own way

Prerequisite:

1. Interfaces in Java: An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types. Interfaces are
used to achieve abstraction and multiple inheritance.

2. Class Implementation: Understanding how classes implement interfaces and provide definitions
for the methods declared in the interface.

3. Polymorphism: Using an interface reference to refer to objects of classes that implement the
interface.

4. Abstraction: Hiding the implementation details of specific functionalities while defining their
structure.

Theory:

In this scenario, we are creating an interface called Vehicle that holds common functionalities such as start (),
stop(), and accelerate(). Each class representing a type of vehicle, such as Bicycle, Car, and Bike, will implement
the Vehicle interface and provide its own version of these functionalities.

• Interface: An interface in Java allows us to define common behaviors for unrelated classes. Since
all vehicles share basic functionalities like starting, stopping, and accelerating, these behaviors will
be declared in the Vehicle interface.

• Class Implementation: The Bicycle, Car, and Bike classes will implement the Vehicle interface and
provide their own way of defining how these behaviors work. For instance, a bicycle may have a
different implementation of acceleration compared to a car.

This approach promotes abstraction and code reusability, as common functionalities are defined once and then
implemented by multiple classes in their unique way.

Program:

interface Vehicle {

void accelerate();

void brake();

void turn(String direction);

void displaySpeed();
}

class Bicycle implements Vehicle {

private int speed;

public void accelerate() {

speed += 5;

public void brake() {

speed -= 5;

public void turn(String direction) {

System.out.println("Turning " + direction);

public void displaySpeed() {

System.out.println("Speed: " + speed);

class Car implements Vehicle {

private int speed;

public void accelerate() {

speed += 10;

public void brake() {

speed -= 10;

public void turn(String direction) {

System.out.println("Turning " + direction);

public void displaySpeed() {


System.out.println("Speed: " + speed);

class Bike implements Vehicle {

private int speed;

public void accelerate() {

speed += 7;

public void brake() {

speed -= 7;

public void turn(String direction) {

System.out.println("Turning " + direction);

public void displaySpeed() {

System.out.println("Speed: " + speed);

class Veh {

public static void main(String[] args) {

Vehicle bicycle = new Bicycle();

bicycle.accelerate();

bicycle.displaySpeed();

bicycle.turn("left");

Vehicle car = new Car();

car.accelerate();

car.displaySpeed();

car.turn("right");
Vehicle bike = new Bike();

bike.accelerate();

bike.displaySpeed();

bike.turn("left");

OUTPUT:

Conclusion:

This program demonstrates how to define common behaviors using interfaces and implement them across
different classes. It showcases the power of abstraction and polymorphism by allowing us to handle different
types of vehicles uniformly.

You might also like