0% found this document useful (0 votes)
8 views

OOPS with JAVA Manual

java

Uploaded by

shettykavan006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

OOPS with JAVA Manual

java

Uploaded by

shettykavan006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

JNANA SANGAMA, BELGAVI-590018, KARNATAKA

A J INSTITUTE OF ENGINEERING & TECHNOLOGY


(A unit of Laxmi Memorial Education Trust. (R))
NH - 66, Kottara Chowki, Kodical Cross, Mangalore- 575 006.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


(Accredited by NBA)

STUDENT MANUAL
Course: OBJECT ORIENTED PROGRAMMING WITH JAVA
Course Code: BCS306A
IV-SEMESTER

Prepared by:
Mrs. Sharon D Souza
Assistant Professor
Department of Computer Science & Engineering, AJIET, Mangalore

ACADEMIC YEAR: 2023-24


Object Oriented Programming with JAVA BCS306A

TABLE OF CONTENTS
Item Page No.

Vision, Mission and Program Educational Objectives i

Program Outcomes (POs) and Program Specific Outcomes (PSOs) ii

General Lab Guidelines- Do’s & Don’ts iii-v

Syllabus- Course Objectives & Suggested Learning Resources vi-ix

Course Outcomes- Mapping of Course Outcomes with POs & PSOs x

Assessment Details (both CIE and SEE) -Scheme of Evaluation xi-xii

Rubrics xiii-xiv

List of Major Equipment xv

List of Experiment/Programs & Additional Experiment/Programs xvi

Dept. of CSE, AJIET, Mangalore


VISION OF THE INSTITUTE
“To produce top-quality engineers who are groomed for attaining excellence in their profession and
competitive enough to help in the growth of nation and global society.”

MISSION OF THE INSTITUTE


M1: To offer affordable high-quality graduate program in engineering with value education and
make the students socially responsible.
M2: To support and enhance the institutional environment to attain research excellence in both
faculty and students and to inspire them to push the boundaries of knowledge base.
M3: To identify the common areas of interest amongst the individuals for the effective industry-
institute partnership in a sustainable way by systematically working together.
M4: To promote the entrepreneurial attitude and inculcate innovative ideas among the engineering
professionals.

VISION OF THE DEPARTMENT


“To adapt the evolutionary changes in computer science and expose the students to the cutting-edge
technologies to produce globally competent professionals.”

MISSION OF THE DEPARTMENT


M1: To mould the students by providing quality computer education and by strengthening the
Industry -Academic interface.
M2: To impart the professional skills, innovative research activities and entrepreneurial capabilities
in students.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


After 4 years of graduation, graduates will be able to

PEO1: To develop in students, the ability to solve real life problems by applying fundamental science
and elementary strengths of computer science courses.
PEO2: To mould students, to have a successful career in the IT industry where graduates will be able
to design and implement the needs of society and nation.
PEO3: To transform students, to excel in a competitive world through higher education and indulge in
research through continuous learning process.
Object Oriented Programming with JAVA BCS306A

PROGRAM OUTCOMES (POs)


PO1: Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2: Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3: Design/Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4: Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
PO5: Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities
with an understanding of the limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO9: Individual and Team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11: Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12: Life-Long Learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES (PSOs)


At the end of the program, graduates will be able to
PSO1: Apply engineering principles, professional ethics and fundamental science in designing systems
and communication models (protocols).
PSO2: Design and develop smart and intelligent based applications in computational environment.

Dept. of CSE, AJIET, Mangalore ii


Object Oriented Programming with JAVA BCS306A

GENERAL LAB GUIDELINES

Do's
1. Maintain discipline in the Laboratory.
2. Before entering the Laboratory, keep the footwear on the shoe rack.
3. Proper dress code has to be maintained while entering the Laboratory.
4. Students should carry a lab observation book, student manual and record book completed in
all aspects.
5. Read and understand the logic of the program thoroughly before coming to the laboratory.
6. Enter the login book before switching on the computer.
7. Enter your batch member names and other details in the slips for hardware kits.
8. Students should be at their concerned places; unnecessary movement is restricted.
9. Students should maintain the same computer until the end of the semester.
10. Report any problems in computers/hardware kits to the faculty member in-charge/laboratory
technician immediately.
11. The practical result should be noted down into their observation and the result must be shown
to the faculty member in-charge for verification.
12. After completing the experiments, students should switch off the computers, enter logout
time, return the hardware kits and keep the chairs properly.

Don'ts
1. Do not come late to the Laboratory.
2. Do not enter the laboratory without an ID card, lab dress code, observation book and record.
3. Do not leave the laboratory without the permission of the faculty in-charge.
4. Never eat, drink while working in the laboratory.
5. Do not handle any equipment before reading the instructions/instruction manuals.
6. Do not exchange the computers with others and hardware kits also.
7. Do not misbehave in the laboratory.
8. Do not alter computer settings/software settings.
9. External Disk/drives should not be connected to computers without permission, doing so will
attract fines.
10. Do not remove anything from the kits/experimental set up without permission. Doing so will
attract fines.
11. Do not mishandle the equipment / Computers.
12. Do not leave the laboratory without verification of hardware kits by the lab instructor.
13. Usage of Mobile phones, tablets and other portable devices are not allowed in restricted
places.

Dept. of CSE, AJIET, Mangalore iii


Object Oriented Programming with JAVA BCS306A

INSTRUCTIONS TO STUDENTS

 Students must bring Observation book, record and manual along with pen, pencil, anderaser etc.,
no borrowing from others.
 Students must handle the trainer kit and other components carefully, as they areexpensive.
 Before switch on the trainer kit, must show the connections to one of the faculties orinstructors.
 After the completion of the experiment should return the components to the respective lab
instructors.
 Before leaving the lab, should check whether they have switch off the power suppliesand keep
their chairs properly.
 Be regular to the Lab Do not come late to the Lab
 Do not throw connecting wires on the Floor
 Wear your College ID card Do not operate the IC trainer kits without permission
 Avoid unnecessary talking while doing the experiment
 Avoid loose connection and short circuits
 Take the signature of the lab in charge before taking the components
 Do not interchange the ICs while doing the experiment
 Handle the trainer kit properly
 Do not panic if you do not get the output
 Keep your work area clean after completing the experiment.
 After completion of the experiment switch off the power and return the components
 Arrange your chairs and tables before leaving.

Dept. of CSE, AJIET, Mangalore iv


Object Oriented Programming with JAVA BCS306A

RULES FOR MAINTAINING LABORATORY RECORD

 Put your name, USN and subject on the outside front cover of the record. Put
thatsame information on the first page inside.
 Update Table of Contents every time you start each new experiment or topic
 Always use pen and write neatly and clearly
 Start each new topic (experiment, notes, calculation, etc.) on a right-side (odd
numbered) page
 Obvious care should be taken to make it readable, even if you have bad handwriting
 Date to be written every page on the top right side corner
 On each right-side page
 Title of experiment
 Aim/Objectives
 Components Required
 Program
 On each left side page
 Stick Output snapshot printouts
 Use labels and captions for figures and tables
 Strictly observe the instructions given by the Teacher/ Lab Instructor.

Dept. of CSE, AJIET, Mangalore v


Object Oriented Programming with JAVA BCS306A

OBJECT ORIENTED PROGRAMMING WITH JAVA


[As per Choice Based Credit System (CBCS) scheme] (Effective
from the academic year 2021-22) SEMESTER – III

Laboratory Code BCS306A CIE Marks 25


Number of Contact Hours/Week 2:0:2:0 SEE Marks -
Total Number of Lab Contact Hours 20 Exam Hours 3 Hrs
CREDITS – 03

Course Objectives
 CLO 1. To learn primitive constructs JAVA programming languages.
 CLO 2. To understand Object Oriented Programming Features of JAVA.
 CLO 3. To gain knowledge on: packages, multithreaded programing and exceptions.

Course Outcomes
 CO 1. Demonstrate proficiency in writing simple programs involving branching and looping structures.
 CO 2. Design a class involving data members and methods for the given scenario.
 CO 3. Apply the concepts of inheritance and interfaces in solving real world problems.
 CO 4. Use the concept of packages and exception handling in solving complex problem
 CO 5. Apply concepts of multithreading, autoboxing and enumerations in program development

Dept. of CSE, AJIET, Mangalore vi


Object Oriented Programming with JAVA BCS306A

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


ASSESSMENT DETAILS (BOTH CIE AND SEE)

 The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.
The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the
SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks).

 A student shall be deemed to have satisfied the academic requirements and earned the credits allotted to
each subject/ course if the student secures a minimum of 40% (40 marks out of 100) in the sum total of the
CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken together.

 IPCC means practical portion integrated with the theory of the course.

 CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.

CONTINUOUS INTERNAL EVALUATION (CIE) for IPCC:


CIE THEORY + CIE PRACTICAL

 CIE for the theory component of the IPCC (Maximum Marks 25)
 25 marks for the theory component are split into
o 15 marks for two Internal Assessment Tests (Average of Two Tests each of 25 Marks , scale down the
marks scored to 15 marks)
 The first test at the end of 40-50% coverage of the syllabus and
 The second test after covering 85-90% of the syllabus
o 10 marks for other assessment methods mentioned in 22OB4.2.
 Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the theory
component of IPCC (that is for 25 marks).
 The student has to secure 40% of 25 marks (10 marks) to qualify in the CIE of the theory component of IPCC.

 CIE for the practical component of the IPCC (Maximum Marks 25)
 25 marks for the practical component are split into
o 15 marks for the conduction of the experiment and preparation of laboratory record, and 10 marks for
the test to be conducted after the completion of all the laboratory sessions.
o On completion of every experiment/program in the laboratory, the students shall be evaluated including
viva-voce and marks shall be awarded on the same day.

Dept. of CSE, AJIET, Mangalore vii


Object Oriented Programming with JAVA BCS306A
 The CIE marks awarded in the case of the Practical component shall be based on the continuous evaluation of
the laboratory report. Each experiment report can be evaluated for 10 marks. Marks of all experiments’ write-
ups are added and scaled down to 15 marks.
 The laboratory test (duration 02/03 hours) after completion of all the experiments shall be conducted for 50
marks and scaled down to 10 marks.
 Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory component of
IPCC for 25 marks.
 The student has to secure 40% of 25 marks to qualify in the CIE of the practical component of the IPCC.

SEMESTER END EXAMINATION (SEE) for IPCC:


Theory SEE will be conducted by University as per the scheduled timetable, with common question papers for the course
(duration 03 hours)
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a maximum of 3 sub-
questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.
4. Marks scored by the student shall be proportionally scaled down to 50 Marks

Dept. of CSE, AJIET, Mangalore viii


Object Oriented Programming with JAVA BCS306A

The theory portion of the IPCC shall be for both CIE and SEE, whereas the practical portion will have a CIE
component only. Questions mentioned in the SEE paper may include questions from the practical component.

To put it simply, evaluation techniques/methods are listed in the table for further understanding

Evaluation Type Maximum Minimum Evaluation Details


Marks Passing
Marks
CIE-IA Tests 15 06 Average of Two Tests each of 25 Marks , scale down
the marks scored to 15 marks
CIE-CCAs 10 04 Any two assignment methods as per clause 22OB4.2
of Regulations (if assessment is project based, then
one assessment method may be adopted)
Total CIE Theory 25 10 Scale down marks of tests and assignments to 25
CIE Practical 15 06 Conduction of experiment’s and Preparation of
Laboratory records etc
CIE Practical Test 10 04 One test after all experiment’s conduction for 50
Marks scale down the marks scored to 10 marks
Total CIE Practical 25 10 Scale down marks of experiment’s record and test
to 25
TOTAL CIE= 50 20
Total CIE Theory + Total
CIE Practical
SEE 50 18 SEE exam is a theory exam, conducted for 100 marks
are scaled down to 50 marks
CIE+SEE 100 40

Course Instructor Domain Co-Ordinator Head of Department

Dept. of CSE, AJIET, Mangalore ix


Object Oriented Programming with JAVA BCS306A

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


RUBRICS FOR PRACTICAL SESSIONS
Practical Sessions- Continuous Evaluation (CE)
Evaluation Parameter Level of Achievement
#R1: Excellent (10-08) Good (07-06) Average (05-4) Poor (3-0)
Observation Observation neatly Observation Observation is Observation is
(10 Marks) written. Handwriting is neatly written. written in unclear written in unclear
clear. Programs written Handwriting is manner. manner.
with no mistakes. clear. Programs Handwriting is not Handwriting is not
written with very very clear. clear. Programs
few mistakes. executed with a
large number of
errors.
#R2: Excellent (30-26) Good (25-20) Average (19-15) Poor (14-0)
Record writing Record is neatly Record is neatly Record is written in Record is written in
(30 Marks) written, handwriting is written, an unclear manner. an unclear manner.
clear. Programs handwriting is Programs executed Programs written
executed with no clear. Programs with few errors with lot of
errors. Mistakes are executed with Handwriting is not mistakes.
covered and corrected very less errors. very clear. Mistakes Handwriting is not
properly and neatly. Most mistakes are are sometimes very clear.
Record submitted on covered and corrected properly. Mistakes are not
time corrected Record submitted corrected. Record
properly and with a delay of 4 to submitted after a
neatly. Record 5 days delay of 1 week
submitted with a
delay of 1 - 3
days
#R3: Excellent (10-08) Good (07-06) Average (05-4) Poor (3-0)
Viva Answered all questions Answered most Answered a few Not able to answer
(10 Marks) with elaboration has of the questions questions. Subject any of the
excellent understanding Failed to knowledge is not questions. Subject
of the topic. elaborate some of adequate knowledge not
the concepts adequate
Each week experiment report is evaluated for 10 marks. Marks of all experiments' write-ups are added and scaled
down to 15 marks.

Practical Sessions- Internal Assessment (IA)


#R1: Excellent (10-08) Good (07-06) Average (05-4) Poor (3-0)
Write-Up Program neatly written. Program neatly Program is written Program is written
(10 Marks) Handwriting is clear. written. in unclear manner. in unclear manner.
Programs written with Handwriting is Handwriting is not Handwriting is not
no mistakes. clear. Programs very clear. clear, Programs
written with very Programs written written with lot of
few mistakes. with fewer mistakes.
mistakes.
#R2: Excellent (30-26) Good (25-20) Average (19-15) Poor (14-0)
Conduction/Execution (30 Execution of the Execution of the Execution of the Execution of the
Marks) program done as per program done as program done as per program was not
the procedure. per the procedure. the procedure. done as per the

Dept. of CSE, AJIET, Mangalore x


Object Oriented Programming with JAVA BCS306A
Programs had less than Programs had less Programs had more procedure.
10 errors. The errors than 20 errors. than 20 errors. The Programs was full
were debugged without The errors were errors were of syntax and
any help. The Result debugged with a debugged with the logical error. The
was tabulated for all little help. The help of instructor. errors were
the cases. Result was The Result was resolved by the
tabulated for tabulated for few of instructor. The
almost all the the cases Result was
cases tabulated only for 1
or 2 Cases
#R3: Excellent (10-08) Good (07-06) Average (05-04) Poor (03-00)
Viva Answered all questions Answered most Answered a few Not able to answer
(10 Marks) with elaboration has of the questions questions. Subject any of the
excellent understanding Failed to knowledge is not questions. Subject
of the topic. elaborate some of adequate knowledge not
the concepts adequate

The laboratory test (duration 02/03 hours) at the end of the 15th week of the semester /after completion of all the
experiments (whichever is early) shall be conducted for 50 marks and scaled down to 10 marks.

Split-up of Marks used Practical Sessions


Rubrics No. Practical Sessions- Continuation Evaluation (CE) Marks
Methodology / Process Steps per Experiment
#R1 Observation 10
#R2 Record writing : Write up of Procedure / Algorithm/ Program 30
and Execution/conduction of experiment
#R3 Viva – Voce (Questions & Answers on relevant Experiment 10
/Topic)
Total Marks 50
(Scale down to 15)
Rubrics No. Practical Sessions-Internal Assessment (IA) Marks
#R1 Write-up of Procedure/Program/Algorithm 10
#R2 Conduction/Execution 30
#R3 Viva-Voce 10
Total Marks 50
(Scale down to 10)

Course Instructor Domain Co-Ordinator Head of Department

Dept. of CSE, AJIET, Mangalore xi


Object Oriented Programming with JAVA BCS306A

LIST OF MAJOR EQUIPMENT

Name of the Laboratory: COMPUTING LABORATORY-2

Sl. No. Name of the Equipment Specialization Quantity

1 Desktop Intel(R) Core (TM) i3-4170/i3-9100 36


processor, 4.00 GB/8.00 GB RAM,
500GB/1TB HDD, 18.5”ACER- Monitor,
Keyboard and Mouse.

2 UPS 10KVA 1

3 Switches 24 Port Gigabytes 1

4 Internet 150 Mbps 1

5 Projector EPSON Projector with HDMI Port 1

Room Number : A-323

Total Area of the laboratory : 130 Sq. Meters

Total Amount Spent : Rs. 12, 30, 563 /-

Name of the HOD : Dr. Antony P. J

Name of the lab in charge : Mrs. Sharon C. D’Souza

Name of the lab instructor : Ms. Riola

Dept. of CSE, AJIET, Mangalore xii


Object Oriented Programming with JAVA BCS306A

Sl
PROGRAMS
No.

PREREQUISITE
 Students should be familiarized about java installation and setting the java environment.
 Usage of IDEs like Eclipse/Netbeans should be introduced.
PART A – List of problems for which student should develop program and execute in the Laboratory
Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read from
1
command line arguments).
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main
2
method to illustrate Stack operations.
A class called Employee, which models an employee with an ID, name and salary, is designed as shown
3 in the following class diagram. The method raiseSalary (percent) increases the salary by the given
percentage. Develop the Employee class and suitable main method for demonstration.
A class called MyPoint, which models a 2D point with x and y coordinates, is designed as follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
4
● A method called distance(int x, int y) that returns the distance from this point to another point at the
given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to the given MyPoint
instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin (0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called TestMyPoint) to test all
the methods defined in the class.
Develop a JAVA program to create a class named shape. Create three sub classes namely: circle, triangle
5 and square, each class has two member functions named draw () and erase (). Demonstrate polymorphism
concepts by developing suitable methods, defining member data and main program.
Develop a JAVA program to create an abstract class Shape with abstract methods calculateArea() and
6 calculatePerimeter(). Create subclasses Circle and Triangle that extend the Shape class and implement the
respective methods to calculate the area and perimeter of each shape.
Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width) and
7 resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that implements the
Resizable interface and implements the resize methods
Develop a JAVA program to create an outer class with a function display. Create another class inside the
8
outer class named inner with a function called display and call the two functions in the main class.
Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero using
try, catch, throw and finally
9
Develop a JAVA program to create a package named mypack and import & implement it in a suitable
10
class.
Write a program to illustrate creation of threads using runnable class. (start method start each of the
11
newly created thread. Inside the run method there is sleep() for suspend the thread for 500 milliseconds).

Dept. of CSE, AJIET, Mangalore xiii


Object Oriented Programming with JAVA BCS306A
Develop a program to create a class MyThread in this class a constructor, call the base class constructor,
12 using super and start the thread. The run method of the class starts after this. It can be observed that both
main thread and created child thread are executed concurrently.
Additional Programs
Assessment Details (both CIE and SEE)
Assessment Details (both CIE and SEE)

The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is
50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50)
and for the SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A
student shall be deemed to have satisfied the academic requirements and earned the credits allotted to
each subject/ course if the student secures a minimum of 40% (40 marks out of 100) in the sum total
of the CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken together.

CIE for the theory component of the IPCC (maximum marks 50)

● IPCC means practical portion integrated with the theory of the course.
● CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.
● 25 marks for the theory component are split into 15 marks for two Internal Assessment Tests (Two
Tests, each of 15 Marks with 01-hour duration, are to be conducted) and 10 marks for other
assessment methods mentioned in 22OB4.2. The first test at the end of 40-50% coverage of the
syllabus and the second test after covering 85-90% of the syllabus.
● Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the
theory component of IPCC (that is for 25 marks).
● The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC.

CIE for the practical component of the IPCC


● 15 marks for the conduction of the experiment and preparation of laboratory record, and 10 marks for
the test to be conducted after the completion of all the laboratory sessions.
● On completion of every experiment/program in the laboratory, the students shall be evaluated
including viva-voce and marks shall be awarded on the same day.
● The CIE marks awarded in the case of the Practical component shall be based on the continuous
evaluation of the laboratory report. Each experiment report can be evaluated for 10 marks. Marks of
all experiments’ write-ups are added and scaled down to 15 marks.
● The laboratory test (duration 02/03 hours) after completion of all the experiments shall be conducted
for 50 marks and scaled down to 10 marks.
● Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory
component of IPCC for 25 marks.
● The student has to secure 40% of 25 marks to qualify in the CIE of the practical component of the
IPCC. SEE for IPCC Theory SEE will be conducted by University as per the scheduled timetable,
with common question papers for the course (duration 03 hours)

Dept. of CSE, AJIET, Mangalore xiv


JAVA INSTALLATION AND SETTING THE
JAVA ENVIRONMENT
Introduction
The Java Development Kit (JDK) is software used for Java programming, along with the Java
Virtual Machine (JVM) and the Java Runtime Environment (JRE). The JDK includes the
compiler and class libraries, allowing developers to create Java programs executable by the
JVM and JRE.
Prerequisites
 A system running Windows 10.
 A network connection.
 Administrator privileges.

Check if Java Is Installed


Before installing the Java Development Kit, check if a Java version is already installed on
Windows. Follow the steps below:

1. Open a command prompt by typing cmd in the search bar and press Enter.
2. Run the following command:

java -version

The command outputs the Java version on your system. If Java isn't installed, the output is a
message stating that Java isn't recognized as an internal or external command.

Download Java for Windows 10


Download the latest Java Development Kit installation file for Windows 10 to have the latest
features and bug fixes.

1. Using your preferred web browser, navigate to the Oracle Java Downloads page.
2. On the Downloads page, click the x64 Installer download link under
the Windows category.

Dept. of CSE, AJIET, Mangalore 1


Wait for the download to complete.
Install Java on Windows 10
After downloading the installation file, proceed with installing Java on your Windows system.
Follow the steps below:
Step 1: Run the Downloaded File
Double-click the downloaded file to start the installation.
Step 2: Configure the Installation Wizard
After running the installation file, the installation wizard welcome screen appears.
1. Click Next to proceed to the next step.

2. After clicking Next, the following Destination Folder section is visible. Set the path
wherein the Java 18 directories and files will get installed. Keep it the default i.e., here it will
install under the following path: “C:\Program Files\Java\jdk-18″. Click on Next:

Dept. of CSE, AJIET, Mangalore 2


The installation continues for some seconds:

The installation finishes as in the following screenshot.


Click on Close:

Now, let us set the JDK path.

Dept. of CSE, AJIET, Mangalore 3


Set Java JDK Path (Environment Variable)
At first, copy the path wherein you installed the Java JDK. Let us copy it first. Remember, we
need to copy the bin path i.e., the following on our system:
C:\Program Files\Java\jdk-18\bin

To set JDK Path, the easiest way is to type Environment Variables on Start. On typing, the
following would be visible. Now, click on Edit Environment Variables,

A new dialog box would be visible. Now, click Environment Variable:

Dept. of CSE, AJIET, Mangalore 4


Go to the System Variables section and double click Path as in the below screenshot:

Now, the steps are displayed as a list marked in the below screenshot:

1. On double-clicking Path, a new dialog box will open.


2. From there, click New,
3. Add the Java JDK path C:\Program Files\Java\jdk-18\bin as shown below:

Dept. of CSE, AJIET, Mangalore 5


Click OK to save the changes and exit the variable editing window.

Step 2: Add JAVA_HOME Variable


Some applications require the JAVA_HOME variable. Follow the steps below to create the
variable:
1. In the Environment Variables window, under the System variables category, click
the New… button to create a new variable.

2. Name the variable as JAVA_HOME.


3. In the variable value field, paste the path to your Java jdk directory and click OK.

Dept. of CSE, AJIET, Mangalore 6


4. Confirm the changes by clicking OK in the Environment Variables and System
properties windows.
Test the Java Installation
Run the java -version command in the command prompt to make sure Java installed
correctly:

If installed correctly, the command outputs the Java version.

ECLIPSE DOWNLOAD AND INSTALLATION


Eclipse is a free open-source platform, Integrated Development Environment (IDE) with the
help of which applications are made using the Java programming languages and other
programming languages are also used such as C/C++, PERL, Python, Ruby, etc.
It is composed of many plug-ins and is designed to be extensible using additional plug-ins.
Eclipse IDE can be used for any programming language for which a plug-in is available.
Following are some plug-ins used in Eclipse IDE:
 The Java Development Tools (JDT) is a plugin that allows Eclipse to be used as a
Java IDE.
 PyDev is a plugin that allows Eclipse to be used as a Python IDE.
 C/C++ Development Tools (CDT) is a plug-in that allows Eclipse to be used as
C/C++ development.
 The Scala is a plug-in that allows Eclipse to be used as an IDE to develop Scala
applications.
 PHPeclipse is a plug-in that allows Eclipse to be used as an IDE to develop PHP
applications.

Installation of Eclipse IDE on Windows:


Follow the below steps to install Eclipse IDE on Windows:
Step 1: In the first step, open your browser and navigate to this https://www.eclipse.org/.
Step 2: Then, click on the “Download” button to download Eclipse IDE .

Dept. of CSE, AJIET, Mangalore 7


Step 3: Now, click on the “Download x86_64” button.

Step 4: Then click on the “Download” button. After clicking on the download button, the
.exe file for the eclipse will be downloaded.

Step 5: Now go to File Explorer and click on “Downloads” after that click on the “eclipse-
inst-jre-win64.exe” file to install Eclipse IDE.
Step 6: Then, click on “Eclipse IDE for Java Developers”.

Dept. of CSE, AJIET, Mangalore 8


Step 7: Then, click on the “Install” button.

Step 8: Now click on “Create a new Java project”.

Dept. of CSE, AJIET, Mangalore 9


Now, you are ready to make new Java projects using eclipse IDE and the screen will look like
this:

Dept. of CSE, AJIET, Mangalore 10


JAVA FUNDAMENTALS, DATA TYPES, OPERATORS,
ARRAY IN JAVA
Aim: Introduce the java fundamentals, data types, operators, Array in java

Theory:

DATA TYPES
Data types are divided into two groups:

 Primitive data types - includes byte, short, int, long, float, double, Boolean and char
 Non-primitive data types - such as String, Arrays and Classes

Primitive Data Types


A primitive data type specifies the size and type of variable values, and it has no additional
methods.
There are eight primitive data types in Java:

Non-Primitive Data Types


Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:

 Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
 Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types start with an
uppercase letter.
 The size of a primitive type depends on the data type, while non-primitive types have
all the same size.

Dept. of CSE, AJIET, Mangalore 11


Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
Java Operators
Operators are used to perform operations on variables and values.
Java divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

1. Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

2. Assignment Operators
Assignment operators are used to assign values to variables.

Dept. of CSE, AJIET, Mangalore 12


3. Java Comparison Operators
Comparison operators are used to compare two values:

4. Java Logical Operators


Logical operators are used to determine the logic between variables or values:

We can add two matrices in java using binary + operator. A matrix is also known as array
of arrays. We can add, subtract and multiply matrices.

Dept. of CSE, AJIET, Mangalore 13


To subtract two matrices, use - operator. Let's see a simple example to add two matrices
of 3 rows and 3 columns.
Decision Making in Java

Decision making in Java executes a particular segment of code based on the result of a Boolean
condition. It is important because conditions define the flow of programs and the output of a
particular program.
The decision-making principles in Java chiefly consist of if else statements, continue, break
and switch statements. It decides the flow of the program control during the execution of the
program.

There are the 6 ways of exercising decision making in Java:

1. If
2. if-else
3. nested-if
4. if-else-if
5. switch-case
6. jump-break, continue

1. IF Statement

Dept. of CSE, AJIET, Mangalore 14


Java if statement is the simplest decision-making statement. It encompasses a Boolean
condition followed by a scope of code which is executed only when the condition evaluates to
true. However, if there are no curly braces to limit the scope of sentences to be executed if the
condition evaluates to true, then only the first line is executed.

Syntax: Flow diagram for Java if statement:


if(condition)
{
//code to be executed
}

2. IF-ELSE Statement

This pair of keywords is used to divide a program to be executed into two parts, one being the
code to be executed if the condition evaluates to true and the other one to be executed if the
value is false. However, if no curly braces are given the first statement after the if or else
keyword is executed.

Syntax Flowchart

if(condition)
{
//code to be executed if the condition is true
}
else
{
//code to be executed if the condition is false
}

3. Nested IF Statements in Java

Dept. of CSE, AJIET, Mangalore 15


The nested if is similar to the nested loops we learnt about in the previous chapters. If the
condition of the outer if statement evaluates to true then the inner if statement is evaluated.
Nested ifs are important if we have to declare extended conditions to a previous condition

Syntax: Flowchart
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

4. IF-ELSE-IF Statements in Java

These statements are similar to the if else statements. The only difference lies in the fact that
each of the else statements can be paired with a different if condition statement. This renders
the ladder as a multiple-choice option for the user. As soon as one of the if conditions evaluate
to true the equivalent code is executed and the rest of the ladder is ignored.

Syntax: Flowchart
if
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else
{
//code to be executed
}

Dept. of CSE, AJIET, Mangalore 16


5. SWITCH Statement in Java

Java switch statement is a different form of the if else if ladder statements.

 This saves the hassle of writing else if for every different option.
 It branches the flow of the program to multiple points as and when required or specified
by the conditions.
 It bases the flow of the program based on the output of the expression.
 As soon as the expression is evaluated, the result is matched with each and every case
listed in the scope. If the output matches with any of the cases mentioned, then the
particular block is executed. A break statement is written after every end of the case block
so that the remaining statements are not executed.
 The default case is written which is executed if none of the cases are the result of the
expression. This is generally the block where error statements are written.

Syntax Flowchart

switch(expression)
{
case <value1>:
//code to be executed

Dept. of CSE, AJIET, Mangalore 17


break;
case <value2>:
//code to be executed
break;
default:
//code to be defaultly
executed
}

6. Jump Statements in Java


The jump statements are the keywords in Java which have specific meaning and specific action
of disrupting the normal flow of the program. Some of them are:
1. Java break statement
The break statement, as the name signifies, is useful to break out of the normal workflow of a
program. We can use it to terminate loops, end cases of switch statements, and as a goto
statement. Break statements, if used in a nested loop, terminates the innermost loop. The
outermost loop still functions.
b. Continue Statement in Java
The continue statement is useful for early iteration of a particular loop. Sometimes rather than
breaking out of a loop and halting it for good we want to skip some iterations based on our
requirements of a program. This results in the usage of continue statements.

Break Statement Continue Statement

Dept. of CSE, AJIET, Mangalore 18


LOOPS IN JAVA
Looping in programming languages is a feature which facilitates the execution of a set of
instructions/functions repeatedly while some condition evaluates to true. Java provides three
ways for executing the loops. While all the ways provide similar basic functionality, they differ
in their syntax and condition checking time.

1. FOR LOOP
Java for loop provides a concise way of writing the loop structure. The for statement
consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping .

Syntax Flowchart
for (initialization expr; test expr; update
exp)
{
// body of the loop
// statements we want to execute
}

Dept. of CSE, AJIET, Mangalore 19


The various parts of the For loop are:

1. Initialization Expression: In this expression, we have to initialize the loop counter to


some value.
Example: int i=1;

2. Test Expression: In this expression, we have to test the condition. If the condition
evaluates to true then, we will execute the body of the loop and go to update expression.
Otherwise, we will exit from the for loop.
Example: i <= 10
3. Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value.
Example: i++;

2. WHILE Loop

Java while loop is a control flow statement that allows code to be executed repeatedly based
on a given Boolean condition. The while loop can be thought of as a repeating if statement.
While loop in Java comes into use when we need to repeatedly execute a block of statements.
The while loop is considered as a repeating if statement. If the number of iterations is not
fixed, it is recommended to use the while loop.

Syntax: Flowchart
while (test_expression)
{
// statements

update_expression;
}

Dept. of CSE, AJIET, Mangalore 20


The various parts of the While loop are:
1. Test Expression: In this expression, we have to test the condition. If the condition evaluates
to true then we will execute the body of the loop and go to update expression. Otherwise, we
will exit from the while loop.
Example: i <= 10

2. Update Expression: After executing the loop body, this expression increments/decrements
the loop variable by some value.
Example: i++;

3. DO-WHILE LOOP

Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-while
check for the condition after executing the statements of the loop body.

Syntax: Flowchart
do
{
// Loop Body
Update_expression
}
// Condition check
while (test_expression);

4. FOR EACH LOOP


For-each is another array traversing technique like for loop, while loop, do-while loop
introduced in Java5.

Dept. of CSE, AJIET, Mangalore 21


 It starts with the keyword for like a normal for-loop.
 Instead of declaring and initializing a loop counter variable, you declare a variable that
is the same type as the base type of the array, followed by a colon, which is then
followed by the array name.
 In the loop body, you can use the loop variable you created rather than using an indexed
array element.
 It’s commonly used to iterate over an array or a Collections class (e.g., ArrayList)

Syntax:
for (type var : array)
{
statements using var;

Program 1:
Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).

import java.util.Scanner;
public class Add_Matrix
{
public static void main(String[] args)
{
int p, q, m, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in first matrix:");
p = s.nextInt();
System.out.print("Enter number of columns in first matrix:");
q = s.nextInt();
System.out.print("Enter number of rows in second matrix:");
m = s.nextInt();
System.out.print("Enter number of columns in second matrix:");
n = s.nextInt();
if (p == m && q == n)
{
int a[][] = new int[p][q];
int b[][] = new int[m][n];
int c[][] = new int[m][n];
System.out.println("Enter all the elements of first matrix:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
a[i][j] = s.nextInt();
}

Dept. of CSE, AJIET, Mangalore 22


}
System.out.println("Enter all the elements of second matrix:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = s.nextInt();
}
}
System.out.println("First Matrix:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println("");
}
System.out.println("Second Matrix:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println("");
}
for (int i = 0; i < p; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < q; k++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
System.out.println("Matrix after addition:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println("");
}
}
else
{

Dept. of CSE, AJIET, Mangalore 23


System.out.println("Addition would not be possible");
}
}
}

Output:
Enter number of rows in first matrix:2
Enter number of columns in first matrix:3
Enter number of rows in second matrix:2
Enter number of columns in second matrix:3
Enter all the elements of first matrix:
1
2
3
4
5
6
Enter all the elements of second matrix:
7
8
9
4
3
2
First Matrix:
123
456
Second Matrix:
789
432
Matrix after addition:
8 10 12
888

Viva Questions:

1. Write java program to Reverse a Number in Java

Dept. of CSE, AJIET, Mangalore 24


2. Java Program to Find Largest of Three Numbers

OUTPUT:

Enter number of rows in first matrix:2


Enter number of columns in first matrix:3
Enter number of rows in second matrix:2
Enter number of columns in second matrix:3
Enter all the elements of first matrix:
1
2
3
4
5
6
Enter all the elements of second matrix:
7
8
9
4
3
2
First Matrix:
123
456
Second Matrix:
789
432
Matrix after addition:
8 10 12
888

RESULT:

Java programs to demonstrate the array concept were successfully written and executed
using Eclipse IDE and the result was verified.

Dept. of CSE, AJIET, Mangalore 25


PROGRAM 2:

Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
This is a Java Program to implement a stack. Stack is an area of memory that holds all local
variables and parameters used by any function and remembers the order in which functions are
called so that function returns occur correctly. ‘push’ operation is used to add an element to
stack and ‘pop’ operation is used to remove an element from stack. ‘peek’ operation is also
implemented returning the value of the top element without removing it. The relation between
the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure.
The implemented stack has bounded capacity.
The stack is a linear data structure that is used to store the collection of objects. It is based on
Last-In-First-Out (LIFO). Java collection framework provides many interfaces and classes to
store the collection of objects. One of them is the Stack class that provides different operations
such as push, pop, search, etc.
In this section, we will discuss the Java Stack class, its methods, and implement the stack
data structure in a Java program. But before moving to the Java Stack class have a quick view
of how the stack works.
The stack data structure has the two most important operations that are push and pop. The
push operation inserts an element into the stack and pop operation removes an element from
the top of the stack. Let's see how they work on stack.

Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

Dept. of CSE, AJIET, Mangalore 26


Let's remove (pop) 18, 45, and 11 from the stack.

Empty Stack: If the stack has no element is known as an empty stack. When the stack is
empty the value of the top variable is -1.

Dept. of CSE, AJIET, Mangalore 27


When we push an element into the stack the top is increased by 1. In the following figure,

o Push 12, top=0


o Push 6, top=1
o Push 9, top=2

Dept. of CSE, AJIET, Mangalore 28


When we pop an element from the stack the value of top is decreased by 1. In the following
figure, we have popped 9.

The following table shows the different values of the top.

Dept. of CSE, AJIET, Mangalore 29


Java Stack Class
In Java, Stack is a class that falls under the Collection framework that extends the Vector class.
It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. It represents
the LIFO stack of objects. Before using the Stack class, we must import the java.util package.
The stack class arranged in the Collections framework hierarchy, as shown below.

Stack Class Constructor


The Stack class contains only the default constructor that creates an empty stack.

1. public Stack()

Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of the Stack
class.

1. Stack stk = new Stack();

Dept. of CSE, AJIET, Mangalore 30


Or

1. Stack<type> stk = new Stack<>();

Where type denotes the type of stack like Integer, String, etc.
Methods of the Stack Class
We can perform push, pop, peek and search operation on the stack. The Java Stack class
provides mainly five methods to perform these operations. Along with this, it also provides all
the methods of the Java Vector class.

Method Modifier Method Description


and Type

empty() boolean The method checks the stack is empty or not.

push(E item) E The method pushes (insert) an element onto the top of
the stack.

pop() E The method removes an element from the top of the stack
and returns the same element as the value of that
function.

peek() E The method looks at the top element of the stack without
removing it.

search(Object int The method searches the specified object and returns the
o) position of the object.

Stack Class empty() Method


The empty() method of the Stack class check the stack is empty or not. If the stack is empty,
it returns true, else returns false. We can also use the isEmpty() method of the Vector class.
Syntax

1. public boolean empty()

Returns: The method returns true if the stack is empty, else returns false.

Dept. of CSE, AJIET, Mangalore 31


PROGRAM 2:
import java.util.*;
class arrayStack
{
protected int arr[];
protected int top, size, len;
/* Constructor for arrayStack */
public arrayStack(int n)
{
size = n;
len = 0;
arr = new int[size];
top = -1;
}
/* Function to check if stack is empty */
public boolean isEmpty()
{
return top == -1;
}
/* Function to check if stack is full */
public boolean isFull()
{
return top == size -1 ;
}

/* Function to add an element to the stack */


public void push(int i)
{
if(top + 1 >= size)
throw new IndexOutOfBoundsException("Overflow Exception");
if(top + 1 < size )
arr[++top] = i;
len++ ;
}
/* Function to delete an element from the stack */
public int pop()
{
if( isEmpty() )
throw new NoSuchElementException("Underflow Exception");
len-- ;
return arr[top--];
}
/* Function to display the status of the stack */
public void display()
{
System.out.print("\nStack = ");
if (len == 0)

Dept. of CSE, AJIET, Mangalore 32


{
System.out.print("Empty\n");
return ;
}
for (int i = top; i >= 0; i--)
System.out.print(arr[i]+" ");
System.out.println();
}
}

/* Class StackImplement */
public class StackImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);

System.out.println("Enter Size of Integer Stack ");


int n = scan.nextInt();
/* Creating object of class arrayStack */
arrayStack stk = new arrayStack(n);
/* Perform Stack Operations */
char ch;
do{
System.out.println("\nStack Operations");
System.out.println("1. push");
System.out.println("2. pop");

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter integer element to push");
try
{
stk.push( scan.nextInt() );
}
catch (Exception e)
{
System.out.println("Error : " + e.getMessage());
}
break;
case 2 :
try
{
System.out.println("Popped Element = " + stk.pop());
}
catch (Exception e)
{

Dept. of CSE, AJIET, Mangalore 33


System.out.println("Error : " + e.getMessage());
}
break;

default :
System.out.println("Wrong Entry \n ");
break;
}
/* display stack */
stk.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');


}
}

RESULT:
Java programs to demonstrate the stack operation were successfully written and executed
using Eclipse IDE and the result was verified.

OUTPUT:
Enter Size of Integer Stack
3
Stack Operations
1. push
2. pop
1
Enter integer element to push
34
Stack = 34
Do you want to continue (Type y or n)

y
Stack Operations
1. push
2. pop
1
Enter integer element to push
45
Stack = 45 34

Do you want to continue (Type y or n)

Dept. of CSE, AJIET, Mangalore 34


Viva Question:

1. What is a stack?

2. What are the operations that can be performed on stack?

3. What are the conditions to be checked before inserting / deleting elements from
the stack?

4. How are stacks are implemented?

5. What are the applications of stack?

6. What is recursion?

7. Define “Top of stack”

Dept. of CSE, AJIET, Mangalore 35


PROGRAM 3:

JAVA CLASSES, OBJECTS, CONSTRUCTORS, DECLARATION AND


INITIALIZATION OF VARIABLES

Aim: Demonstrating creation of java classes, objects, constructors, declaration and


initialization of variables.

OBJECT
An entity that has state and behaviour is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
An object has three characteristics:
 State: represents the data (value) of an object.
 Behaviour: represents the behaviour (functionality) of an object such as deposit,
withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

CLASS
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}

CONSTRUCTOR
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
Rules for creating Java constructor
There are two rules defined for the constructor.

1. Constructor name must be the same as its class name

Dept. of CSE, AJIET, Mangalore 36


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Program 3:
A class called Employee, which models an employee with an ID, name and salary, is
designed as shown in the following class diagram. The method raise Salary (percent)
increases the salary by the given percentage. Develop the Employee class and suitable
main method for demonstration.

package employee;
class Employee {
private String name;
private int id;
private double salary;

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


this.name = name;
this.id = id;
this.salary = salary;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getID() {


return id;
}

public void setID(int id) {


this.id = id;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;

Dept. of CSE, AJIET, Mangalore 37


}

public void raiseSalary(double percentage) {


salary = salary + salary * percentage / 100;
}

public void printEmployeeDetails() {


System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Salary: " + salary);
}
}

public class Employeemain {

public static void main(String[] args) {


// TODO Auto-generated method stub
Employee employee1 = new Employee("Franziska Waltraud", 1, 40000);
Employee employee2 = new Employee("Hubertus Andrea", 2, 60000);
System.out.println("\nEmployee Details:");
employee1.printEmployeeDetails();
employee2.printEmployeeDetails();

employee1.raiseSalary(8);
employee2.raiseSalary(12);

System.out.println("\nAfter raising salary:");


System.out.println("\n8% for 'Franziska Waltraud':");
employee1.printEmployeeDetails();
System.out.println("\n12% for 'Hubertus Andrea':");
employee2.printEmployeeDetails();
}

Dept. of CSE, AJIET, Mangalore 38


OUTPUT

Employee Details:
Name: Franziska Waltraud
ID: 1
Salary: 40000.0
Name: Hubertus Andrea
ID: 2
Salary: 60000.0

After raising salary:

8% for 'Franziska Waltraud':


Name: Franziska Waltraud
ID: 1
Salary: 43200.0

12% for 'Hubertus Andrea':


Name: Hubertus Andrea
ID: 2
Salary: 67200.0

RESULT: A Java program to Demonstrate the creation of classes, objects, constructors,


declaration and initialization of variables was successfully written and executed using the
eclipse IDE and the result was verified.

Viva Questions

1. Create a class named 'Student' with String variable 'name' and integer variable 'roll_no'.
Assign the value of roll_no as '2' and that of name as "John" by creating an object of the
class Student.

Dept. of CSE, AJIET, Mangalore 39


2. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5
units by creating a class named 'Triangle' without any parameter in its constructor.

Dept. of CSE, AJIET, Mangalore 40


PROGRAM 4:

METHOD OVERLOADING IN JAVA

Aim: Discuss the various Method overloading in java

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
Different Ways of Method Overloading in Java
Changing the Number of Parameters.
Changing Data Types of the Arguments.
Changing the Order of the Parameters of Methods

1. METHOD OVERLOADING
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int, int) for two parameters, and b(int, int, int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behaviour of the method because its name differs.
So, we perform method overloading to figure out the program quickly.

Advantage of method overloading


Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

2. CONSTRUCTOR OVERLOADING

Dept. of CSE, AJIET, Mangalore 41


The process of defining multiple constructors of the same class is referred to as Constructor
overloading. However, each constructor should have a different signature or input parameters.
In other words, constructor overloading in Java is a technique that enables a single class to have
more than one constructor that varies by the list of arguments passed. Each overloaded
constructor is used to perform different task in the class.
The Java compiler identifies the overloaded constructors on the basis of their parameter lists,
parameter types and the number of input parameters. Hence, the constructors that are
overloaded should have different signatures. A constructor’s signature contains its name and
parameter types. An ambiguity issue arises when two of the class constructors have an identical
signature.
The compiler fails to differentiate between the two and hence returns an error notification.
When constructors with different signatures are overloaded, the compiler determines the
constructor to be invoked based on the number of input parameters of the objects.

Benefits of Constructor Overloading in Java


The key advantages of making use of constructor overloading while writing Java programs are:
 The constructor overloading enables the accomplishment of static polymorphism.
 The class instances can be initialized in several ways with the use of constructor
overloading.
 It facilitates the process of defining multiple constructors in a class with unique
signatures.
 Each overloaded constructor performs various tasks for specified purposes.

3. OVERRIDING

In any object-oriented programming language, Overriding is a feature that allows a subclass


or child class to provide a specific implementation of a method that is already provided by
one of its super-classes or parent classes. When a method in a subclass has the same name,
same parameters or signature, and same return type(or sub-type) as a method in its super-
class, then the method in the subclass is said to override the method in the super-class.

Method overriding is one of the ways by which java achieve Polymorphism. The version of
a method that is executed will be determined by the object that is used to invoke it. If an
object of a parent class is used to invoke the method, then the version in the parent class will
be executed, but if an object of the subclass is used to invoke the method, then the version
in the child class will be executed. In other words, it is the type of the object being referred

Dept. of CSE, AJIET, Mangalore 42


to (not the type of the reference variable) that determines which version of an overridden
method will be executed.

A class called MyPoint, which models a 2D point with x and y coordinates, is designed
as follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0,
0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x,
y)".
● A method called distance(int x, int y) that returns the distance from this point to
another point at the given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to
the given MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the
origin (0,0) Develop the code for the class MyPoint. Also develop a JAVA program
(called TestMyPoint) to test all the methods defined in the class.

PROGRAM 4:

package employee;

class MyPoint
{
private int x = 0;
private int y = 0;
public MyPoint()
{
this(0, 0);
}
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}

public double distance(int x, int y)


{
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}

public double distance(MyPoint another)


{

Dept. of CSE, AJIET, Mangalore 43


int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}

public double distance() {


return Math.sqrt(this.x*this.x + this.y*this.y);
}

public int getX()


{
return x;
}

public void setX(int x)


{
this.x = x;
}

public int getY()


{
return y;
}

public void setY(int y)


{
this.y = y;
}

public void setXY(int x, int y)


{
this.x = x;
this.y = y;
}
public int[] getXY() {
int[] coord = new int[2];
coord[0] = this.x;
coord[1] = this.y;
return coord;
}

public String toString()


{
return "(" + x + ", " + y + ")";
}
}

public class Point {

Dept. of CSE, AJIET, Mangalore 44


public static void main(String[] args) {
// TODO Auto-generated method stub
//MyPoint p1 = new MyPoint(3, 0);

MyPoint p1 = new MyPoint(); // Test constructor


System.out.println(p1); // Test toString()
p1.setX(8); // Test setters
p1.setY(6);
System.out.println("x is: " + p1.getX()); // Test getters
System.out.println("y is: " + p1.getY());
p1.setXY(3, 0); // Test setXY()
System.out.println(p1.getXY()[0]); // Test getXY()
System.out.println(p1.getXY()[1]);
System.out.println(p1);

MyPoint p2 = new MyPoint(0, 4);


System.out.println(p1.distance());
System.out.println(p1.distance(p2)); // which version?
System.out.println(p1.distance(5, 6)); // which version?

OUTPUT:

(0, 0)
x is: 8
y is: 6
3
0
(3, 0)
3.0
5.0
6.324555320336759

RESULT:
Java programs to demonstrate the decision-making statements and loops constructs was
successfully written and executed using Eclipse IDE and the result was verified.

Dept. of CSE, AJIET, Mangalore 45


Viva Questions:

1Java Program to Display Even Numbers from 1 to 10

2. java program to input weekday number to calculate the weekday name

Dept. of CSE, AJIET, Mangalore 46


PROGRAM 5:

OBJECT ORIENTED CONCEPTS

Aim: Demonstrate the core object-oriented concept of Inheritance, polymorphism

OBJECT ORIENTED PROGRAMMING (OOPs) CONCEPT

Object-oriented programming is a core of Java Programming, which is used for designing a


program using classes and objects. This can also be characterized as data controlling for
accessing the code. In this type of approach, programmers define the data type of a data
structure and the operations that are applied to the data structure.

OOPs in java is to improve code readability and reusability by defining a Java program
efficiently. The main principles of object-oriented programming are abstraction,
encapsulation, inheritance, and polymorphism. These concepts aim to implement real-world
entities in programs.
List of OOPs Concepts in Java
 Objects
 Classes
 Abstraction
 Inheritance
 Polymorphism
 Encapsulation

1. ABSTRACTION
Abstraction is a process which displays only the information needed and hides the unnecessary
information. The main purpose of abstraction is data hiding. Abstraction means selecting data
from a large number of data to show the information needed, which helps in reducing
programming complexity and efforts.
There are also abstract class and abstract methods. An abstract class is a type of class that
declares one or more abstract methods. An abstract method is a method that has a method
definition but not implementation. Once the object is modelled using data abstraction, the same
sets of data can also be used in different applications—abstract classes, generic types of
behaviours and object-oriented programming hierarchy. Abstract methods are used when two
or more subclasses do the same task in different ways and through different implementations.
An abstract class can have both the methods, i.e., abstract methods and regular methods.

2. INHERITANCE
Inheritance is a method in which one object acquires/inherits another object’s properties, and
inheritance also supports hierarchical classification. The idea behind this is that we can create
new classes built on existing classes, i.e., when you inherit from an existing class, we can reuse
methods and fields of the parent class. Inheritance represents the parent-child relationship. To
know more about this concept check the free inheritance in java course.

Dept. of CSE, AJIET, Mangalore 47


For example, a whale is a part of the classification of marine animals, which is part of class
mammal, which is under that class of animal. We use hierarchical classification, i.e., top-down
classification. If we want to describe a more specific class of animals such as mammals, they
would have more specific attributes such as teeth; cold-blooded, warm-blooded, etc. This
comes under the subclass of animals whereas animals come under the superclass. The subclass
is a class which inherits properties of the superclass. This is also called a derived class. A
superclass is a base class or parental class from which a subclass inherits properties.
We use inheritance mainly for method overriding:
To inherit a class, we use the extend keyword.

There are five types of inheritance single, multilevel, multiple, hybrid and hierarchical.
 Single level
In this one class i.e., the derived class inherits properties from its parental class. This enables
code reusability and also adds new features to the code. Example: class B inherits properties
from class A. Class A is the base or parental class and class B is the derived class.

 Multilevel
This one class is derived from another class which is also derived from another class i.e., this
class has more than one parental class, hence it is called multilevel inheritance.
 Hierarchical level
In this one parental class has two or more derived classes or we can say that two or more child
classes has one parental class.
 Hybrid inheritance
This is the combination of multiple and multilevel inheritance and in java multiple inheritance
is not supported as it leads to ambiguity and this type of inheritance can only be achieved
through interfaces.
Consider that class a is the parental or base class of class b and class c and in turn class b and
class c are parental or base class of class d. Class b and class c are derived classes from class a
and class d is derived class from class b and class c.
Single level Multilevel
Class a { Class a {
… ….
} }
Class b extends class a { Class b extends class a {
… ….
} }
Class c extends class b {

}
Hierarchical level
Class a {

}

Dept. of CSE, AJIET, Mangalore 48


Class b extends class a {
..
}
Class c extends class a {
..
}

3. POLYMORPHISM
Polymorphism refers to many forms, or it is a process that performs a single action in different
ways. It occurs when we have many classes related to each other by inheritance.
Polymorphism is of two different types, i.e., compile-time polymorphism and runtime
polymorphism. One of the examples in Compile time polymorphism is that when we overload
a static method in java. Run time polymorphism is also called a dynamic method dispatch is
a method in which a call to an overridden method is resolved at run time rather than compile
time. In this method, the overridden method is always called through the reference variable.
By using method overloading and method overriding, we can perform polymorphism.
Generally, the concept of polymorphism is often expressed as one interface, multiple
methods. This reduces complexity by allowing the same interface to be used as a general class
of action.

4. ENCAPSULATION
Encapsulation is one of the concepts in OOPs concepts; it is the process that binds together the
data and code into a single unit and keeps both from being safe from outside interference and
misuse. In this process, the data is hidden from other classes and can be accessed only through
the current class’s methods. Hence, it is also known as data hiding. Encapsulation acts as a
protective wrapper that prevents the code and data from being accessed by outsiders. These are
controlled through a well-defined interface.
Encapsulation is achieved by declaring the variables as private and providing public setter and
getter methods to modify and view the variable values. In encapsulation, the fields of a class
are made read-only or write-only. This method also improves the re-usability. Encapsulated
code is also easy to test for unit testing.

Advantages of OOPs Concept


Some of the advantages are:
 Re-usability
When we say re-usability, it means that “write once, use it multiple times” i.e., reusing some
facilities rather than building it again and again, which can be achieved by using class. We can
use it n number of times whenever required.
 Data redundancy
It is one of the greatest advantages in oops. This is the condition which is created at the data
storage when the same piece of data is held at two different places. If we want to use a similar
functionality in multiple classes, we can just write common class definitions for the similar
functionalities by inheriting them.
 Code maintenance
It is easy to modify or maintain existing code as new objects which can be created with small
differences from the existing ones. This helps users from doing rework many times and
modifying the existing codes incorporating new changes to it.
 Security

Dept. of CSE, AJIET, Mangalore 49


Data hiding and abstraction are used to filter out limited exposure which means we are
providing only necessary data to view as we maintain security.
 Design benefits
The designers will have a longer and extensive design phase, which results in better designs.
At a point of time when the program has reached critical limits, it will be easier to program all
non oops one separately.
 Easy troubleshooting
Using encapsulation objects are self-constrained. So, if developers face any problem easily it
can be solved. And there will be no possibility of code duplicity.
 Flexibility
 Problem solving

Disadvantages of OOPs Concept


 Effort – Lot of work is put into creating these programs.
 Speed – These programs are slower compared to other programs.
 Size – OOPs programs are bigger when compared to other programs.

Dept. of CSE, AJIET, Mangalore 50


PROGRAM 5:

Develop a JAVA program to create a class named shape. Create three sub classes
namely: circle, triangle and square, each class has two member functions named draw
() and erase (). Demonstrate polymorphism concepts by developing suitable methods,
defining member data and main program.

package employee;

class Shapes {
public void draw() {
System.out.println("Drawing a shape");
}

void erase Shape() {


}
}

class Triangle extends Shapes {


public void draw() {
System.out.println("Triangle is ½ * base * height ");
}

public void erase Shape() {

System.out.println("Triangle. Erase()");
}
}

class Circle extends Shapes {


public void draw() {
System.out.println("Circle is 3.14 * radius * radius ");
}

public void erase Shape() {

System.out.println("Circle. Erase()");
}
}

class square extends Shapes {


public void draw() {
System.out.println("Drawing a square ");
}

public void erase Shape() {

System.out.println("square. Erase()");
}

Dept. of CSE, AJIET, Mangalore 51


}

public class Point {

public static void main(String[] args) {


Shapes myShape = new Shapes(); // Create a Shapes object
Shapes myTriangle = new Triangle(); // Create a Triangle object
Shapes myCircle = new Circle(); // Create a Circle object
square mysquare = new square(); // Create a square object
myShape.draw();
myTriangle.draw();
myShape.draw();
myCircle.draw();
mysquare.draw();
myTriangle.eraseShape();
myShape.eraseShape();
myCircle.eraseShape();
mysquare.eraseShape();
}

OUTPUT:

Drawing a shape
Triangle is ½ * base * height
Drawing a shape
Circle is 3.14 * radius * radius
Drawing a square
Triangle.erase()
Circle.erase()
square.erase()

RESULT:
Java program to demonstrate the core object-oriented concept of Inheritance, polymorphism
was written and executed using Eclipse IDE and the result was verified.

Dept. of CSE, AJIET, Mangalore 52


Viva Questions:

1. Write a program to design Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

2. Loop through the elements of an ArrayList with a for loop, and use the size()
method to specify how many times the loop should run:

Dept. of CSE, AJIET, Mangalore 53


PROGRAM 6:

ABSTRACT CLASS IN JAVA

Aim: Introduce concepts of abstract class in Java

1. ABSTRACTION

Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. The trivial or the non-essential units are not displayed to the user. Ex: A car is viewed
as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviours of an
object differentiate it from other objects of similar type and also help in classifying/grouping
the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of a car or applying brakes will stop the car, but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in
the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.

Abstract classes and Abstract methods:


1. An abstract class is a class that is declared with an abstract keyword.
2. An abstract method is a method that is declared without implementation.
3. An abstract class may or may not have all abstract methods. Some of them can be
concrete methods
4. A method-defined abstract must always be redefined in the subclass, thus
making overriding compulsory or making the subclass itself abstract.
5. Any class that contains one or more abstract methods must also be declared with an
abstract keyword.
6. There can be no object of an abstract class. That is, an abstract class cannot be
directly instantiated with the new operator.
7. An abstract class can have parameterized constructors and the default constructor
is always present in an abstract class.

When to use abstract classes and abstract methods with an example


There are situations in which we will want to define a superclass that declares the structure of
a given abstraction without providing a complete implementation of every method. Sometimes
we will want to create a superclass that only defines a generalization form that will be shared
by all of its subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design system or game
simulation. The base type is “shape” and each shape has a color, size, and so on. From this,
specific types of shapes are derived(inherited)-circle, square, triangle, and so on — each of
which may have additional characteristics and behaviours. For example, certain shapes can be
flipped. Some behaviours may be different, such as when you want to calculate the area of a
shape. The type hierarchy embodies both the similarities and differences between the shapes.

Dept. of CSE, AJIET, Mangalore 54


1. ABSTRACT CLASSES
An abstract is a java modifier applicable for classes and methods in java but not for
Variables.

In java, the following some important observations about abstract classes are as follows:
1. An instance of an abstract class cannot be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract method.
4. There can be a final method in abstract class but any abstract method in
class(abstract class) cannot be declared as final or in simpler terms final method
cannot be abstract itself as it will yield an error: “Illegal combination of modifiers:
abstract and final”
5. We can define static methods in an abstract class
6. We can use the abstract keyword for declaring top-level classes (Outer class) as
well as inner classes as abstract
7. If a class contains at least one abstract method then compulsory should declare a
class as abstract
8. If the Child class is unable to provide implementation to all abstract methods of
the Parent class, then we should declare that Child class as abstract so that the
next level Child class should provide implementation to the remaining abstract
method

2. ABSTRACT METHOD

Sometimes, just method declaration is required in super-classes. This can be achieved by


specifying the abstract type modifier. These methods are sometimes referred to as subclasser
responsibility because they have no implementation specified in the super-class. Thus, a
subclass must override them to provide method definition. To declare an abstract method, use
this general form:

abstract type method-name(parameter-list);


As you can see, no method body is present. Any concrete class(i.e. class without abstract
keyword) that extends an abstract class must override all the abstract methods of the class.

Dept. of CSE, AJIET, Mangalore 55


Important rules for abstract methods:
 Any class that contains one or more abstract methods must also be declared abstract
 The following are various illegal combinations of other modifiers for methods with
respect to abstract modifier:
1. final
2. abstract native
3. abstract synchronized
4. abstract static
5. abstract private
6. abstract strictfp

PROGRAM 6:

Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that
extend the Shape class and implement the respective methods to calculate the area and
perimeter of each shape.

package employee;

abstract class Shapes {


public abstract double calculateArea();
public abstract double calculatePerimeter();
}
class Circle extends Shapes {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

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

@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

class Triangle extends Shapes {


private double side1;
private double side2;
private double side3;

public Triangle(double side1, double side2, double side3) {

Dept. of CSE, AJIET, Mangalore 56


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

@Override
public double calculateArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
public double calculatePerimeter() {
return side1 + side2 + side3;
}
}

public class Point {

public static void main(String[] args) {


double r = 4.0;
Circle = new Circle(r);
double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;
Triangle = new Triangle(ts1, ts2, ts3);
System.out.println("Radius of the Circle"+r);
System.out.println("Area of the Circle: " + circle.calculateArea());
System.out.println("Perimeter of the Circle: " + circle.calculatePerimeter());
System.out.println("\nSides of the Triangle are: "+ts1+','+ts2+','+ts3);
System.out.println("Area of the Triangle: " + triangle.calculateArea());
System.out.println("Perimeter of the Triangle: " + triangle.calculatePerimeter());
}

OUTPUT:
Radius of the Circle4.0
Area of the Circle: 50.26548245743669
Perimeter of the Circle: 25.132741228718345

Sides of the Traiangel are: 3.0,4.0,5.0


Area of the Triangle: 6.0
Perimeter of the Triangle: 12.0

Dept. of CSE, AJIET, Mangalore 57


RESULT:

Java program to introduce concepts of abstract class was successfully written and executed
using Eclipse IDE and the result is verified

Viva Questions

1. Write output for below code:

2. Explain Constructor Chaining In Java with Examples

Dept. of CSE, AJIET, Mangalore 58


PROGRAM 7:
INTERFACE

Aim: Introduce the concept of interface.


3. INTERFACE

An Interface in Java programming language is defined as an abstract type used to specify the
behaviour of a class. An interface in Java is a blueprint of a class. A Java interface contains
static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction
and multiple inheritance in Java. In other words, interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents the IS-A relationship.
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
 Interfaces specify what a class must do and not how. It is the blueprint of the class.
 An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So, it specifies
a set of methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
 A Java library example is Comparator Interface. If a class implements this interface,
then it can be used to sort a collection.
Syntax:
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total abstraction. That
means all the methods in an interface are declared with an empty body and are public and all
fields are public, static, and final by default. A class that implements an interface must
implement all the methods declared in the interface. To implement interface use implements
keyword.
Why do we use an Interface?
 It is used to achieve total abstraction.
 Since java does not support multiple inheritances in the case of class, by using an
interface it can achieve multiple inheritances.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public and static

Dept. of CSE, AJIET, Mangalore 59


 First, we define an interface "Resizable" with the methods resizeWidth(int width) and
resizeHeight(int height) to allow an object to be resized.
 The "Rectangle" class implements the Resizable interface and provides its own
implementations of the resize methods. It also has a printSize() method to display the
current rectangle size.
 In the main() method, we create an instance of the "Rectangle" class and display its
size. Then, we call the resizeWidth() and resizeHeight() methods to change the
rectangle size.
 Finally, we print the updated size.

Flowchart of Resizable Java:

Flowchart of Rectangle Java:

Flowchart of Main Java:

Dept. of CSE, AJIET, Mangalore 60


PROGRAM 7:

Develop a JAVA program to create an interface Resizable with methods


resizeWidth(int width) and resizeHeight(int height) that allow an object to be resized.
Create a class Rectangle that implements the Resizable interface and implements the
resize methods

package employee;

//Resizable.java
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

//Rectangle.java
class Rectangle implements Resizable {
private int width;
private int height;

public Rectangle(int width, int height) {


this.width = width;
this.height = height;
}

public void resizeWidth(int width) {


this.width = width;
}

public void resizeHeight(int height) {


this.height = height;
}

Dept. of CSE, AJIET, Mangalore 61


public void printSize() {
System.out.println("Width: " + width + ", Height: " + height);
}
}

public class Point {

public static void main(String[] args) {


Rectangle = new Rectangle(100, 150);
rectangle.printSize();

rectangle.resizeWidth(150);
rectangle.resizeHeight(200);
rectangle.printSize();
}

OUTPUT:
Width: 100, Height: 150
Width: 150, Height: 200

RESULT:
Java program to Introduce the concept of interface was written and successfully executed using
eclipse IDE and the result was verified.

Viva Questions

1. How to create a package in java?

Dept. of CSE, AJIET, Mangalore 62


2. What is the main objective of garbage collection?

3. What do you understand by Object Cloning and how do you achieve it in Java?

Dept. of CSE, AJIET, Mangalore 63


PROGRAM 8:

INNER CLASS IN JAVA

Aim: Introduction to Inner class in java

In Java, inner class refers to the class that is declared inside class or interface which were
mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented
so bringing it closer to the real world. Now geeks you must be wondering why they were
introduced?
There are certain advantages associated with inner classes are as follows:
 Making code clean and readable.
 Private methods of the outer class can be accessed, so bringing a new dimension
and making it closer to the real world.
 Optimizing the code module.

Types of Inner Classes


There are basically four types of inner classes in java.
1. Nested Inner Class
2. Method Local Inner Classes
3. Static Nested Classes
4. Anonymous Inner Classes

PROGRAM 8:

Develop a JAVA program to create an outer class with a function display. Create another
class inside the outer class named inner with a function called display and call the two
functions in the main class.

package employee;

class Outer {
// Method defined inside outer class
void display()
{

// Print statement
System.out.println("inside outerMethod");
}
// Class 2
// Simple nested inner class
class Inner {

// show() method of inner class


public void display()

Dept. of CSE, AJIET, Mangalore 64


{

// Print statement
System.out.println("In a nested class method");
}
}
}
public class Point {

public static void main(String[] args) {


// Note how inner class object is created inside
// main()
Outer.Inner in = new Outer().new Inner();

// Calling show() method over above object created


in.display();
// Creating object of outer class inside main()
// method
Outer x = new Outer();
x.display();
}

OUTPUT

In a nested class method


inside outerMethod

Viva Questions:

1. Write a java program to check whether a given string is palindrome.

Dept. of CSE, AJIET, Mangalore 65


2. To create an abstract class named shape that contains two integers and an empty
method named printArea .Provide three classes named Rectangle ,Triangle and Circle
subclass that each one of the classes extends the Class Shape .Each one of the classes
contains only the method printArea() that prints the area of Shape.

Dept. of CSE, AJIET, Mangalore 66


PROGRAM 9:
EXCEPTION HANDLING

Aim: Exception handling in java, introduction to throwable class, throw, throws,


finally.

THEORY:
Exception Handling in Java is one of the effective means to handle the runtime errors so that
the regular flow of the application can be preserved. Java Exception Handling is a mechanism
to handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e., at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains information
about the exception, such as the name and description of the exception and the state of the
program when the exception occurred.

Major reasons why an exception Occurs


 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle errors.
Let us discuss the most important part which is the differences between Error and
Exception that is as follows:
 Error: An Error indicates a serious problem that a reasonable application should
not try to catch.
 Exception: Exception indicates conditions that a reasonable application might try
to catch.

Exception Hierarchy
All exception and error types are subclasses of class Throwable, which is the base class of the
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch. NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to
do with the run-time environment itself(JRE). StackOverflowError is an example of such an
error.

Dept. of CSE, AJIET, Mangalore 67


Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.

How Programmer Handles an Exception?


Customized Exception Handling: Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program
statements that you think can raise exceptions are contained within a try block. If an exception
occurs within the try block, it is thrown. Your code can catch this exception (using catch block)
and handle it in some rational manner. System-generated exceptions are automatically thrown
by the Java run-time system. To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such by a throws clause. Any
code that absolutely must be executed after a try block completes is put in a finally block.

How to Use the try-catch Clause?


try {
// block of code to monitor for errors
// the code you think can raise an exception
} catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2

Dept. of CSE, AJIET, Mangalore 68


}
// optional
finally { // block of code to be executed after try block ends
}
Certain below key points are needed to be remembered that are as follows:
 In a method, there can be more than one statement that might throw an exception,
So put all these statements within their own try block and provide a separate
exception handler within their own catch block for each of them.
 If an exception occurs within the try block, that exception is handled by the
exception handler associated with it. To associate the exception handler, we must
put a catch block after it. There can be more than one exception handlers.
Each catch block is an exception handler that handles the exception to the type
indicated by its argument. The argument, ExceptionType declares the type of
exception that it can handle and must be the name of the class that inherits from
the Throwable class.
 For each try block, there can be zero or more catch blocks, but only one final block.
 The finally block is optional. It always gets executed whether an exception occurred
in try block or not. If an exception occurs, then it will be executed after try and
catch blocks. And if an exception does not occur, then it will be executed after
the try block. The finally block in java is used to put important codes such as clean
up code e.g., closing the file or closing the connection.
The summary is depicted via visual aid below as follows:

Using custom exception class

In this approach, we will implement a custom class or a class created by a programmer to


handle divide by exception in java. Steps we follow in this approach are as follows −

 We initialize two numbers for numerator and denominator. Denominator value is


initialised with zero.

Dept. of CSE, AJIET, Mangalore 69


 We create a custom class for divide by zero exception which extends exception class
 In try block we explicitly throw the exception and call custom class using catch block
to handle the exception.

we created a ‘DivideByZeroException’ custom class and extends ‘Exception’. This class


handles the exception caused by dividing by zero. When an exception is caused in main
method we call the custom class using ‘throw’ keyword by creating an object to the class
using ‘new; keyword.

PROGRAM 9:

Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
package employee;
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
public class Point {

public static void main(String[] args) {


int numerator = 15;
int denominator = 2;
try {
if (denominator == 0) {
throw new DivideByZeroException("Error: Cannot divide a number by
zero.");
}
int answer = numerator / denominator;
System.out.println("Result: " + answer);
} catch (DivideByZeroException ex) {
System.out.println(ex.getMessage());
}
finally {
System.out.println("I am in final block");
}
}

OUTPUT 1 :
Result: 7
I am in final block

OUTPUT 2 :

Dept. of CSE, AJIET, Mangalore 70


Error: Cannot divide a number by zero.
I am in final block

RESULT:
Java program to handle Exception in java, introduction to throwable class, throw, throws,
finally was successfully written and executed using the Eclipse IDE and the result was
verified

Viva Questions:

1. Write a program to print the exception information using printStackTrace()


method

2. Java Program to Demonstrate Need of try-catch Clause

Dept. of CSE, AJIET, Mangalore 71


PROGRAM 10:
JAVA PACKAGES

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
 Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
 Providing controlled access: protected and default have package level access
control. A protected member is accessible by classes in the same package and its
subclasses. A default member (without any access specifier) is accessible by classes
in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an import
class from existing packages and use it in our program. A package is a container of a group of
related classes where some of the classes are accessible are exposed and others are kept for
internal purpose.
We can reuse existing classes from the packages as many times as we need it in our program.

How packages work?


Package names and directory structure are closely related. For example, if a package name
is college.staff.cse, then there are three directories, college, staff and cse such that cse is
present in staff and staff is present college. Also, the directory college is accessible
through CLASSPATH variable, i.e., path of parent directory of college is present in
CLASSPATH.
The idea is to make sure that classes are easy to locate.

Package naming conventions: Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is
college.tech.cse, college.tech.ee, college.art.history, etc.

Adding a class to a Package: We can add more classes to a created package by using package
name at the top of the program and saving it in the package directory. We need a new java file
to define a public class, otherwise we can add the new class to an existing .java file and
recompile it.
Subpackages: Packages that are inside another package are the subpackages. These are not
imported by default; they have to imported explicitly. Also, members of a subpackage have no
access privileges, i.e., they are considered as different package for protected and default access
specifiers.

Types of packages:

Dept. of CSE, AJIET, Mangalore 72


Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:

1. java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2. java.io: Contains classed for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4. java.applet: Contains classes for creating Applets.
5. java.awt: Contain classes for implementing the components for graphical user interfaces
(like button, menus etc).
6. java.net: Contain classes for supporting networking operations.

User-defined packages
These are the packages that are defined by the user. First, we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.
How to Create a package?
Creating a package is a simple task as follows

 Choose the name of the package


 Include the package command as the first line of code in your Java Source File.
 The Source file contains the classes, interfaces, etc you want to include in the
package
 Compile to create the Java packages

Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
package employee2;

public class pack {

// TODO Auto-generated method stub


public void msg(){
System.out.println("Hello");

Dept. of CSE, AJIET, Mangalore 73


} }

package employee;
import employee2.pack;
public class Point {

public static void main(String[] args) {


pack obj = new pack();
obj.msg();
}

OUTPUT:
Hello

RESULT:

VIVA QUESTIONS:

1. Explain the usage of Java packages.

2. What is a predefined package in Java?

Dept. of CSE, AJIET, Mangalore 74


3. Predict the output of following Java program

4. With an example Java code show the use of super keyword with variables

Dept. of CSE, AJIET, Mangalore 75


PROGRAM 11:
THREADS

Aim: Demonstrate creation of threads using Thread class and Runnable interface,
multi-threaded programming.

THEORY:
Typically, threads can be defined as a subprocess with lightweight with the smallest unit of
processes and also has separate paths of execution. These threads use shared memory but they
act independently hence if there is an exception in threads that do not affect the working of
other threads despite them sharing the same memory.

Threads in a Shared Memory Environment in OS

In the above diagram a thread runs inside the process and there will be context-based switching
between threads there can be multiple processes running in OS, and each process again can
have multiple threads running simultaneously. The Multithreading concept is popularly applied
in games, animation…etc.
The Concept of Multitasking
To help users, Operating System accommodates users the privilege of multitasking, where
users can perform multiple actions simultaneously on the machine. This Multitasking can be
enabled in two ways:
1. Process-Based Multitasking
2. Thread-Based Multitasking

1. Process-Based Multitasking (Multiprocessing)


In this type of Multitasking, processes are heavyweight and each process was allocated by a
separate memory area. And as the process is heavyweight the cost of communication between
processes is high and it takes a long time for switching between processes as it involves actions
such as loading, saving in registers, updating maps, lists, etc.
2. Thread-Based Multitasking
As we discussed above Threads are provided with lightweight nature and share the same
address space, and the cost of communication between threads is also low.
Why Threads are used?

Dept. of CSE, AJIET, Mangalore 76


Now, we can understand why threads are being used as they had the advantage of being
lightweight and can provide communication between multiple threads at a Low Cost
contributing to effective multi-tasking within a shared memory environment.
Life Cycle of Thread
There are different states Thread transfers into during its lifetime, let us know about those states
in the following lines: in its lifetime, a thread undergoes the following states, namely:
1. New State
2. Active State
3. Waiting/Blocked State
4. Timed Waiting State
5. Terminated State

We can see the working of different states in a Thread in the above Diagram.
1. New State
By default, a Thread will be in a new state, in this state, code has not yet been run and the
execution process is not yet initiated.
2. Active State
A Thread that is a new state by default gets transferred to Active state when it invokes the
start() method, his Active state contains two sub-states namely:
 Runnable State: In This State, The Thread is ready to run at any given time and
it’s the job of the Thread Scheduler to provide the thread time for the runnable state
preserved threads. A program that has obtained Multithreading shares slices of time
intervals which are shared between threads hence, these threads run for some short

Dept. of CSE, AJIET, Mangalore 77


span of time and wait in the runnable state to get their schedules slice of a time
interval.
 Running State: When the Thread Receives CPU allocated by Thread Scheduler, it
transfers from the “Runnable” state to the “Running” state. and after the expiry of
its given time slice session, it again moves back to the “Runnable” state and waits
for its next time slice.

3. Waiting/Blocked State
If a Thread is inactive but on a temporary time, then either it is at waiting or blocked state, for
example, if there are two threads, T1 and T2 where T1 need to communicate to the camera and
other thread T2 already using a camera to scan then T1 waits until T2 Thread completes its
work, at this state T1 is parked in waiting for the state, and in another scenario, the user called
two Threads T2 and T3 with the same functionality and both had same time slice given by
Thread Scheduler then both Threads T1, T2 is in a blocked state. When there are multiple
threads parked in Blocked/Waiting state Thread Scheduler clears Queue by rejecting unwanted
Threads and allocating CPU on a priority basis.
4. Timed Waiting State
Sometimes the longer duration of waiting for threads causes starvation, if we take an example
like there are two threads T1, T2 waiting for CPU and T1 is undergoing Critical Coding
operation and if it does not exit CPU until its operation gets executed then T2 will be exposed
to longer waiting with undetermined certainty, In order to avoid this starvation situation, we
had Timed Waiting for the state to avoid that kind of scenario as in Timed Waiting, each thread
has a time period for which sleep() method is invoked and after the time expires the Threads
starts executing its task.
5. Terminated State
A thread will be in Terminated State, due to the below reasons:
 Termination is achieved by a Thread when it finishes its task Normally.
 Sometimes Threads may be terminated due to unusual events like segmentation
faults, exceptions…etc. and such kind of Termination can be called Abnormal
Termination.
 A terminated Thread means it is dead and no longer available.
What is Main Thread?
As we are familiar that, we create Main Method in each and every Java Program, which acts
as an entry point for the code to get executed by JVM, similarly in this Multithreading Concept,
Each Program has one Main Thread which was provided by default by JVM, hence whenever
a program is being created in java, JVM provides the Main Thread for its Execution.
How to Create Threads using Java Programming Language?
We can create Threads in java using two ways, namely:
1. By extending Thread Class
2. By Implementing a Runnable interface

1. By Extending Thread Class


We can run Threads in Java by using Thread Class, which provides constructors and methods
for creating and performing operations on a Thread, which extends a Thread class that can
implement Runnable Interface. We use the following constructors for creating the Thread:
 Thread
 Thread(Runnable r)

Dept. of CSE, AJIET, Mangalore 78


 Thread(String name)
 Thread(String name, Runnable r)

PROGRAM 11:
Write a program to illustrate creation of threads using runnable class. (start method start
each of the newly created thread. Inside the run method there is sleep() for suspend the
thread for 500 milliseconds).

import java.util.Random;
import java.util.Scanner;
class randThread extends Thread
{
Random rm=new Random();
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Random no. : "+rm.nextInt(100));
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
class squareThread extends Thread
{
int num;
squareThread(int n)
{
num=n;
}
public void run()
{
for(int i=1;i<+num;i++)
System.out.println("square of "+i+"-"+(i*i));
}
}
class cubeThread extends Thread
{
int num;
cubeThread(int n)
{
num=n;
}

Dept. of CSE, AJIET, Mangalore 79


public void run()
{
for(int i=1;i<=num;i++)
System.out.println("Cube of "+i+"-"+i*i*i);
}
}
public class Threaddemo{
public static void main(String[] args) throws InterruptedException {
System.out.println("Enter the value of n");
int n=new Scanner(System.in).nextInt();
randThread t1=new randThread();
squareThread t2=new squareThread(n);
cubeThread t3=new cubeThread(n);
t1.start();
t2.start();
t3.start();
}
}

OUTPUT

Enter the value of n


10
square of 1-1
square of 2-4
square of 3-9
square of 4-16
square of 5-25
square of 6-36
square of 7-49
square of 8-64
square of 9-81
Cube of 1-1
Cube of 2-8
Cube of 3-27
Cube of 4-64
Cube of 5-125
Cube of 6-216
Cube of 7-343
Random no. : 88
Cube of 8-512
Cube of 9-729
Cube of 10-1000
Random no. : 34
Random no. : 10
Random no. : 73
Random no. : 46
Random no. : 18
Random no. : 99

Dept. of CSE, AJIET, Mangalore 80


Random no. : 99
Random no. : 73
Random no. : 4

RESULT:
Java program to demonstrate creation of threads using Thread class and Runnable interface,
multi-threaded programming was successfully written and executed using eclipse IDE and the
result was verified.

VIVA QUESTIONS

1) What is multithreading?

2) What is thread?

3)What is the difference between preemptive scheduling and time slicing?

4)What does join() method?

5) Is it possible to start a thread twice?

6) Can we call the run() method instead of start()?

Dept. of CSE, AJIET, Mangalore 81


PROGRAM 12:
THREAD AND CONSTRUCTOR
This program create a class called My Thread. In this class a constructor calls the base class
constructor using super and starts the thread. The run method of the class starts after this. Here
we can observed that both main thread and creation of child thread are executed concurrently.

Java provides built-in support for multithreaded programming. A multi-threaded program


contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution.
When a Java program starts up, one thread begins running immediately. This is usually called
the main thread of our program because it is the one that is executed when our program begins.
There are certain properties associated with the main thread which are as follows:
 It is the thread from which other “child” threads will be spawned.
 Often, it must be the last thread to finish execution because it performs various
shutdown actions

The flow diagram is as follows:

Dept. of CSE, AJIET, Mangalore 82


How to control Main thread
The main thread is created automatically when our program is started. To control it we must
obtain a reference to it. This can be done by calling the method currentThread( ) which is
present in Thread class. This method returns a reference to the thread on which it is called. The
default priority of Main thread is 5 and for all remaining user threads priority will be inherited
from parent to child.
create a Java program that demonstrates concurrent execution using threads. In this example,
we'll create a class MyThread that extends the Thread class. The constructor of MyThread will
call the base class constructor using super, and the run method will define the behavior of the
child thread. The main thread will also run concurrently with the child thread.
In this program:
We create a MyThread class that extends the Thread class.
In the MyThread constructor, we call the base class constructor using super(threadName) and
pass a name for the child thread.

Dept. of CSE, AJIET, Mangalore 83


The run method in MyThread defines the behavior of the child thread, which will count from
1 to 5, printing its name and count value.
In the main method, we create an instance of MyThread (the child thread) and start it using
start().
The main thread runs concurrently with the child thread, counting from 1 to 5.

PROGRAM 12:
Develop a program to create a class MyThread in this class a constructor, call the base
class constructor, using super and start the thread. The run method of the class starts
after this. It can be observed that both main thread and created child thread are
executed concurrently.

// Online Java Compiler


// Use this editor to write, compile and run your Java code online
class MyThread extends Thread {
public MyThread(String threadName) {
super(threadName); // Call the base class (Thread) constructor with a thread name
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + ": Count " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println(getName() + " has finished.");
}
}
class HelloWorld {
public static void main(String[] args) {
MyThread childThread = new MyThread("Child Thread");
childThread.start(); // Start the child thread

// Main thread behavior


for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread: Count " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println("Main Thread has finished.");

Dept. of CSE, AJIET, Mangalore 84


}
}

OUTPUT 1:
Main Thread: Count 1Child Thread: Count 1
Main Thread: Count 2
Child Thread: Count 2
Main Thread: Count 3
Child Thread: Count 3Main Thread: Count 4
Child Thread: Count 4
Main Thread: Count 5
Child Thread: Count 5
Main Thread has finished.
Child Thread has finished.

RESULT:
This program demonstrates the concurrent execution of the main thread and the child
thread.

VIVA QUESTIONS:

1. Write program demonstrating how to create a file in Java

2.What is the difference between Collection and Collections?

3.Write program demonstrating how to read contents from a file in Java

4. write program to display image in applet

Dept. of CSE, AJIET, Mangalore 85


ADDITIONAL PRACTICE PROGRAMS

1. Write a Java program to generate a Fibonacci series.


2. Write a Java program to reverse a number
3. Write a Java program to display even numbers from 1 to 100
4. Write a Java program to find the sum of first n natural numbers.
5. Write a Java Program to print the duplicate elements of an array
6. Write a Java Program to sort the elements of an array in ascending order
7. Create a class named 'Student' with String variable 'name' and integer variable 'roll_no'.
Assign the value of roll_no as '2' and that of name as "John" by creating an object of
the class Student.
8. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5
units by creating a class named 'Triangle' without any parameter in its constructor.
9. Write a program to print the area of a rectangle by creating a class named 'Area' taking
the values of its length and breadth as parameters of its constructor and having a method
named 'returnArea' which returns the area of the rectangle. Length and breadth of
rectangle are entered through keyboard.
10. Print the sum, difference and product of two complex numbers by creating a class
named 'Complex' with separate methods for each operation whose real and imaginary
parts are entered by user.
11. Write a program that would print the information (name, year of joining, salary,
address) of three employees by creating a class named 'Employee'. The output should
be as follows:

Name Year of joining Address


Robert 1994 64C- WallsStreat
Sam 2000 68D- WallsStreat
John 1999 26B- WallsStreat

12. Create a class called Invoice that a hardware store might use to represent an invoice for
an item sold at the store. An Invoice should include four pieces of information as instance
variables‐a part number (type String), a part description (type String),a quantity of the item
being purchased (type int) and a price per item (double). Your class should have a constructor
that initializes the four instance variables. Provide a set and a get method for each instance
variable. In addition, provide a method named getInvoice Amount that calculates the invoice
amount (i.e., multiplies the quantity by the price per item), then returns the amount as a double
value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it
should be set to 0.0. Write a test application named InvoiceTest that demonstrates class
Invoice’s capabilities.
13. Create a class called Employee that includes three pieces of information as instance
variables—a first name (typeString), a last name (typeString) and a monthly salary (double).
Your class should have a constructor that initializes the three instance variables. Provide a set
and a get method for each instance variable. If the monthly salary is not positive, set it to 0.0.

Dept. of CSE, AJIET, Mangalore 86


Write a test application named EmployeeTest that demonstrates class Employee’s capabilities.
Create two Employee objects and display each object’s yearly salary. Then give each Employee
a 10% raise and display each Employee’s yearly salary again.

14. Create a class called Date that includes three pieces of information as instance
variables—a month (typeint), a day (typeint) and a year (typeint). Your class should have a
constructor that initializes the three instance variables and assumes that the values provided are
correct. Provide a set and a get method for each instance variable. Provide a method
displayDate that displays the month, day and year separated by forward slashes(/). Write a test
application named DateTest that demonstrates classDate’s capabilities.
15. Create class SavingsAccount. Usea static variable annualInterestRate to store the
annual interest rate for all account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has ondeposit. Provide
method calculateMonthlyInterest to calculate the monthly www.oumstudents.tk interest by
multiplying the savingsBalance by annualInterestRate divided by 12 this interest should be
added to savingsBalance. Provide a static method modifyInterestRate that sets the
annualInterestRate to a new value. Write a program to test class SavingsAccount. Instantiate
two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and $3000.00,
respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the
new balances for both savers. Then set the annualInterestRate to 5%, calculate the next month’s
interest and print the new balances for both savers.
16. Create a class called Book to represent a book. A Book should include four pieces of
information as instance variables‐a book name, an ISBN number, an author name and a
publisher. Your class should have a constructor that initializes the four instance variables.
Provide a mutator method and accessor method (query method) for each instance variable.
Inaddition, provide a method named getBookInfo that returns the description of the book as a
String (the description should include all the information about the book). You should use this
keyword in member methods and constructor. Write a test application named BookTest to
create an array of object for 30 elements for class Book to demonstrate the class Book's
capabilities.
17. Create MyOwnAutoShop class which contains the main() method. Perform the
following within the main() method. ◦Create an instance of Sedan class and initialize all the
fields with appropriate values. Use super(...) method in the constructor for initializing the fields
of the superclass. ◦Create two instances of the Ford class and initialize all the fields with
appropriate values. Use super(...) method in the constructor for initializing the fields of the
super class. www.oumstudents.tk ◦Create an instance of Car class and initialize all the fields
with appropriate values. Display the sale prices of all instance.
18. Write an applet that asks the user to enter two floating‐point numbers, obtains the two
numbers from the user and draws their sum, product (multiplication), difference and quotient
(division). Use the techniques shown in example.
19. Create an applet that can display the following component. No event handling is needed
for the components.

Dept. of CSE, AJIET, Mangalore 87


20. Create an applet that can display the following component. No event handling is
needed for the components.

21. Temperature Conversion:


a. Write a temperature conversion applet that converts from Fahrenheit to Celsius. The
Fahrenheit temperature should be entered from the keyboard (via a JTextField). A JLabel
should be used to display the converted temperature. Use the following formula for the
conversion: Celcius = ((5/9)*(Ferenheit‐32)).
b. Enhance the temperature conversion applet of Q1 by adding the Kelvin temperature
scale. The applet should also allow the user to make conversions between any two scales. Use
the following formula for the conversion between Kelvin and Celsius (in addition to the
formulain Q1): Kelvin = Celcius + 273.15

Dept. of CSE, AJIET, Mangalore 88

You might also like