0% found this document useful (0 votes)
20 views48 pages

Summer - Training - File by Divyansh Srivastava

This document is an industrial training report for a Java project submitted by Divyansh Srivastava from Goel Institute of Higher Studies, Lucknow. It includes acknowledgments, a description of the college and training organization, as well as various Java programming exercises. The report aims to fulfill the requirements for the Bachelor of Computer Applications degree for the academic session 2024-2025.

Uploaded by

arjun9654abc
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)
20 views48 pages

Summer - Training - File by Divyansh Srivastava

This document is an industrial training report for a Java project submitted by Divyansh Srivastava from Goel Institute of Higher Studies, Lucknow. It includes acknowledgments, a description of the college and training organization, as well as various Java programming exercises. The report aims to fulfill the requirements for the Bachelor of Computer Applications degree for the academic session 2024-2025.

Uploaded by

arjun9654abc
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/ 48

UNIVERSITY OF LUCKNOW

GOEL INSTITUTE OF HIGHER STUDIES MAHAVIDYLAYA, LUCKNOW


COLLEGE CODE:1164
BACHELOR OF COMPUTER APPLICATION
INDUSTRIAL TRAINING REPORT FILE [NBCA-308P]
“GIHSM JAVA PROJECT”
UNDER GUIDANCE- SUBMITTED BY-
Mr. Arun Singh Yadav DIVYANSH SRIVASTAVA
Assistant professor, Project guide Department of computer Science
Dept. of Computer Application G.I.H.S MAHAVIDYALAYA
G.I.H.S Mahavidyalaya

BCA IIIrd SEMESTER


AUGUST 2024
DEPARTMENT OF COMPUTER SCIENCE
G.I.H.S Mahavidyalaya

CERTIFICATE

This is to certify that the summer training project entitled “JAVA TRAINING” has been

prepared by Mr. Divyansh Srivastava under my supervision. This report has been completed as

a partial fulfilment of the requirements for the award of the degree “Bachelor of Computer

Applications (BCA)” for the academic session 2024-2025.

Dr. Santosh Pandey Mr. Arun Singh Yadav


Principal, Project Guide,
Department of Computer Science, Department of Computer Science,
G.I.H.S Mahavidyalaya,(Lucknow) G.I.H.S Mahavidyalaya,(Lucknow)

1
ACKNOWLEDGEMENT

I would like to express my special thanks of gratitude to our sir Dr. Santosh Pandey as well as

my project guide Mr. Arun Singh Yadav and my trainer Mr. Vivek Agarwal who gave me the

golden opportunity to do this wonderful project which also helped me in doing a lot of research

and I came to know about so many new things. I am really thankful to them.Secondly, I would

like to think my teachers Mr. Hemant Panday, Mr. Shivansh ojha, Mr. Akash Yadav, and Mr.

Pradyumna Mishra who helped me a lot in finalizing this project within the limited time

frame.Also, I would like to thank my parents for moral support and my teachers for their

support in this project.I am making this project to increase my knowledge.Thanks again to

all who helped me.

With Regards,

Divyansh Srivastava
2311644050075
Department of Computer Science,
Goel Institute of Higher Studies Mahavidyalaya, Lucknow

2
ABOUT THE COLLEGE

G.I.H.S.M. Lucknow is one of the premier higher education institution which aims to provide
quality education to the students in the field of technical and professional education. The
institute was established with a vision to bring together the students from all backgrounds and
to motivate them to realise their potentials.

G.I.H.S.M. Lucknow was established in the year 2010. It offers various undergraduate and
postgraduate courses in the field of engineering, computer science and others. Apart from UG
and PG courses, it also has diploma courses in mechanical, civil and electrical engineering
disciplines.

The faculty of G.I.H.S.M. Lucknow is a blend of both industry experts and academicians so
that the students get the best of both the worlds. The faculty believes in imparting both
theoretical and practical knowledge for the overall personality development.

3
TRAINING ORGANIZATION CERTIFICATE

4
ABOUT THE ORGANISATION

SHRI BALAJI INFOTECH the software development company and working for the customer
satisfaction. Shri Balaji Infotech provides professional services focused on custom software
and web solutions for businesses worldwide. Our mission is to deliver cost effective, quality-
centric, timelines and scalable solutions thus helping our clients and partners to achieve
outstanding business results and generate great returns. At the helm of affairs it has strong
technical team to develop and manage software’s and create strong support for large
corporations worldwide.
In Shri Balaji Infotech we are trying to provide high quality human capital practicing ethical
business standards to our clients. We develop high-quality eye catching websites and softwares
that comply with all today's standards.

SHRI BALAJI INFOTECH provides professional services focused on custom software and
web solutions for businesses worldwide. Our mission is to deliver cost effective, quality-
centric, timelines and scalable solutions thus helping our clients and partners to achieve
outstanding business results and generate great returns. At the helm of affairs it has strong
technical team to develop and manage software’s and create strong support for large
corporations worldwide.
SBIT is an Offshore Software Development specialist that combines the definite bottom-line
benefits of Offshore Outsourcing with its recognized expertise in strategic global models that
help it in providing reliable Outsourcing Software Development Solutions. The services offered
cover Custom Software Development, Application Development, Web Application
Development, E-commerce web site design, Web Marketing, Website Design and Software
Maintenance. Our goal is to deliver premium quality software development services and
products while giving unmatched value to enterprises worldwide at an affordable cost. Our
transparent, efficient and flexible world class software development process zero downs risks
of project failures and creates powerful software solutions that meet present as well as future
demands. They can give you real feedback about us. If you have any query regarding our
services just fill our feedback form our business executives will get back to you within 24 hours
or you can contact us through the numbers available on our contact us page.
You can mail us at mail [email protected]

5
ABOUT THE TRAINER

Vivek Agarwal
Email Id:- [email protected]
Contact:- 9935868159
Objective
Process-Oriented Seeking assignment in software development a growth oriented organization
preferably IT, Service Industry and strive for excellence with dedication, positive attitude and
passion towards the work.

Work Experience
(1) Tech Mahindra, STPI Lucknow working as a Software developer, 2005.
(2) Niest Noida working as a Software developer, 2007
(4) Currently running a Education, development and automation firm M/S Shri Balaji Infotech
in Lucknow from 2008.

Technical Expertise:
Programming Languages: C,C++,C#,java,python.
Technologies : Django, REST, API,MERN,MachineLearning.
Web Related : html,css,jquery,bootstrap,react js.
Front End Tools : Visual Studio ,PyCharm,Sublime,vs code.
RDBMS : MS SQL Server ,mysql.
Networking : CCNA

Education:

➢ 1 year Diploma in Networking( CCNA)

➢ 2 year Diploma(Center for development of Advance computing) C-DAC, Pune


➢ MCA from Mahan Institute of Technology(Delhi University).

6
TABLE OF CONTENT

Serial Content Page no.


no.
Title page
Certification of originally
Acknowledgement

1. Basic programs 1-16


1.1. Addition
1.2. Subtraction
1.3. circumference
1.4. Area of square ,rectangle

2. Constructor 16-19
2.1 Default constructor
2.2 Parameter constructor
2.3
3. Inheritance 19-24
3.1 Single inheritance
3.2 Multilevel inheritance
3.3 Hierarchical inheritance
3.4 Hybrid inheritance
3.5 Multiple inheritance

4. Overriding 24-25
5. Overloading 25-26

6. Abstraction 27
6.1 Abstract class

7. Access modifiers 28-33


7.1 Public
7.2 Private
7.3 Default and protected

8. polymorphism 34-35

9. Encapsulation 36

10. Mini Project

7
TOOLS &TECHNOLOGY

During this industrial training I have used various tools for programming, problem solving and
documentation. Here are the tools used during and after that to develop this projects report:

Tools:
• Code Editor: VS Code: Visual Studio Code combines the simplicity of a source code editor
with powerful developer tooling, like IntelliSense code completion and debugging.
First and foremost, it is an editor that gets out of your way. The delightfully frictionless edit-
build-debug cycle means less time fiddling with your environment, and more time executing
on your ideas.
SOME FEATURES OF VS CODE:
1. Command Line
2. Command Palette
3. Git Integration
4. Change language mode
5. Customization
6. Zen Mode
7. Split view
8. Status Bar
9. Debugging
10. Default Keyboard shortcuts

• Java JDK Version- 8.0.2710.9


• Documentation: Microsoft Word

Technology
• Java 8: Java 8 is the most awaited release of Java programming language development
because, in the entire history of Java, it never released that many major features. It consists of
major features of Java. It is a new version of Java and was released by Oracle on 18 March
2014. Java provided support for functional programming, new Java 8 APIs, a new JavaScript
engine, new Java 8 streaming API, functional interfaces, default methods, date-time API
changes, etc.
There are a few major Java 8 features mentioned below:
• Lambda Expressions: Concise functional code using ->.
• Functional Interfaces: Single-method interfaces.
• Introduced and Improved APIs:
Stream API: Efficient Data Manipulation.
Concurrency API Improvements: New classes for parallel processing
▪ Optional Class: Handle null values safely.
▪ forEach() Method in Iterable Interface: Executes an action for each
element.
▪ Default Methods: Evolve interfaces without breaking compatibility.
▪ Static Methods: Allows adding methods with default implementations.
▪ Method References: Refer to methods easily.
• Maven
• SpringBoot

8
ABOUT TOOLS

9
1. Write a program to add two numbers using java.

class Main {

public static void main(String[] args) {

int first = 10;

int second = 20;

int sum = first + second;

System.out.println(first + " + " + second + " = " + sum);

}}

Output.

10+20 = 30

❖ WAP SWAPPING TWO NUMBER USING JAVA.

import java.util.Scanner;
public class SwapTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the first number


System.out.print("Enter the first number: ");
int a = scanner.nextInt();

// Input for the second number


System.out.print("Enter the second number: ");
int b = scanner.nextInt();

// Display original values


System.out.println("Before Swapping: a = " + a + ", b = " + b);
// Swapping using a temporary variable
int temp = a;
a = b;
b = temp;

// Display swapped values using temporary variable


System.out.println("After Swapping (using temp): a = " + a + ", b = " + b);

// Re-swap to demonstrate the second method


// Reassign original values for demonstration
temp = a;
a = b;

10
b = temp;

// Swapping without a temporary variable


a = a + b; // Step 1: Sum a and b
b = a - b; // Step 2: Assign new value of b
a = a - b; // Step 3: Assign new value of a

// Display swapped values without using temporary variable


System.out.println("After Swapping (without temp): a = " + a + ", b = " + b);

scanner.close();
}
}
Output

Enter the first number: 5


Enter the second number: 10
Before Swapping: a = 5, b = 10
After Swapping (using temp): a = 10, b = 5
After Swapping (without temp): a = 5, b = 10

❖ WAP TO FIND THE LARGEST TWO NUMBER.

import java.util.Scanner;

public class LargestOfTwoNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the first number


System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();

// Input for the second number


System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();

// Determine the largest number


if (num1 > num2) {
System.out.println("The largest number is: " + num1);
} else if (num2 > num1) {
System.out.println("The largest number is: " + num2);
} else {
System.out.println("Both numbers are equal.");
}

scanner.close();

11
}
}

Output.
Enter the first number: 15
Enter the second number: 10
The largest number is: 15

❖ WAP TO CHECK IF A NUMBER IS DIVISIBLE BY 5.

import java.util.Scanner;

public class DivisibleByFive {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the number


System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Check if the number is divisible by 5


if (number % 5 == 0) {
System.out.println(number + " is divisible by 5.");
} else {
System.out.println(number + " is not divisible by 5.");
}

scanner.close();
}
}

Output.
Enter a number: 25
25 is divisible by 5.

❖ WAP TO CHECK IF A NUMBER IS MULTIPLE BY BOTH 3AND 5.

import java.util.Scanner;

public class MultipleOfThreeAndFive {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the number


System.out.print("Enter a number: ");
int number = scanner.nextInt();

12
// Check if the number is a multiple of both 3 and 5
if (number % 3 == 0 && number % 5 == 0) {
System.out.println(number + " is a multiple of both 3 and 5.");
} else {
System.out.println(number + " is not a multiple of both 3 and 5.");
}

scanner.close();
}
}

Output.
Enter a number: 15
15 is a multiple of both 3 and 5.

Enter a number: 10
10 is not a multiple of both 3 and 5.

❖ WAP TO CHECK IF A YEAR IS LEAP YEAR .

import java.util.Scanner;

public class LeapYearChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the year


System.out.print("Enter a year: ");
int year = scanner.nextInt();

// Check if the year is a leap year


booleanisLeapYear;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
isLeapYear = true;
} else {
isLeapYear = false;
}

// Output the result


if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}

scanner.close();
}

13
}
Output.
Enter a year: 2020
2020 is a leap year.
Enter a year: 1900
1900 is not a leap year.

❖ WAP TO CHECK A CHARACTER IS VOWEL OR CONSONANT.

import java.util.Scanner;

public class VowelOrConsonant {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the character


System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);

// Check if the character is a vowel or consonant


if (Character.isLetter(ch)) { // Check if the input is a letter
ch = Character.toLowerCase(ch); // Convert to lowercase for uniformity

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {


System.out.println(ch + " is a vowel.");
} else {
System.out.println(ch + " is a consonant.");
}
} else {
System.out.println("Invalid input. Please enter a letter.");
}

scanner.close();
}
}
Output.
Enter a character: A
A is a vowel.

Enter a character: b
b is a consonant.

❖ WAP TO CHECK A CHARACTER IS UPPERCASE AND LOWERCASE.

import java.util.Scanner;

public class UppercaseLowercaseChecker {

14
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the character


System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);

// Check if the character is a letter


if (Character.isLetter(ch)) {
if (Character.isUpperCase(ch)) {
System.out.println(ch + " is an uppercase letter.");
} else {
System.out.println(ch + " is a lowercase letter.");
}
} else {
System.out.println("Invalid input. Please enter a letter.");
}

scanner.close();
}
}

Output.

Enter a character: A
A is an uppercase letter.

Enter a character: g
g is a lowercase letter.

❖ WAP TO FIND THE DAY OF THE WEEK USING SWITCH CASE.

import java.util.Scanner;

public class DayOfWeek {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the day number


System.out.print("Enter a number (1-7) for the day of the week: ");
int day = scanner.nextInt();

// Determine the day of the week using switch case


String dayName;
switch (day) {
case 1:
dayName = "Monday";

15
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid input. Please enter a number between 1 and 7.";
}

// Output the result


System.out.println(dayName);

scanner.close();
}
}

Output.
Enter a number (1-7) for the day of the week: 3
Wednesday

Enter a number (1-7) for the day of the week: 8


Invalid input. Please enter a number between 1 and 7.

❖ WAP TO FIND AREA OF TRIANGLE.


public class TriangleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the base


System.out.print("Enter the base of the triangle: ");
double base = scanner.nextDouble();

// Input for the height


System.out.print("Enter the height of the triangle: ");

16
double height = scanner.nextDouble();

// Calculate the area


double area = 0.5 * base * height;

// Output the result


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

scanner.close();
}
}
Output:
Enter the base of the triangle: 5
Enter the height of the triangle: 10
The area of the triangle is: 25.0

❖ WAP TO FIND SIMPLE INTEREST.

import java.util.Scanner;

public class SimpleInterestCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the principal amount


System.out.print("Enter the principal amount: ");
double principal = scanner.nextDouble();

// Input for the rate of interest


System.out.print("Enter the rate of interest (in %): ");
double rate = scanner.nextDouble();

// Input for the time (in years)


System.out.print("Enter the time (in years): ");
double time = scanner.nextDouble();

// Calculate simple interest


double simpleInterest = (principal * rate * time) / 100;

// Output the result


System.out.println("The simple interest is: " + simpleInterest);

scanner.close();
}
}

OUTPUT:-

17
Enter the principal amount: 1000
Enter the rate of interest (in %): 5
Enter the time (in years): 2
The simple interest is: 100.0

❖ WAP IN JAVA TO INCREMENT AND DECREMENT A NUM.


import java.util.Scanner;

public class IncrementDecrement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the number


System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Increment the number


int incrementedNumber = number + 1;

// Decrement the number


int decrementedNumber = number - 1;

// Output the results


System.out.println("Original number: " + number);
System.out.println("Incremented number: " + incrementedNumber);
System.out.println("Decremented number: " + decrementedNumber);

scanner.close();
}
}
OUTPUT:-
Enter a number: 10
Original number: 10
Incremented number: 11
Decremented number: 9

❖ WAP IN JAVA TO FIND PARAMETER OF A SQUARE


import java.util.Scanner;
public class SquarePerimeter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the side length of the square


System.out.print("Enter the length of a side of the square: ");
double side = scanner.nextDouble();

18
// Calculate the perimeter
double perimeter = 4 * side;

// Output the result


System.out.println("The perimeter of the square is: " + perimeter);

scanner.close();
}
}
OUTPUT
Enter the length of a side of the square: 5
The perimeter of the square is: 20.0

❖ WAP IN JAVA TO FIND CIRCUMFERENCE OF CIRCLE.

import java.util.Scanner;

public class CircleCircumference {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the radius of the circle


System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();

// Calculate the circumference


double circumference = 2 * Math.PI * radius;

// Output the result


System.out.println("The circumference of the circle is: " + circumference);

scanner.close();
}
}
OUTPUT:-

Enter the radius of the circle: 5


The circumference of the circle is: 31.41592653589793
❖ WAP IN JAVA USING SIMPLE INSTANCE METHOD TO CALCULATE AREA OF
RECTANGLE.

import java.util.Scanner;

class Rectangle {
// Instance variables
private double length;
private double width;

19
// Constructor to initialize the rectangle
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Instance method to calculate area


public double calculateArea() {
return length * width;
}
}

public class AreaCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the length and width of the rectangle


System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();

// Create a Rectangle object


Rectangle rectangle = new Rectangle(length, width);

// Calculate and display the area


double area = rectangle.calculateArea();
System.out.println("The area of the rectangle is: " + area);

scanner.close();
}
}

OUTPUT:-

Enter the length of the rectangle: 5


Enter the width of the rectangle: 10
The area of the rectangle is: 50.0

❖ JAVA PROGRAM TO CALCULATE AREA OF A RECTANGLE USING AN INSTANCE


METHOD WITH PARAMETERS

import java.util.Scanner;

class Rectangle {
// Instance method to calculate area with parameters

20
public double calculateArea(double length, double width) {
return length * width;
}
}

public class AreaCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the length and width of the rectangle


System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();

// Create a Rectangle object


Rectangle rectangle = new Rectangle();

// Calculate and display the area


double area = rectangle.calculateArea(length, width);
System.out.println("The area of the rectangle is: " + area);

scanner.close();
}
}

OUTPUT:-

Enter the length of the rectangle: 5


Enter the width of the rectangle: 10
The area of the rectangle is: 50.0

❖ WAP IN JAVA USING DEFAULT CONSTRUCTOR

// Class definition
class Person {
// Instance variables
String name;
int age;

// Default constructor
public Person() {
name = "Unknown";
age = 0;
}

21
// Method to display person details
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

public class DefaultConstructorExample {


public static void main(String[] args) {
// Create an instance of the Person class using the default constructor
Person person = new Person();

// Display the default values


person.displayInfo();
}
}

OUTPUT:-

Name: Unknown
Age: 0

❖ JAVA PROGRAM WITH CONSTRUCTOR HAVING MULTIPLE PARAMETERS

import java.util.Scanner;

class Rectangle {
// Instance variables
private double length;
private double width;

// Constructor with multiple parameters


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Method to calculate area


public double calculateArea() {
return length * width;
}

// Method to calculate perimeter


public double calculatePerimeter() {
return 2 * (length + width);
}
}

22
public class RectangleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the length and width of the rectangle


System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();

// Create a Rectangle object using the constructor


Rectangle rectangle = new Rectangle(length, width);

// Calculate and display the area and perimeter


double area = rectangle.calculateArea();
double perimeter = rectangle.calculatePerimeter();
System.out.println("The area of the rectangle is: " + area);
System.out.println("The perimeter of the rectangle is: " + perimeter);

scanner.close();
}
}

OUTPUT:-

Enter the length of the rectangle: 5


Enter the width of the rectangle: 10
The area of the rectangle is: 50.0
The perimeter of the rectangle is: 30.0

❖ WAP IN JAVA USING SINGLE INHERITANCE

// Base class
class Animal {
// Method in the base class
public void eat() {
System.out.println("This animal eats food.");
}
}

// Derived class
class Dog extends Animal {
// Method in the derived class
public void bark() {
System.out.println("The dog barks.");
}
}

23
public class SingleInheritanceExample {
public static void main(String[] args) {
// Create an instance of the Dog class
Dog dog = new Dog();

// Call methods from both the base and derived classes


dog.eat(); // Method from the Animal class
dog.bark(); // Method from the Dog class
}
}

OUTPUT:-

This animal eats food.


The dog barks.

❖ WAP IN JAVA USING MULTILEVEL INHERITANCE

// Base class
class Animal {
// Method in the base class
public void eat() {
System.out.println("This animal eats food.");
}
}

// First derived class


class Dog extends Animal {
// Method in the first derived class
public void bark() {
System.out.println("The dog barks.");
}
}

// Second derived class


class Bulldog extends Dog {
// Method in the second derived class
public void showAffection() {
System.out.println("The bulldog shows affection.");
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
// Create an instance of the Bulldog class
Bulldog bulldog = new Bulldog();

// Call methods from the multilevel inheritance hierarchy

24
bulldog.eat(); // Method from the Animal class
bulldog.bark(); // Method from the Dog class
bulldog.showAffection(); // Method from the Bulldog class
}
}

OUTPUT:-

This animal eats food.


The dog barks.
The bulldog shows affection.

❖ WAP IN JAVA USING HIERARCHICAL INHERITANCE

// Base class
class Animal {
// Method in the base class
public void eat() {
System.out.println("This animal eats food.");
}
}

// Derived class 1
class Dog extends Animal {
// Method in the Dog class
public void bark() {
System.out.println("The dog barks.");
}
}

// Derived class 2
class Cat extends Animal {
// Method in the Cat class
public void meow() {
System.out.println("The cat meows.");
}
}

public class HierarchicalInheritanceExample {


public static void main(String[] args) {
// Create instances of Dog and Cat classes
Dog dog = new Dog();
Cat cat = new Cat();

// Call methods from the Animal class and derived classes


dog.eat(); // Method from the Animal class
dog.bark(); // Method from the Dog class

25
cat.eat(); // Method from the Animal class
cat.meow(); // Method from the Cat class
}
}

OUTPUT:-

This animal eats food.


The dog barks.
This animal eats food.
The cat meows.

❖ WAP IN JAVA USING HYBRID INHERITANCE

// Base class
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}

// Derived class 1
class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}

// Derived class 2
class Cat extends Animal {
public void meow() {
System.out.println("The cat meows.");
}
}

// Interface
interface Pet {
void play();
}

// Derived class 3 that implements the interface


class Bulldog extends Dog implements Pet {
public void play() {
System.out.println("The bulldog plays fetch.");
}
}

public class HybridInheritanceExample {

26
public static void main(String[] args) {
// Create instances of Dog, Cat, and Bulldog classes
Dog dog = new Dog();
Cat cat = new Cat();
Bulldog bulldog = new Bulldog();

// Call methods from the Animal class and derived classes


dog.eat(); // Method from the Animal class
dog.bark(); // Method from the Dog class

cat.eat(); // Method from the Animal class


cat.meow(); // Method from the Cat class

bulldog.eat(); // Method from the Animal class


bulldog.bark(); // Method from the Dog class
bulldog.play(); // Method from the Pet interface
}
}

OUTPUT:-

This animal eats food.


The dog barks.
This animal eats food.
The cat meows.
This animal eats food.
The dog barks.
The bulldog plays fetch.

❖ WAP IN JAVA OF MULTIPLE INHERITANCE USING INTERFACE


// First interface
interface CanBark {
void bark();
}

// Second interface
interface CanMeow {
void meow();
}

// Class implementing multiple interfaces


class Dog implements CanBark {
@Override
public void bark() {
System.out.println("The dog barks.");
}
}

27
// Class implementing multiple interfaces
class Cat implements CanMeow {
@Override
public void meow() {
System.out.println("The cat meows.");
}
}

// Class that implements both interfaces


class Bulldog extends Dog implements CanMeow {
@Override
public void meow() {
System.out.println("The bulldog can't meow, but it barks!");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
Bulldog bulldog = new Bulldog();

// Calling methods from Dog and Cat classes


dog.bark(); // Method from CanBark interface
cat.meow(); // Method from CanMeow interface

// Calling methods from Bulldog class


bulldog.bark(); // Inherited from Dog
bulldog.meow(); // Implemented in Bulldog
}
}

OUTPUT:-

The dog barks.


The cat meows.
The dog barks.
The bulldog can't meow, but it barks!

❖ WAP IN JAVA USING BASIC METHOD OVERLOADING

public class MethodOverloadingExample {

// Method to add two integers


public int add(int a, int b) {
return a + b;
}

28
// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two doubles


public double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


MethodOverloadingExample calculator = new MethodOverloadingExample();

// Call the add method with two integers


System.out.println("Sum of two integers: " + calculator.add(5, 10));

// Call the overloaded add method with three integers


System.out.println("Sum of three integers: " + calculator.add(5, 10, 15));

// Call the overloaded add method with two doubles


System.out.println("Sum of two doubles: " + calculator.add(5.5, 10.5));
}
}

OUTPUT:-

Sum of two integers: 15


Sum of three integers: 30
Sum of two doubles: 16.0

❖ WAP IN JAVA USING METHOD OVERLOADING WITH DIFFERENT PARAMETER

public class AreaCalculator {

// Method to calculate the area of a rectangle


public double calculateArea(double length, double width) {
return length * width;
}

// Overloaded method to calculate the area of a triangle


public double calculateArea(double base, double height) {
return 0.5 * base * height;
}

// Overloaded method to calculate the area of a circle


public double calculateArea(double radius) {
return Math.PI * radius * radius;
}

29
public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();

// Calculate the area of a rectangle


System.out.println("Area of Rectangle (length: 5, width: 10): " + calculator.calculateArea(5, 10));

// Calculate the area of a triangle


System.out.println("Area of Triangle (base: 5, height: 10): " + calculator.calculateArea(5, 10));

// Calculate the area of a circle


System.out.println("Area of Circle (radius: 7): " + calculator.calculateArea(7));
}
}

OUTPUT:-

Area of Rectangle (length: 5, width: 10): 50.0


Area of Triangle (base: 5, height: 10): 25.0
Area of Circle (radius: 7): 153.93804002589985

❖ WRITE A JAVA PROGRAM USING ABSTRACT CLASS.


// Abstract class
abstract class Animal {
// Abstract method
abstract void sound();

// Regular method
void sleep() {
System.out.println("The animal is sleeping.");
}
}

// Dog class extending Animal


class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}

// Cat class extending Animal


class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}

30
}

// Main class to test the abstract class and its implementations


public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Creating a Dog object
Animal myCat = new Cat(); // Creating a Cat object

myDog.sound(); // Output: Bark


myDog.sleep(); // Output: The animal is sleeping.

myCat.sound(); // Output: Meow


myCat.sleep(); // Output: The animal is sleeping.
}
}

Output:
Bark
The animal is sleeping.
Meow
The animal is sleeping.
❖ WRITE A JAVA PROGRAM USING ABSTRACTION

/abstract parent class


Abstract class animal {
//abstract method
public abstract void sound ( ) ;
}
Public class lion extends animal {
Public void sound ( ) {
System.out.println(“ roar “ );
}
public Static void main ( Stringargs [ ] ) {
animal obj = new lion ( );
obj. sound ();
}
}

Output:
Roar

❖ WAP IN JAVA USING PRIVATE CLASS

public class OuterClass {

// Private nested class

31
private class InnerClass {
private String message;

// Constructor for the inner class


public InnerClass(String msg) {
this.message = msg;
}

// Method to display the message


public void displayMessage() {
System.out.println("Message from InnerClass: " + message);
}
}

// Method to create an instance of the InnerClass


public void createInnerClass(String msg) {
InnerClass inner = new InnerClass(msg);
inner.displayMessage();
}
}

public class PrivateClassExample {


public static void main(String[] args) {
OuterClass outer = new OuterClass();

// Create an inner class instance and display the message


outer.createInnerClass("Hello from the private inner class!");
}
}

OUTPUT:-

Message from InnerClass: Hello from the private inner class!

❖ WAP CLASS WITH MULTIPLE OBJECT.


// Class definition
class Car {
// Instance variables
String make;
String model;
int year;

// Constructor to initialize Car objects


public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

32
// Method to display car details
public void displayInfo() {
System.out.println("Car Make: " + make);
System.out.println("Car Model: " + model);
System.out.println("Car Year: " + year);
System.out.println(" ------------------- ");
}
}

public class MultipleObjectsExample {


public static void main(String[] args) {
// Creating multiple Car objects
Car car1 = new Car("Toyota", "Camry", 2020);
Car car2 = new Car("Honda", "Civic", 2019);
Car car3 = new Car("Ford", "Mustang", 2021);

// Displaying the details of each car


car1.displayInfo();
car2.displayInfo();
car3.displayInfo();
}
}

Output:
Car Make: Toyota
Car Model: Camry
Car Year: 2020

Car Make: Honda


Car Model: Civic
Car Year: 2019

Car Make: Ford


Car Model: Mustang
Car Year: 2021

❖ WRITE A JAVA PROGRAM METHOD WITH PARAMETER


// Class definition
class Calculator {

// Method to add two numbers


public int add(int a, int b) {
return a + b;
}

// Method to subtract two numbers


public int subtract(int a, int b) {

33
return a - b;
}

// Method to multiply two numbers


public int multiply(int a, int b) {
return a * b;
}

// Method to divide two numbers


public double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
System.out.println("Cannot divide by zero.");
return 0; // or throw an exception
}
}
}

public class MethodWithParameterExample {


public static void main(String[] args) {
// Create an instance of the Calculator class
Calculator calculator = new Calculator();

// Call the methods with parameters and print the results


System.out.println("Addition (5 + 3): " + calculator.add(5, 3));
System.out.println("Subtraction (5 - 3): " + calculator.subtract(5, 3));
System.out.println("Multiplication (5 * 3): " + calculator.multiply(5, 3));
System.out.println("Division (5 / 2): " + calculator.divide(5, 2));
System.out.println("Division (5 / 0): " + calculator.divide(5, 0)); // Demonstrating division by zero
}
}

Output:
Addition (5 + 3): 8
Subtraction (5 - 3): 2
Multiplication (5 * 3): 15
Division (5 / 2): 2.5
Cannot divide by zero.
Division (5 / 0): 0.0

❖ WRITE A JAVA PROGRAM OF INTERFACE


// Defining a simple interface
interface Greeting {
void sayHello(); // Abstract method
}

// Implementing the Greeting interface in a class

34
class EnglishGreeting implements Greeting {
@Override
public void sayHello() {
System.out.println("Hello!");
}
}

// Main class to test the interface


public class Main {
public static void main(String[] args) {
Greeting greeting = new EnglishGreeting(); // Create an instance of EnglishGreeting
greeting.sayHello(); // Call the method
}
}
Output:
Hello!

❖ WRITE A JAVA PROGRAM USING PACKAGE


import com.example.shapes.Circle;
import com.example.shapes.Rectangle;

public class Main {


public static void main(String[] args) {
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);

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


System.out.println("Area of Rectangle: " + rectangle.area()); //
}
}
Output:
Area of Circle: 78.53981633974483
Area of Rectangle: 24.0

❖ WRITE A JAVA PROGRAM USING ARRAY.

public class ArrayExample {


public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = {10, 20, 30, 40, 50};

// Calculate the sum of the array elements


int sum = 0;
for (int number : numbers) {
sum += number;

35
}

// Calculate the average


double average = sum / (double) numbers.length;

// Display the results


System.out.println("Sum of the array: " + sum); // Output: Sum of the array: 150
System.out.println("Average of the array: " + average); // Output: Average of the array: 30.0
}
}
Output:
Sum of the array: 150
Average of the array: 30.0

❖ REVERSE A NUMBER USING A WHILE LOOP IN JAVA

class Main {
public static void main(String[] args) {

int num = 1234, reversed = 0;

System.out.println("Original Number: " + num);

// run loop until num becomes 0


while(num != 0) {

// get last digit from num


int digit = num % 10;
reversed = reversed * 10 + digit;

// remove the last digit from num


num /= 10;
}

System.out.println("Reversed Number: " + reversed);


}
}

Output:
Reversed Number: 4321

❖ JAVA PROGRAM TO CHECK PALINDROME

import java.util.Scanner;

public class PalindromeCheck {

36
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String input = scanner.nextLine();

// Remove spaces and convert to lowercase for uniformity


String cleanedInput = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

// Check if the cleaned input is a palindrome


if (isPalindrome(cleanedInput)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}

scanner.close();
}

// Method to check if a string is a palindrome


public static booleanisPalindrome(String str) {
int left = 0;
int right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {
return false; // Not a palindrome
}
left++;
right--;
}
return true; // Is a palindrome
}
}

Output:
Enter a string: A man, a plan, a canal, Panama
The string is a palindrome.

❖ JAVA PROGRAM TO CONVERT BYTE ARRAY TO HEXADECIMAL


public class ByteArrayToHex {
public static void main(String[] args) {
// Example byte array
byte[] byteArray = {10, 15, 16, 31, 100, -1};

// Convert byte array to hexadecimal


String hexString = bytesToHex(byteArray);

37
// Display the result
System.out.println("Hexadecimal representation: " + hexString);
}

// Method to convert byte array to hexadecimal string


public static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();

for (byte b : bytes) {


// Convert each byte to hex and append to the StringBuilder
String hex = Integer.toHexString(b & 0xFF); // Use & 0xFF to handle negative bytes
if (hex.length() < 2) {
hexString.append('0'); // Pad with leading zero if necessary
}
hexString.append(hex);
}

return hexString.toString().toUpperCase(); // Return the result in uppercase


}
}

Output:
Hexadecimal representation: 0A0F101F64FF

❖ WRITE A JAVA PROGRAM USING POLYMORPHISM

// Base class
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Subclass Dog
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}

// Subclass Cat
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}

38
}

// Main class to demonstrate polymorphism


public class PolymorphismExample {
public static void main(String[] args) {
Animal myDog = new Dog(); // Upcasting to Animal type
Animal myCat = new Cat(); // Upcasting to Animal type

// Calling the overridden methods


myDog.makeSound(); // Output: Dog barks
myCat.makeSound(); // Output: Cat meows

// Creating an array of Animal type


Animal[] animals = {new Dog(), new Cat()};

// Iterating over the array and calling makeSound


for (Animal animal : animals) {
animal.makeSound(); // Calls the respective overridden method
}
}
}

Output:
Dog barks
Cat meows
Dog barks
Cat meows

❖ WRITE A JAVA PROGRAM USING ENCAPSULATION


class animal {
// private field
private int age;
//getter method
Public int getage( ) {
return age;
}
//setter method
public void setAge( int age ) {
this. Age = age;
}
}
class Main {
public static void main (String args []);
//create an object of person
Animal a1= new Animal ();
//change age using setter

39
A1. setAge (12);
// access age using getter
System.out.println(“ animal age is ” + a1. getage( ) );
}
}

Output:

Animal age is 12

40
PROJECT CODE

package MyPackage;

import jakarta.servlet.ServletException;

import jakarta.servlet.annotation.WebServlet;

import jakarta.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Date;
import java.util.Scanner;

import com.google.gson.Gson;

import com.google.gson.JsonObject;

/**

* Servlet implementation class MyServlet

*/

public class MyServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public MyServlet() {

super();

41
// TODO Auto-generated constructor stub

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// TODO Auto-generated method stub

response.sendRedirect("index.html");

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// TODO Auto-generated method stub

//API Key

String apiKey = "ecbc16c33017929a5b62a5db187969b5";

// Get the city from the form input

String city = request.getParameter("city");

// Create the URL for the OpenWeatherMap API request

String apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid="


+ apiKey;

try {

URL url = new URL(apiUrl);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

42
InputStream inputStream = connection.getInputStream();

InputStreamReader reader = new InputStreamReader(inputStream);

// System.out.println(reader);

Scanner scanner = new Scanner(reader);

StringBuilder responseContent = new StringBuilder();

while (scanner.hasNext()) {

responseContent.append(scanner.nextLine());

// System.out.println(responseContent);

scanner.close();

// Parse the JSON response to extract temperature, date, and humidity

Gson gson = new Gson();

JsonObject jsonObject = gson.fromJson(responseContent.toString(), JsonObject.class);

//Date & Time

long dateTimestamp = jsonObject.get("dt").getAsLong() * 1000;

String date = new Date(dateTimestamp).toString();

//Temperature

double temperatureKelvin =
jsonObject.getAsJsonObject("main").get("temp").getAsDouble();

int temperatureCelsius = (int) (temperatureKelvin - 273.15);

//Humidity

int humidity = jsonObject.getAsJsonObject("main").get("humidity").getAsInt();

//Wind Speed

43
double windSpeed = jsonObject.getAsJsonObject("wind").get("speed").getAsDouble();

//Weather Condition

String weatherCondition =
jsonObject.getAsJsonArray("weather").get(0).getAsJsonObject().get("main").getAsString();

// Set the data as request attributes (for sending to the jsp page)

request.setAttribute("date", date);

request.setAttribute("city", city);

request.setAttribute("temperature", temperatureCelsius);

request.setAttribute("weatherCondition", weatherCondition);

request.setAttribute("humidity", humidity);

request.setAttribute("windSpeed", windSpeed);

request.setAttribute("weatherData", responseContent.toString());

connection.disconnect();

} catch (IOException e) {

e.printStackTrace();

// Forward the request to the weather.jsp page for rendering

request.getRequestDispatcher("index.jsp").forward(request, response);

44
ABOUT THE PROJECT

Introduction
The weather forecasting website is designed to provide users with real-time weather
information, including current conditions, forecasts, and severe weather alerts. The website
aims to serve a wide audience, such as travelers, outdoor enthusiasts, and anyone interested in
staying updated on weather changes. The website leverages technologies like HTML, CSS,
JavaScript, and integrates an API (e.g., OpenWeatherMap) to fetch weather data.
Key Features
The website offers several key features, including current weather updates (temperature,
humidity, wind speed), short-term and long-term weather forecasts, and a location search
function. Users can toggle between Celsius and Fahrenheit, ensuring accessibility to a
broader audience. Additionally, the website provides weather alerts for severe conditions,
helping users stay prepared.
API Integration
The weather data is fetched from a third-party weather API, such as OpenWeatherMap. The
API provides accurate and timely data on current weather and forecasts. Integration with the
API is handled via AJAX calls, ensuring the website can display real-time information with
minimal delay.
User Interface and Design
The website features a simple, user-friendly interface, designed to provide a smooth user
experience. It is responsive, ensuring that it works seamlessly on various devices, including
desktops, tablets, and smartphones. The design focuses on clear and easy-to-read weather
information, with an intuitive layout for quick navigation.
Testing and Quality Assurance

45
The website undergoes thorough testing to ensure it functions across different browsers and
devices. Performance testing is also carried out to maintain a fast loading time and ensure the
site is responsive even under heavy traffic. The error handling process ensures users are notified if
there are any issues with fetching data.

Future Enhancements
In the future, the website could be expanded with additional features, such as radar maps,
real-time weather alerts via push notifications, or even a mobile app version. User
personalization options, such as saving preferred locations or switching between different
weather themes, could also be added to improve the user experience.
This version covers the core aspects of the project while keeping it concise and clear.

CONCLUSION
This summer training has provided me with valuable insights and hands-on experience in
various Java concepts and web development. Throughout the training, I learned essential Java
programming techniques, including object-oriented programming (OOP), data structures,
algorithms, and exception handling, all of which were crucial in understanding the
fundamentals of coding and software development. The training also gave me an opportunity
to apply these concepts through practical coding exercises, which enhanced my problem-
solving skills and deepened my understanding of Java.
The mini project of developing a weather forecasting webpage allowed me to integrate my
Java knowledge with web development technologies. By creating a functional and interactive
weather forecasting website, I not only honed my skills in HTML, CSS, and JavaScript but
also learned how to work with APIs to fetch real-time weather data. This project has
significantly improved my understanding of full-stack development and how backend logic
can interact with the frontend for dynamic content delivery.
This training has equipped me with a solid foundation in both Java and web development.
The combination of theoretical learning and practical implementation has boosted my
confidence in taking on more complex programming challenges in the future. I am now better
prepared for advanced learning and real-world applications in software and web
development.

REFERENCES
Java Programming:

• "Head First Java" by Kathy Sierra and Bert Bates. O'Reilly Media, 2nd Edition, 2005.

• "Effective Java" by Joshua Bloch. Addison-Wesley, 3rd Edition, 2018.

46
• "Java: The Complete Reference" by Herbert Schildt. McGraw-Hill Education, 11th Edition,
2018.

• Oracle. Java Documentation. https://docs.oracle.com/en/java/.

Web Development (HTML, CSS, JavaScript):

• "HTML and CSS: Design and Build Websites" by Jon Duckett. Wiley, 2011.

• "JavaScript and JQuery: Interactive Front-End Web Development" by Jon Duckett. Wiley,
2014.

• MDN Web Docs. Mozilla Developer Network. https://developer.mozilla.org/en-US/.

Weather API Integration:

• OpenWeatherMap API Documentation. https://openweathermap.org/api.

• "APIs: A Strategy Guide" by Daniel Jacobson, Greg Brail, and Dan Woods. O'Reilly Media,
2011.

Project Development:

• "Responsive Web Design with HTML5 and CSS3" by Ben Frain. Packt Publishing, 3rd Edition,
2015.

• W3Schools, Web Development Tutorials. https://www.w3schools.com/.

General Programming and Software Development:

• "Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C. Martin. Prentice


Hall, 2008.

• "The Pragmatic Programmer: Your Journey to Mastery" by Andrew Hunt and David Thomas.
Addison-Wesley, 20th Anniversary Edition, 2019.

47

You might also like